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
<repo_name>gbacus/node3-weather-website<file_sep>/src/utils/forecast.js const request = require("request"); const forecast = (lat, lng, callback) => { const url = `https://api.darksky.net/forecast/5282f7a4d39f7f291e4017d5ce21ca5a/${lat},${lng}`; request({ url, json: true }, (error, { body }) => { if (error) { callback("Unable to connect to weather services", undefined); } else if (body.error) { callback("Unable to find location. Try another search.", undefined); } else { const { currently: { temperature, precipProbability }, daily: { data } } = body; callback( undefined, `${data[0].summary} It is currently ${temperature} with a ${precipProbability}% chance of rain. The high is ${data[0].temperatureHigh} and the low is ${data[0].temperatureLow}` ); } }); }; module.exports = forecast;
98772fb8033e2ec90bdb382bb073740fe4868524
[ "JavaScript" ]
1
JavaScript
gbacus/node3-weather-website
4cdcb3269e6aac9329001958120bf509150bf273
761047f1ec2a9de496a93d04eafaaf7bfce8b7d7
refs/heads/master
<repo_name>eskadah/birthday_reminder<file_sep>/app/br_days_before_view_controller.rb class BRDaysBeforeViewController <UITableViewController def viewDidLoad super backgroundView = UIImageView.alloc.initWithImage(UIImage.imageNamed 'app-background.png') tableView.backgroundView = backgroundView end def tableView(tableView, cellForRowAtIndexPath: indexPath) cell = tableView.dequeueReusableCellWithIdentifier('Cell') cell.textLabel.text = BRDSettings.sharedInstance.titleForDaysBefore(indexPath.row) cell.accessoryType = BRDSettings.sharedInstance.daysBefore == indexPath.row ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone cell end def tableView(tableView, numberOfRowsInSection: section) 8 end def tableView(tableView, didSelectRowAtIndexPath: indexPath) if indexPath.row == BRDSettings.sharedInstance.daysBefore return #tableView.deselectRowAtIndexPath(indexPath,animated:false) end oldIndexPath = NSIndexPath.indexPathForRow(BRDSettings.sharedInstance.daysBefore, inSection: 0) BRDSettings.sharedInstance.daysBefore = indexPath.row tableView.reloadRowsAtIndexPaths([oldIndexPath,indexPath],withRowAnimation:UITableViewRowAnimationNone) end end<file_sep>/app/br_blue_button.rb class BRBlueButton < UIButton # To change this template use File | Settings | File Templates. end<file_sep>/app/app_delegate.rb class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) story_board = UIStoryboard.storyboardWithName('MainStoryBoard1', bundle: NSBundle.mainBundle) root_controller = story_board.instantiateInitialViewController @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) @window.rootViewController =root_controller #root_controller.view.sizeToFit @window.makeKeyAndVisible BRStyleSheet.initStyles true end def applicationDidBecomeActive(application) UIApplication.sharedApplication.applicationIconBadgeNumber = 0 end end <file_sep>/Rakefile # -*- coding: utf-8 -*- $:.unshift("/Library/RubyMotion/lib") require 'motion/project/template/ios' begin require 'bundler' Bundler.require rescue LoadError end Motion::Project::App.setup do |app| # Use `rake config' to see complete project settings. app.name = 'birthdaytest' app.frameworks += ['CoreData','QuartzCore','AddressBook','Accounts','Social'] app.file_dependencies 'app/app_delegate.rb' => 'app/br_model.rb' app.file_dependencies 'app/br_home_view_controller.rb' => 'app/ui_image_view.rb' app.info_plist['FacebookAppID'] = '316689658473081' app.pods do pod 'Facebook-iOS-SDK' end end <file_sep>/app/br_core_view_controller.rb class BRCoreViewController < UIViewController def viewDidLoad super view.backgroundColor = UIColor.grayColor backgroundView = UIImageView.alloc.initWithImage(UIImage.imageNamed 'app-background.png') view.insertSubview(backgroundView, atIndex:0) end def cancelAndDismiss puts 'cancel' self.dismissModalViewControllerAnimated(true,completion:lambda {puts 'dismissed'}[]) end def saveAndDismiss puts 'saved' self.dismissViewControllerAnimated(true,completion:lambda {puts 'dismissed'}[]) end end<file_sep>/app/br_home_view_controller.rb class BRHomeViewController < BRCoreViewController attr_accessor :has_friends def viewDidLoad super @table_view = view.viewWithTag 1 @importView = view.viewWithTag 20 @addressBookButton = view.viewWithTag 21 @facebookButton = view.viewWithTag 22 @addressBookButton.addTarget(self, action:'importFromAddressBookTapped:',forControlEvents:UIControlEventTouchUpInside) @facebookButton.addTarget(self, action:'importFromFacebookTapped:',forControlEvents:UIControlEventTouchUpInside) @importLabel = view.viewWithTag 23 @addressBook = toolbarItems[1] @addressBook.target = self @addressBook.action ='importFromAddressBookTapped:' @facebook = toolbarItems[3] @facebook.target = self @facebook.action ='importFromFacebookTapped:' BRStyleSheet.styleLabel(@importLabel,withType:'BRLabelTypeLarge') end def has_friends=(flag) @has_friends = flag @importView.hidden = @has_friends @table_view.hidden = !@has_friends if navigationController.topViewController == self navigationController.setToolbarHidden(!@has_friends,animated:false) end end def viewWillAppear(animated) super puts 'home view will appear' @table_view.reloadData self.has_friends = fetchedResultsController.fetchedObjects.count > 0 #BRDModel.sharedInstance.updateCachedBirthdays NSNotificationCenter.defaultCenter.addObserver(self, selector: 'handleCachedBirthdaysDidUpdate:', name: 'BRNotificationCachedBirthdaysDidUpdate', object: nil) NSNotificationCenter.defaultCenter.addObserver(self, selector: 'updateBirthdays', name: UIApplicationDidBecomeActiveNotification, object: nil) end def viewWillDisappear(animated) super NSNotificationCenter.defaultCenter.removeObserver(self, name: 'BRNotificationCachedBirthdaysDidUpdate', object: nil) NSNotificationCenter.defaultCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) end def handleCachedBirthdaysDidUpdate(notification) puts ' handleCachedBirthdaysCalled' @table_view.reloadData end def tableView(tableView, cellForRowAtIndexPath:indexPath) cell = @table_view.dequeueReusableCellWithIdentifier('Cell') birthday = fetchedResultsController.objectAtIndexPath(indexPath) #@birthdays[indexPath.row] brTableCell = cell brTableCell.birthday = birthday #if birthday.imageData # brTableCell.iconView.image = UIImage.imageWithData birthday.imageData #else # brTableCell.iconView.image = UIImage.imageNamed('icon-birthday-cake.png') #end if birthday.imageData == nil if birthday.picURL && birthday.picURL.length > 0 brTableCell.iconView.setImageWithRemoteFileURL(birthday.picURL,placeHolderImage:UIImage.imageNamed('icon-birthday-cake.png')) end if birthday.picURL && birthday.picURL.length > 0 && UIImageView.imageCache.cachedImageForURL(birthday.picURL) puts'called length > 0 and has picURL 2' brTableCell.iconView.image = UIImageView.imageCache.cachedImageForURL(birthday.picURL) else brTableCell.iconView.image = UIImage.imageNamed('icon-birthday-cake.png') end else brTableCell.iconView.image = UIImage.imageWithData(birthday.imageData) end backgroundImage = indexPath.row == 0 ? UIImage.imageNamed('table-row-background.png') : UIImage.imageNamed('table-row-icing-background.png') brTableCell.backgroundView = UIImageView.alloc.initWithImage backgroundImage return brTableCell end def tableView(tableView, numberOfRowsInSection:section) sectionInfo = fetchedResultsController.sections.objectAtIndex(section) sectionInfo.numberOfObjects #@birthdays.count end def tableView (tableView,didSelectRowAtIndexPath:indexPath) @table_view.deselectRowAtIndexPath(indexPath,animated:true) end def prepareForSegue(segue,sender:sender) #puts "prepare for Segue!" identifier = segue.identifier begin selectedIndexPath = @table_view.indexPathForSelectedRow birthday = fetchedResultsController.objectAtIndexPath(selectedIndexPath) birthdayDetailViewController = segue.destinationViewController birthdayDetailViewController.birthday = birthday end if identifier == "BirthdayDetail" if identifier == "AddBirthday" context = BRDModel.sharedInstance.managedObjectContext birthday = NSEntityDescription.insertNewObjectForEntityForName('BirthdayReminder', inManagedObjectContext: context) birthday.updateWithDefaults navigationController = segue.destinationViewController birthdayEditViewController = navigationController.topViewController birthdayEditViewController.birthday = birthday end end def fetchedResultsController if @fetchedResultsController == nil fetchRequest = NSFetchRequest.alloc.init context = BRDModel.sharedInstance.managedObjectContext entity = NSEntityDescription.entityForName("BirthdayReminder", inManagedObjectContext: context) fetchRequest.entity = entity sortdescriptor = NSSortDescriptor.alloc.initWithKey("nextBirthday", ascending: true) sortDescriptors = NSArray.alloc.initWithObjects(sortdescriptor,nil) fetchRequest.sortDescriptors = sortDescriptors @fetchedResultsController = NSFetchedResultsController.alloc.initWithFetchRequest(fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) @fetchedResultsController.delegate = self error = Pointer.new('@') unless @fetchedResultsController.performFetch(error) puts "Unresolved Error" end end @fetchedResultsController end def importFromAddressBookTapped(sender) nav = self.storyboard.instantiateViewControllerWithIdentifier 'ImportAddressBook' navigationController.presentViewController(nav,animated: true,completion:nil) end def importFromFacebookTapped(sender) puts 'import from facebook' nav = self.storyboard.instantiateViewControllerWithIdentifier 'ImportFacebook' navigationController.presentViewController(nav,animated: true,completion:nil) end def controllerDidChangeContent(controller) end def updateBirthdays puts 'updateBdaysCalled on active notification' BRDModel.sharedInstance.updateCachedBirthdays end end <file_sep>/app/br_import_faceboo_view_controller.rb class BRImportFacebookViewController < BRImportViewController def viewDidLoad super end def viewWillAppear(animated) super NSNotificationCenter.defaultCenter.addObserver(self, selector: 'handleFacebookBirthdaysDidUpdate:', name: 'BRNotificationFaceBookBirthdaysDidUpdate', object: BRDModel.sharedInstance) BRDModel.sharedInstance.fetchFacebookBirthdays end def viewWillDisappear(animated) super NSNotificationCenter.defaultCenter.removeObserver(self, name: 'BRNotificationFaceBookBirthdaysDidUpdate', object: BRDModel.sharedInstance) end def handleFacebookBirthdaysDidUpdate(notification) userInfo = notification.userInfo self.birthdays = userInfo['birthdays'] @table_view.reloadData end end<file_sep>/app/br_model.rb class BRDModel attr_accessor :facebookAccount,:currentFacebookAction,:postToFacebookMessage,:postToFacebookID def managedObjectContext coordinator = persistentStoreCoordinator @managedObjectContext ||= begin managedObjectContext = NSManagedObjectContext.alloc.init managedObjectContext.setPersistentStoreCoordinator(coordinator) managedObjectContext end if coordinator return @managedObjectContext end def managedObjectModel @managedObjectModel||= begin @managedObjectModel = NSManagedObjectModel.alloc.init #@managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil) #model_path = NSBundle.mainBundle.pathForResource("BirthdayReminder",ofType:'momd') #model_url = NSURL.fileURLWithPath(model_path) #@managedObjectModel = NSManagedObjectModel.alloc.initWithContentsOfURL(model_url) @managedObjectModel.setEntities([BRDBirthday.entity]) #@managedObjectModel.entities = [BRDBirthday.entity] end #puts "this is managedObjectModel.entities #{@managedObjectModel.entities}" return @managedObjectModel end def persistentStoreCoordinator @persistentStoreCoordinator ||= begin storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("BirthdayReminder.sqlite") error = Pointer.new(:object) persistentStoreCoordinator = NSPersistentStoreCoordinator.alloc.initWithManagedObjectModel managedObjectModel unless persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration:nil, URL: storeURL, options: nil, error: error) raise "Can't add persistent SQLite store: #{error[0].description}" abort end @persistentStoreCoordinator = persistentStoreCoordinator end @persistentStoreCoordinator end def applicationDocumentsDirectory NSFileManager.defaultManager.URLsForDirectory(NSDocumentDirectory, inDomains: NSUserDomainMask).lastObject end def self.sharedInstance @sharedInstance ||= self.alloc.init return @sharedInstance end def saveChanges error = Pointer.new('@') if self.managedObjectContext.hasChanges if self.managedObjectContext.save(error) puts "save in BRDMODEL succeeded" else raise "it failed #{error[0].description}" end end end def getExistingBirthdaysWithUIDs(uid) fetchRequest = NSFetchRequest.alloc.init context = @managedObjectContext predicate = NSPredicate.predicateWithFormat("uid IN %@",argumentArray:[uid]) fetchRequest.predicate = predicate entity = NSEntityDescription.entityForName("BirthdayReminder", inManagedObjectContext: context) fetchRequest.entity = entity sortDescriptor = NSSortDescriptor.alloc.initWithKey("uid", ascending:true) fetchRequest.sortDescriptors = [sortDescriptor] fetchedResultsController = NSFetchedResultsController.alloc.initWithFetchRequest(fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) error = Pointer.new(:object) unless fetchedResultsController.performFetch(error) puts "there was an error in performing the fetch for UIDS: #{error[0].description}" abort end fetchedObjects = fetchedResultsController.fetchedObjects resultCount = fetchedObjects.count return {} if resultCount == 0 tmpDict = {} fetchedObjects.each{|f|birthday = f;tmpDict[birthday.uid] = birthday} return tmpDict end def cancelChanges managedObjectContext.rollback end # addressBook code starts def fetchAddressBookBirthdays addressbook = ABAddressBookCreateWithOptions(nil,nil) case ABAddressBookGetAuthorizationStatus() when KABAuthorizationStatusNotDetermined ABAddressBookRequestAccessWithCompletion(addressbook,lambda do |granted,error| if granted puts 'Access to the Address Book has been granted' gcdq_main = Dispatch::Queue.main gcdq_main.async do self.extractBirthdaysFromAddressBook(ABAddressBookCreateWithOptions(nil,nil)) end else puts 'Access to the Address Book has been denied' end end ) when KABAuthorizationStatusAuthorized puts 'User has already authorized access' extractBirthdaysFromAddressBook(ABAddressBookCreateWithOptions(nil,nil)) when KABAuthorizationStatusRestricted puts 'User cannot access due to parental controls' when KABAuthorizationStatusDenied puts ' User has denied access' end end def extractBirthdaysFromAddressBook(addressbook) puts 'extractBirthdayFromAddressBook' people = ABAddressBookCopyArrayOfAllPeople(addressbook) peopleCount = ABAddressBookGetPersonCount(addressbook) birthdays = [] (0...peopleCount).each do |i| addressbookRecord = CFArrayGetValueAtIndex(people, i) addressbookRecordObject = addressbookRecord.to_object birthdate = ABRecordCopyValue(addressbookRecordObject,KABPersonBirthdayProperty) next unless birthdate birthday = BRDBirthdayImport.alloc.initWithAddressBookRecord(addressbookRecord.to_object) birthdays << birthday end birthdays.sort_by!{|birthday| birthday.name} userInfo = {'birthdays' => birthdays} performSelectorOnMainThread('postAddressNotification:', withObject:userInfo, waitUntilDone:nil) end def postAddressNotification(userInfo) NSNotificationCenter.defaultCenter.postNotificationName('BRNotificationAddressBookBirthdaysDidUpdate', object: self, userInfo: userInfo) end def importBirthdays(birthdaysToImport) newUIDs = [] birthdaysToImport.each_with_index do |importBirthday,_| uid = importBirthday.uid newUIDs << uid end existingBirthdays = getExistingBirthdaysWithUIDs(newUIDs) context = BRDModel.sharedInstance.managedObjectContext birthdaysToImport.each do |importBirthday| uid = importBirthday.uid birthday = existingBirthdays[uid] if birthday else birthday = NSEntityDescription.insertNewObjectForEntityForName('BirthdayReminder', inManagedObjectContext:context) birthday.uid = uid existingBirthdays[uid] = birthday birthday.name = importBirthday.name birthday.uid = importBirthday.uid birthday.picURL = importBirthday.picURL birthday.imageData = importBirthday.imageData birthday.addressBookID = importBirthday.addressBookID birthday.facebookID = importBirthday.facebookID birthday.birthDay = importBirthday.birthDay birthday.birthMonth = importBirthday.birthMonth birthday.birthYear = importBirthday.birthYear birthday.updateNextBirthdayAndAge end end saveChanges updateCachedBirthdays end def fetchFacebookBirthdays puts 'fetchFacebookBirthdays' unless facebookAccount self.currentFacebookAction = 'FacebookActionGetFriendsBirthdays' authenticateWithFacebook return end requestURL = NSURL.URLWithString('https://graph.facebook.com/me/friends') params = {'fields'=>'name,id,birthday'} request = SLRequest.requestForServiceType(SLServiceTypeFacebook, requestMethod: SLRequestMethodGET, URL: requestURL, parameters: params) request.account = facebookAccount handler = lambda do |responseData,urlResponse,error| if error NSLog('error with getting my friends birthdays: %@',error) else resultD = NSJSONSerialization.JSONObjectWithData(responseData, options: 0, error: nil) NSLog('facebook returned friends: %@', resultD) birthdayDictionaries = resultD['data'] #birthdayCount = birthdayDictionaries.count birthdays = [] birthdayDictionaries.each do |facebookDictionary| birthDateS = facebookDictionary['birthday'] next unless birthDateS NSLog('Found a Birthday from Facebook: %@',facebookDictionary) birthday = BRDBirthdayImport.alloc.initWithFacebookDictionary(facebookDictionary) birthdays << birthday end birthdays.sort_by!{|birthday| birthday.name} userInfo = {'birthdays'=> birthdays} performSelectorOnMainThread('postFacebookNotification:', withObject:userInfo, waitUntilDone:nil) end end request.performRequestWithHandler(handler) end def postFacebookNotification(userInfo) NSNotificationCenter.defaultCenter.postNotificationName('BRNotificationFaceBookBirthdaysDidUpdate', object: self, userInfo: userInfo) end def authenticateWithFacebook accountStore = ACAccountStore.alloc.init accountTypeFacebook = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook) options = {ACFacebookAppIdKey => '316689658473081', ACFacebookPermissionsKey => ['publish_actions','friends_birthday','email'], ACFacebookAudienceKey => ACFacebookAudienceFriends } completion = lambda do |granted, error| if granted puts 'Facebook Authorized!' accounts = accountStore.accountsWithAccountType accountTypeFacebook self.facebookAccount = accounts.last case currentFacebookAction when 'FacebookActionGetFriendsBirthdays' then fetchFacebookBirthdays when 'FacebookActionPostToWall' #self.postToFacebookWall(self.postToFacebookMessage,withFacebookID:self.postToFacebookID) array = [postToFacebookMessage,self.postToFacebookID] dict = {'message'=>postToFacebookMessage,'id'=>postToFacebookID} #performSelectorOnMainThread('postToFacebookWall:withFacebookID:', withObject:dict, waitUntilDone:true) gcdq_main = Dispatch::Queue.main gcdq_main.async do postToFacebookWall(postToFacebookMessage,withFacebookID:postToFacebookID) end end else if error.code == ACErrorAccountNotFound puts'No Facebook Account Found' else puts "authentication failed:#{error.localizedDescription}" end end end accountStore.requestAccessToAccountsWithType(accountTypeFacebook, options: options, completion: completion) end def postToFacebookWall(message,withFacebookID:id) puts 'postToFacebookWall Method Called from BRDMODEL' if self.facebookAccount.nil? puts 'not authorized to post to FB' self.postToFacebookID = id puts self.postToFacebookID self.postToFacebookMessage = message self.currentFacebookAction = 'FacebookActionPostToWall' authenticateWithFacebook return end puts 'we are authorized to post to FB!' fbcredential = facebookAccount.credential accessToken = fbcredential.oauthToken handler = lambda do |result,url,error| if error puts "there is an error:#{error.localizedDescription}" else puts "there was no error;#{url.absoluteString}" if url end end #params = {'app_id' => '316689658473081','name'=> 'Happy Birthday!','to'=>"#{self.postToFacebookID}"} params = {'app_id' => '316689658473081','name'=> 'Happy Birthday!','to'=>"#{id}"} #if id puts id puts params #session = FBSession.alloc.initWithAppID('316689658473081',permissions:nil,urlSchemeSuffix:nil,tokenCacheStrategy:nil) #FBSession.renewSystemCredentials(nil) #FBAccessTokenData.createTokenFromString(accessToken.to_s,permissions:nil,expirationDate:nil,) # make sure you add the FacebookAppID entry to info.plist before continuing with below session = FBSession.alloc.init session.openWithBehavior(FBSessionLoginBehaviorUseSystemAccountIfPresent,completionHandler:nil) FBWebDialogs.presentFeedDialogModallyWithSession(session,parameters:params,handler:handler) end def updateCachedBirthdays puts 'update cached bdays called' UIApplication.sharedApplication.cancelAllLocalNotifications fetchRequest = NSFetchRequest.alloc.init context = managedObjectContext entity = NSEntityDescription.entityForName('BirthdayReminder', inManagedObjectContext: context) sortDescriptor = NSSortDescriptor.alloc.initWithKey('nextBirthday', ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] fetchRequest.entity = entity fetchedResultsController = NSFetchedResultsController.alloc.initWithFetchRequest(fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) error = Pointer.new('@') unless fetchedResultsController.performFetch(error) puts error.localizedDescription abort end puts 'got here' fetchedObjects = fetchedResultsController.fetchedObjects resultCount = fetchedObjects.count scheduled = 0 now = NSDate.date dateComponentsToday = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate: now) today = NSCalendar.currentCalendar.dateFromComponents(dateComponentsToday) fetchedObjects.each do |birthday| if today < birthday.nextBirthday birthday.updateNextBirthdayAndAge end if scheduled< 20 fireDate = BRDSettings.sharedInstance.reminderDateForNextBirthday(birthday.nextBirthday) if now.compare(fireDate)!= NSOrderedAscending else reminderNotification = UILocalNotification.alloc.init reminderNotification.fireDate = fireDate reminderNotification.timeZone = NSTimeZone.defaultTimeZone reminderNotification.alertAction = 'View Birthdays' reminderNotification.alertBody =BRDSettings.sharedInstance.reminderTextForNextBirthday(birthday) reminderNotification.soundName = 'HappyBirthday.m4a' reminderNotification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication.scheduleLocalNotification(reminderNotification) scheduled += 1 end end end self.saveChanges puts 'got here too!' gcdq_main = Dispatch::Queue.main gcdq_main.async do puts 'got here too!' NSNotificationCenter.defaultCenter.postNotificationName('BRNotificationCachedBirthdaysDidUpdate', object: self, userInfo: nil) end true end end<file_sep>/app/brd_settings.rb class BRDSettings attr_accessor :notificationHour,:notificationMinute,:daysBefore def notificationHour hour = userDefaults['notificationHour'] || 9 end def notificationHour=(hr) userDefaults['notificationHour'] = hr userDefaults.synchronize end def notificationMinute hour = userDefaults['notificationMinute'] || 0 end def notificationMinute=(min) userDefaults['notificationMinute'] = min userDefaults.synchronize end def daysBefore days = userDefaults['daysBefore'] || 0 end def daysBefore=(days) userDefaults['daysBefore'] = days userDefaults.synchronize end def self.sharedInstance @sharedInstance ||= BRDSettings.alloc.init end def titleForNotificationTime hour = BRDSettings.sharedInstance.notificationHour minute = BRDSettings.sharedInstance.notificationMinute components = NSCalendar.currentCalendar.components(NSHourCalendarUnit|NSMinuteCalendarUnit, fromDate: NSDate.date) components.hour = hour components.minute = minute date = NSCalendar.currentCalendar.dateFromComponents components dateFormatter ||= NSDateFormatter.alloc.init dateFormatter.setDateFormat('h:mm a') dateFormatter.stringFromDate date end def titleForDaysBefore(daysBefore) case daysBefore when 0 then 'On Birthday' when 1 then '1 Day Before' when 2 then '2 Days Before' when 3 then '3 Days Before' when 4 then '5 Days Before' when 5 then '1 week Before' when 6 then '2 weeks Before' when 7 then '3 weeks Before' else return '' end end def userDefaults userDefaults = NSUserDefaults.standardUserDefaults end def reminderDateForNextBirthday(nextBirthday) secondsInOneDay = 3600*24.0 case self.daysBefore when 0 then timeInterval = 0.0 when 1 then timeInterval = secondsInOneDay when 2 then timeInterval = secondsInOneDay*2 when 3 then timeInterval = secondsInOneDay*3 when 4 then timeInterval = secondsInOneDay*5 when 5 then timeInterval = secondsInOneDay*7 when 6 then timeInterval = secondsInOneDay*14 when 7 then timeInterval = secondsInOneDay*21 end reminderDate = nextBirthday.dateByAddingTimeInterval -timeInterval components = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit, fromDate: reminderDate) components.hour = self.notificationHour components.minute = self.notificationMinute NSCalendar.currentCalendar.dateFromComponents components end def reminderTextForNextBirthday(birthday) if birthday.nextBirthdayAge > 0 if self.daysBefore == 0 text = "#{birthday.name} is #{birthday.nextBirthdayAge}" else text = "#{birthday.name} will be #{birthday.nextBirthdayAge}" end else text = "It's #{birthday.name}'s Birthday" end case self.daysBefore when 0 text + 'today' when 1 text +'tomorrow' when 2 text +'in 2 days' when 3 text + 'in 3 days' when 4 text + 'in 5 days' when 5 text + 'in 1 week' when 6 text + 'in 2 weeks' when 7 text + 'in 3 weeks' else '' end end end<file_sep>/README.md birthday_reminder ================= Birthday Reminder App from Foundation Iphone App development written with Rubymotion This is a complete rewrite of the Birthday Reminder App written by <NAME> in the book; "Foundation Iphone App Development" published by Apress The port works as described and some modifications have been made to ensure compliance with the latest Facebook SDK The App is a mixture of idiomatic and non-idiomatic ruby. <file_sep>/app/ui_image_view.rb class UIImageView class ImageCache attr_accessor :cache def init a = super if a NSNotificationCenter.defaultCenter.addObserver(self, selector: 'clearCache', name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) end return a end def dealloc NSNotificationCenter.defaultCenter.removeObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) end def cache @cache ||= {} end def clearCache @cache.clear end def cachedImageForURL(url) cache[url] end def storeCachedImage(image,forURL:url) cache[url] = image end end class DownloadHelper attr_accessor :url,:data,:connection,:delegate,:image def konnection @connection end def connection @connection end def data @data||=NSMutableData.data end def connection(connection, didReceiveData: data) self.data.appendData(data) # print 'this is data ',!!data end def connectionDidFinishLoading(connection) #puts 'delegate method called' delegate.didCompleteDownloadForURL(image.url,withData:data) end def didCompleteDownloadForURL(url,withData:data) image = UIImage.imageWithData(data) return unless image imageCache = UIImageView.imageCache imageCache.storeCachedImage(image,forURL:url) self.image = image end def cancelConnection if connection connection.cancel connection = nil end end def dealloc cancelConnection end end end module RemoteFileHidden attr_accessor :url,:downloadHelper def UIImageView.imageCache @imageCache ||= UIImageView::ImageCache.alloc.init end def downloadHelper helper ||= UIImageView::DownloadHelper.alloc.init helper.delegate = helper helper.image = self @downloadHelper = helper @downloadHelper end def setImageWithRemoteFileURL(urlString,placeHolderImage:placeHolderImage) if self.url != nil && self.url == urlString return end self.url = urlString self.downloadHelper.url = urlString self.downloadHelper.cancelConnection imageCache = UIImageView.imageCache image = imageCache.cachedImageForURL(urlString) if image self.image = image return end self.image = placeHolderImage url = NSURL.URLWithString(urlString) request = NSURLRequest.requestWithURL(url) self.downloadHelper.url = urlString self.downloadHelper.connection = NSURLConnection.alloc.initWithRequest(request, delegate: self.downloadHelper, startImmediately: true) #puts downloadHelper.connection self.downloadHelper.data = NSMutableData.data if @downloadHelper.connection end end class UIImageView include RemoteFileHidden alias_method :old_dealloc, :dealloc def dealloc downloadHelper.cancelConnection if url old_dealloc end end<file_sep>/app/br_import_view_controller.rb class BRImportViewController < BRCoreViewController attr_accessor :birthdays,:selectedIndexPathToBirthday def birthdays @birthdays ||= [] end def viewDidLoad super @table_view = view.viewWithTag 1 @table_view.dataSource = self @table_view.delegate = self leftButton = navigationItem.leftBarButtonItem leftButton.target = self leftButton.action = :cancelAndDismiss @importButton = navigationItem.rightBarButtonItem @importButton.target = self @importButton.action = 'didTapImportButton:' toolbarItems[1].target = self toolbarItems[1].action = 'didTapSelectAllButton:' toolbarItems[2].target = self toolbarItems[2].action = 'didTapSelectNoneButton:' end def viewWillAppear(animated) super updateImportButton end def didTapImportButton(sender) birthdaysToImport = selectedIndexPathToBirthday.allValues BRDModel.sharedInstance.importBirthdays(birthdaysToImport) self.dismissViewControllerAnimated(true, completion: nil) end def didTapSelectAllButton(sender) birthdays.each_with_index do |birthdayImport,i| indexPath = NSIndexPath.indexPathForRow(i,inSection:0) selectedIndexPathToBirthday[indexPath] = birthdayImport @table_view.reloadData updateImportButton end end def didTapSelectNoneButton(sender) selectedIndexPathToBirthday.clear @table_view.reloadData updateImportButton end def tableView(tableView, numberOfRowsInSection:number) puts 'number of rows called' puts birthdays.size birthdays.size end def tableView(tableView, cellForRowAtIndexPath:indexPath) cell = @table_view.dequeueReusableCellWithIdentifier('Cell') birthdayImport = birthdays[indexPath.row] brTableCell = cell brTableCell.birthdayImport = birthdayImport #if birthdayImport.imageData == nil # brTableCell.iconView.image = UIImage.imageNamed "icon-birthday-cake.png" #else # brTableCell.iconView.image = UIImage.imageWithData birthdayImport.imageData #end backgroundImage = indexPath.row == 0 ? UIImage.imageNamed("table-row-background.png") : UIImage.imageNamed('table-row-icing-background.png') brTableCell.backgroundView = UIImageView.alloc.initWithImage backgroundImage updateAccessoryForTableCell(cell,atIndexPath:indexPath) cell end def selectedIndexPathToBirthday @selectedIndexPathToBirthday||= {} end def updateImportButton @importButton.enabled = selectedIndexPathToBirthday.size > 0 end def selectedAtIndexPath?(indexPath) @selectedIndexPathToBirthday.include?(indexPath) end def updateAccessoryForTableCell(tableCell,atIndexPath:indexPath) if selectedAtIndexPath?(indexPath) imageView = UIImageView.alloc.initWithImage(UIImage.imageNamed('icon-import-selected.png')) else imageView = UIImageView.alloc.initWithImage(UIImage.imageNamed('icon-import-not-selected.png')) end tableCell.accessoryView = imageView end def tableView(tableView, didSelectRowAtIndexPath:indexPath) isSelected = selectedAtIndexPath?(indexPath) birthdayImport = birthdays[indexPath.row] if isSelected self.selectedIndexPathToBirthday.delete indexPath else selectedIndexPathToBirthday[indexPath] = birthdayImport end updateAccessoryForTableCell(tableView.cellForRowAtIndexPath(indexPath),atIndexPath:indexPath) updateImportButton end end<file_sep>/app/ui_birthday_table_view_cell.rb class BirthdayTableViewCell < UITableViewCell attr_reader :birthday attr_accessor :birthdayImport def iconView @icon_view ||= contentView.viewWithTag 1 BRStyleSheet.styleRoundCorneredView(@icon_view) @icon_view end def iconView=(x) @icon_view = x end def remainingDaysImageView @remaining_days_image_view = contentView.viewWithTag 2 end def remainingDaysImageView=(x) @remaining_days_image_view = x end def nameLabel @name_label = contentView.viewWithTag 3 BRStyleSheet.styleLabel(@name_label,withType:'BRLabelTypeName') if @name_label @name_label end def nameLabel=(x) @name_label = x end def birthdayLabel @birthday_label = contentView.viewWithTag 4 BRStyleSheet.styleLabel(@birthday_label,withType:'BRLabelTypeBirthdayDate') if @birthday_label @birthday_label end def birthdayLabel=(x) @birthday_label = x end def remainingDaysLabel @remaining_days_label = contentView.viewWithTag 5 end def remainingDaysLabel=(x) @remaining_days_label = x end def remainingDaysSubTextLabel @remaining_days_sub_text_label = contentView.viewWithTag 6 BRStyleSheet.styleLabel(@remaining_days_label,withType:'BRLabelTypeDaysUntilBirthday') if @remaining_days_label @remaining_days_sub_text_label end def remainingDaysSubTextLabel=(x) @remaining_days_sub_text_label = x end def birthday=(birthday) @birthday = birthday nameLabel.text = birthday.name days = birthday.remainingDaysUntilNextBirthday if days == 0 remainingDaysLabel.text = remainingDaysSubTextLabel.text = '' remainingDaysImageView.image = UIImage.imageNamed 'icon-birthday-cake.png' else remainingDaysLabel.text = "#{days}" remainingDaysSubTextLabel.text = days == 1 ? 'more day' : 'more days' remainingDaysImageView.image = UIImage.imageNamed 'icon-days-remaining.png' end birthdayLabel.text = birthday.birthdayTextToDisplay if birthday.imageData == nil if birthday.picURL && birthday.picURL.length > 0 puts'called length > 0 and has picURL' iconView.setImageWithRemoteFileURL(birthday.picURL,placeHolderImage:UIImage.imageNamed('icon-birthday-cake.png')) else iconView.image = UIImage.imageNamed('icon-birthday-cake.png') end else iconView.image = UIImage.imageWithData(@birthday.imageData) end end def birthdayImport=(birthdayImport) puts "this is birthdayImportData: #{birthdayImport.imageData}" @birthdayImport = birthdayImport nameLabel.text = birthdayImport.name days = birthdayImport.remainingDaysUntilNextBirthday if days == 0 remainingDaysLabel.text = remainingDaysSubTextLabel.text = '' remainingDaysImageView.image = UIImage.imageNamed 'icon-birthday-cake.png' else remainingDaysLabel.text = "#{days}" remainingDaysSubTextLabel.text = days == 1 ? 'more day' : 'more days' remainingDaysImageView.image = UIImage.imageNamed 'icon-days-remaining.png' end birthdayLabel.text = birthdayImport.birthdayTextToDisplay if birthdayImport.imageData == nil if birthdayImport.picURL && birthdayImport.picURL.length > 0 puts ' birthda import picurl has length' iconView.setImageWithRemoteFileURL(birthdayImport.picURL,placeHolderImage:UIImage.imageNamed('icon-birthday-cake.png')) else puts ' birthda import picurl has no length' self.iconView.image = UIImage.imageNamed('icon-birthday-cake.png') end else self.iconView.image = UIImage.imageWithData(birthdayImport.imageData) end end end <file_sep>/app/br_notes_edit_view_controller.rb class BRNotesEditViewController < BRCoreViewController attr_accessor :birthday def viewWillAppear(animated) super @text_view.text = birthday.notes @text_view.becomeFirstResponder end def viewDidLoad super left = self.navigationItem.leftBarButtonItem left.target = self left.action = :cancelAndDismiss @save_button = self.navigationItem.rightBarButtonItem @save_button.target = self @save_button.action = :saveAndDismiss @text_view = view.viewWithTag 1 @text_view.delegate = self BRStyleSheet.styleTextView @text_view end def textViewDidChange(textView) #puts "User changed the notes Text #{@text_view.text}" birthday.notes = @text_view.text end def cancelAndDismiss BRDModel.sharedInstance.cancelChanges super end def saveAndDismiss BRDModel.sharedInstance.saveChanges super end end<file_sep>/app/br_style_sheet.rb #=begin class BRStyleSheet #=begin @@kFontLightOnDarkTextColour = UIColor.colorWithRed(255.0/255.0, green:251.0/255.0, blue:218.0/255.0, alpha:1.0) @@kFontDarkOnLightTextColour = UIColor.colorWithRed(1.0/255.0, green:1.0/255.0, blue:1.0/255.0, alpha:1.0) @@kFontNavigationTextColour = UIColor.colorWithRed(106.0/255.0, green:62.0/255.0, blue:39.0/255.0, alpha:1.0) @@kFontNavigationDisabledTextColour = UIColor.colorWithRed(106.0/255.0, green:62.0/255.0, blue:39.0/255.0, alpha:0.6) @@kNavigationButtonBackgroundColour=UIColor.colorWithRed(255.0/255.0, green:245.0/255.0, blue:225.0/255.0, alpha:1.0) @@kToolbarButtonBackgroundColour = UIColor.colorWithRed(39.0/255.0, green:17.0/255.0, blue:5.0/255.0, alpha:1.0) @@kLargeButtonTextColour = UIColor.whiteColor #=end def self.fonts @@kFontNavigation = UIFont.systemFontOfSize(18) #=begin @@kFontName = UIFont.fontWithName("HelveticaNeue-Bold", size:15.0) @@kFontBirthdayDate = UIFont.fontWithName("HelveticaNeue", size:13.0) @@kFontDaysUntilBirthday = UIFont.fontWithName("HelveticaNeue-Bold", size:25.0) @@kFontDaysUntilBirthdaySubText = UIFont.fontWithName("HelveticaNeue", size:9.0) @@kFontLarge = UIFont.fontWithName("HelveticaNeue-Bold", size:17.0) @@kFontButton = UIFont.fontWithName("HelveticaNeue-Bold", size:30.0) @@kFontNotes = UIFont.fontWithName("HelveticaNeue", size:16.0) @@kFontPicPhoto = UIFont.fontWithName("HelveticaNeue-Bold", size:12.0) @@kFontDropShadowColour = UIColor.colorWithRed(1.0/255.0, green:1.0/255.0, blue:1.0/255.0, alpha:0.75) #=end end def self.styleLabel(label, withType:labelType) fonts case labelType when 'BRLabelTypeName' label.font = @@kFontName label.layer.shadowColor = @@kFontDropShadowColour.CGColor label.layer.shadowOffset = CGSizeMake(1, 1) label.layer.shadowRadius = 0 label.layer.masksToBounds = false label.textColor = @@kFontLightOnDarkTextColour when 'BRLabelTypeBirthdayDate' label.font = @@kFontBirthdayDate label.textColor = @@kFontLightOnDarkTextColour when 'BRLabelTypeDaysUntilBirthday' label.font = @@kFontDaysUntilBirthday label.textColor = @@kFontDarkOnLightTextColour when 'BRLabelTypeDaysUntilBirthdaySubText' label.font = @@kFontDaysUntilBirthdaySubText label.textColor = @@kFontDarkOnLightTextColour when 'BRLabelTypeLarge' label.textColor = @@kFontLightOnDarkTextColour label.layer.shadowColor = @@kFontDropShadowColour.CGColor label.layer.shadowOffset = CGSizeMake(1, 1) label.layer.shadowRadius = 0 label.layer.masksToBounds = false else label.textColor = @@kFontLightOnDarkTextColour end end #=end def self.styleRoundCorneredView(view) view.layer.cornerRadius = 4.0 view.layer.masksToBounds = true view.clipsToBounds = true end def self.initStyles fonts titleTextAttributes = NSDictionary.dictionaryWithObjectsAndKeys(@@kFontNavigationTextColour,UITextAttributeTextColor,UIColor.whiteColor,UITextAttributeTextShadowColor,NSValue.valueWithUIOffset(UIOffsetMake(0,2)),UITextAttributeTextShadowOffset,@@kFontNavigation,UITextAttributeFont,nil) UINavigationBar.appearance.setTitleTextAttributes(titleTextAttributes) UINavigationBar.appearance.setBackgroundImage(UIImage.imageNamed("navigation-bar-background.png"), forBarMetrics: UIBarMetricsDefault) UIBarButtonItem.appearanceWhenContainedIn(UINavigationBar,nil).setTintColor(@@kNavigationButtonBackgroundColour) barButtonItemTextAttributes = NSDictionary.dictionaryWithObjectsAndKeys(@@kFontNavigationTextColour,UITextAttributeTextColor,UIColor.whiteColor, UITextAttributeTextShadowColor,NSValue.valueWithUIOffset(UIOffsetMake(0,1)), UITextAttributeTextShadowOffset,nil ) UIBarButtonItem.appearanceWhenContainedIn(UINavigationBar,nil).setTitleTextAttributes(barButtonItemTextAttributes, forState: UIControlStateNormal ) disabledBarButtonItemTextAttributes = NSDictionary.dictionaryWithObjectsAndKeys(@@kFontNavigationDisabledTextColour,UITextAttributeTextColor,UIColor.whiteColor,UITextAttributeTextShadowColor,NSValue.valueWithUIOffset(UIOffsetMake(0,1)),UITextAttributeTextShadowOffset,nil) UIBarButtonItem.appearanceWhenContainedIn(UINavigationBar,nil).setTitleTextAttributes(disabledBarButtonItemTextAttributes, forState: UIControlStateDisabled) UIToolbar.appearance.setBackgroundImage(UIImage.imageNamed("tool-bar-background.png"), forToolbarPosition: UIToolbarPositionAny, barMetrics: UIBarMetricsDefault) UIBarButtonItem.appearanceWhenContainedIn(UIToolbar,nil).setTintColor @@kToolbarButtonBackgroundColour barButtonItemTextAttributes = {UITextAttributeTextColor:UIColor.whiteColor} UIBarButtonItem.appearanceWhenContainedIn(UIToolbar,nil).setTitleTextAttributes(barButtonItemTextAttributes, forState: UIControlStateNormal) #Buttons BRBlueButton.appearance.setBackgroundImage(UIImage.imageNamed("button-blue.png"), forState: UIControlStateNormal) BRBlueButton.appearance.setTitleColor(@@kLargeButtonTextColour, forState: UIControlStateNormal) BRBlueButton.appearance.font = @@kFontLarge BRRedButton.appearance.setBackgroundImage(UIImage.imageNamed("button-red.png"), forState: UIControlStateNormal) BRRedButton.appearance.setTitleColor(@@kLargeButtonTextColour, forState: UIControlStateNormal) BRRedButton.appearance.font = @@kFontLarge #Table View UITableView.appearance.backgroundColor = UIColor.clearColor UITableViewCell.appearance.selectionStyle = UITableViewCellSelectionStyleNone UITableView.appearance.separatorStyle = UITableViewCellSeparatorStyleNone end # p NSHomeDirectory() def self.styleTextView(textView) textView.backgroundColor = UIColor.clearColor textView.font = @@kFontNotes textView.textColor = @@kFontLightOnDarkTextColour textView.layer.shadowColor = @@kFontDropShadowColour.CGColor textView.layer.shadowOffset =[1.0,1.0] textView.layer.shadowRadius = 0.0 textView.layer.masksToBounds = false end end #=end<file_sep>/app/BRBirthdayEditViewController.rb class BRBirthdayEditViewController < BRCoreViewController attr_accessor :birthday SIDE = 71.0 def viewWillAppear(animated) super @name_text_field.text = @birthday.name #@date_picker.date = @birthday.birthdate components = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:@date_picker.date) components.day = @birthday.birthDay if @birthday.birthDay > 0 components.month = @birthday.birthMonth if @birthday.birthMonth > 0 if @birthday.birthYear > 0 components.year = @birthday.birthYear @include_year_switch.on = true else @include_year_switch.on = false end @birthday.updateNextBirthdayAndAge @date_picker.date = NSCalendar.currentCalendar.dateFromComponents components if birthday.imageData == nil if birthday.picURL && birthday.picURL.length > 0 @photo_view.setImageWithRemoteFileURL(birthday.picURL,placeHolderImage:(UIImage.imageNamed('icon-birthday-cake.png'))) else @photo_view.image = UIImage.imageNamed('icon-birthday-cake.png') end else @photo_view.image = UIImage.imageWithData(@birthday.imageData) end updateSaveButton end def viewDidLoad super left = self.navigationItem.leftBarButtonItem left.target = self left.action = :cancelAndDismiss @save_button = self.navigationItem.rightBarButtonItem @save_button.target = self @save_button.action = :saveAndDismiss #date_picker = self.view.subviews.grep(UIDatePicker).first #text_field = self.view.subviews.grep(UITextField).first @date_picker = view.viewWithTag 2 @name_text_field = view.viewWithTag 1 @include_year_label = view.viewWithTag 3 @include_year_switch = view.viewWithTag 4 @photo_container_view = view.viewWithTag 5 @photo_view = view.viewWithTag 7 @pic_photo_label = view.viewWithTag 8 @gesture_recognizer = @photo_container_view.gestureRecognizers[0] @name_text_field.delegate = self @name_text_field.addTarget(self, action:'didChangeNameText', forControlEvents:UIControlEventEditingChanged) @include_year_switch.addTarget(self, action:'didToggleSwitch', forControlEvents:UIControlEventValueChanged) @date_picker.addTarget(self, action:'didChangeDatePicker', forControlEvents:UIControlEventValueChanged) @gesture_recognizer.addTarget(self,action:"didTapPhoto") BRStyleSheet.styleLabel(@include_year_label,withType:'BRLabelTypeLarge') BRStyleSheet.styleRoundCorneredView @photo_container_view end def textFieldShouldReturn(sender) @name_text_field.resignFirstResponder false end def didChangeNameText #puts @name_text_field.text #self.birthday['name']=@name_text_field.text @birthday.name = @name_text_field.text updateSaveButton end def updateSaveButton @save_button.enabled = false unless @name_text_field.text @save_button.enabled = @name_text_field.text.length>0 if @name_text_field.text end def didToggleSwitch updateBirthdayDetails end def didChangeDatePicker #puts @date_picker.date #elf.birthday["birthdate"]= @date_picker.date updateBirthdayDetails end def didTapPhoto puts "photo was tapped" unless UIImagePickerController.isSourceTypeAvailable UIImagePickerControllerSourceTypeCamera puts "No camera detected!" pickPhoto return end actionSheet = UIActionSheet.alloc.initWithTitle(nil,delegate:self,cancelButtonTitle:"Cancel",destructiveButtonTitle:nil,otherButtonTitles:'Take a Photo','Pick from Photo Library', nil) actionSheet.showInView self.view end def actionSheet(actionSheet, didDismissWithButtonIndex:buttonIndex) return if buttonIndex == actionSheet.cancelButtonIndex case buttonIndex when 0 then takePhoto when 1 then pickPhoto end end def imagePicker @imagePicker ||= UIImagePickerController.alloc.init @imagePicker.delegate = self if @imagePicker return @imagePicker end def takePhoto imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera self.navigationController.presentViewController(@imagePicker,animated:true,completion:nil) end def pickPhoto imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary self.navigationController.presentViewController(@imagePicker,animated:true,completion:nil) end def imagePickerController(picker,didFinishPickingMediaWithInfo:info) picker.dismissViewControllerAnimated(true, completion:nil) #picker.dismissModalViewControllerAnimated(true) image = info[UIImagePickerControllerOriginalImage] @photo_view.image = image side = SIDE side *= UIScreen.mainScreen.scale thumbnail = image.createThumbnailToFillSize((CGSizeMake(side,side))) @photo_view.image = thumbnail @birthday.imageData =UIImageJPEGRepresentation(thumbnail,1.0) end def updateBirthdayDetails calendar = NSCalendar.currentCalendar components = calendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:@date_picker.date) @birthday.birthMonth = components.month @birthday.birthDay = components.day @birthday.birthYear = 0 @birthday.birthYear = components.year if @include_year_switch.on? @birthday.updateNextBirthdayAndAge end def saveAndDismiss BRDModel.sharedInstance.saveChanges BRDModel.sharedInstance.updateCachedBirthdays super end def cancelAndDismiss BRDModel.sharedInstance.cancelChanges super end =begin def self.respondToNotification p 'i responded' end =end #NSNotificationCenter.defaultCenter.addObserver(self, selector: 'respondToNotification', name: UIKeyboardWillShowNotification, object: nil) end class UIImage def createThumbnailToFillSize(size) mainImageSize = self.size repositionedImageSize = mainImageSize width_scaler = size.width/mainImageSize.width length_scaler = size.height/mainImageSize.height if width_scaler > length_scaler scaler = width_scaler; #repositionedImageSize.height = (size.height/scaler) else scaler = length_scaler; #repositionedImageSize.width = (size.width/scaler) end new_x = (( repositionedImageSize.width - mainImageSize.width)/2.0) * scaler new_y = (( repositionedImageSize.height - mainImageSize.height)/2.0) * scaler UIGraphicsBeginImageContext(size) self.drawInRect(CGRectMake(new_x,new_y,mainImageSize.width*scaler,mainImageSize.height*scaler)) thumb = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return thumb end end<file_sep>/app/brd_birthday_import.rb class BRDBirthdayImport attr_accessor :addressBookID,:birthDay,:birthMonth,:birthYear,:facebookID,:imageData,:name,:nextBirthday,:nextBirthdayAge,:picURL,:uid,:remainingDaysUntilNextBirthday,:birthdayTextToDisplay,:isBirthdayToday def initWithAddressBookRecord(addressBookRecord) a = init if a firstName = nil lastName = nil birthdate = nil recordID = ABRecordGetRecordID(addressBookRecord) firstName = ABRecordCopyValue(addressBookRecord,KABPersonFirstNameProperty) lastName = ABRecordCopyValue(addressBookRecord,KABPersonLastNameProperty) birthdate = ABRecordCopyValue(addressBookRecord,KABPersonBirthdayProperty) name = firstName.nil? ? lastName : firstName + ' ' + lastName a.name = name a.uid = "ab-#{recordID}" a.addressBookID = recordID a.birthDay = birthdate.day a.birthMonth = birthdate.month a.birthYear = birthdate.year updateNextBirthdayAndAge if nextBirthdayAge > 150 a.birthYear = 0 a.nextBirthdayAge = 0 end if ABPersonHasImageData(addressBookRecord) imageData = ABPersonCopyImageData(addressBookRecord) fullSizeImage = UIImage.imageWithData imageData side = 71.0 side *= UIScreen.mainScreen.scale thumbnail = fullSizeImage.createThumbnailToFillSize([side,side]) a.imageData = UIImageJPEGRepresentation(thumbnail,1.0) end end a end def initWithFacebookDictionary(dict) a = init if a a.name = dict['name'] a.uid = "fb-#{dict['id']}" a.facebookID ="#{dict['id']}" a.picURL ="http://graph.facebook.com/#{facebookID}/picture?type=large" birthDateString = dict['birthday'] birthdaySegments = birthDateString.split('/') a.birthDay = birthdaySegments[1].to_i a.birthMonth = birthdaySegments[0].to_i if birthdaySegments.size > 2 a.birthYear = birthdaySegments[2].to_i end a.updateNextBirthdayAndAge end a end def updateNextBirthdayAndAge now = NSDate.date calendar = NSCalendar.currentCalendar dateComponents = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents(dateComponents) dateComponents.day = birthDay.intValue dateComponents.month = birthMonth.intValue birthDayThisYear = calendar.dateFromComponents(dateComponents) if today.compare(birthDayThisYear) == NSOrderedDescending dateComponents.year += 1 self.nextBirthday = calendar.dateFromComponents(dateComponents) else self.nextBirthday = birthDayThisYear.copy end if self.birthYear.intValue > 0 self.nextBirthdayAge = NSNumber.numberWithInt(dateComponents.year - birthYear.intValue) else self.nextBirthdayAge = 0 end end def updateWithDefaults now = NSDate.date dateComponents = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) self.birthDay = dateComponents.day self.birthMonth = dateComponents.month self.birthYear = 0 updateNextBirthdayAndAge end def remainingDaysUntilNextBirthday now = NSDate.date calendar = NSCalendar.currentCalendar componentsToday = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents componentsToday timeDiffSecs = self.nextBirthday.timeIntervalSinceDate now days = (timeDiffSecs/(60.0*60.0*24.0)).floor end def isBirthdayToday remainingDaysUntilNextBirthday == 0 end def birthdayTextToDisplay now = NSDate.date calendar = NSCalendar.currentCalendar componentsToday = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents componentsToday components = calendar.components(NSMonthCalendarUnit|NSDayCalendarUnit,fromDate:today,toDate:self.nextBirthday,options:0) if components.month == 0 if components.day == 0 if self.nextBirthdayAge.intValue > 0 return "#{self.nextBirthdayAge} Today!" else return "Today!" end end if components.day == 1 if self.nextBirthdayAge.intValue > 0 return "#{self.nextBirthdayAge} Tomorrow!" else return "Tomorrow!" end end end text = "" if self.nextBirthdayAge > 0 text = "#{self.nextBirthdayAge} on" end dateFormatterPartial ||= NSDateFormatter.alloc.init.setDateFormat("MMM d") return (text + " "+ dateFormatterPartial.stringFromDate(nextBirthday)) end end<file_sep>/app/br_settings_view_controller.rb class BRSettingsViewController < UITableViewController def viewDidLoad super p @tableCellDaysBefore p @tableCellNotificationTime @doneButton = self.navigationItem.rightBarButtonItem @doneButton.target = self @doneButton.action = 'didClickDoneButton:' backgroundView = UIImageView.alloc.initWithImage(UIImage.imageNamed('app-background.png')) tableView.backgroundView = backgroundView end def viewWillAppear(animated) super cellArray = tableView.visibleCells @tableCellDaysBefore = cellArray.first @tableCellNotificationTime = cellArray.last @tableCellNotificationTime.detailTextLabel.text = BRDSettings.sharedInstance.titleForNotificationTime @tableCellDaysBefore.detailTextLabel.text = BRDSettings.sharedInstance.titleForDaysBefore(BRDSettings.sharedInstance.daysBefore) end def didClickDoneButton(sender) BRDModel.sharedInstance.updateCachedBirthdays self.dismissViewControllerAnimated(true, completion: nil) end def createSectionHeaderWithLabel(text) view = UIView.alloc.initWithFrame [[0,0],[320,40.0]] label = UILabel.alloc.initWithFrame [[10.0,15.0],[300.0,20.0]] label.backgroundColor = UIColor.clearColor BRStyleSheet.styleLabel(label,withType:'BRLabelTypeLarge') label.text = text view.addSubview label view end def tableView(tableView,heightForHeaderInSection:section ) 40.0 end def tableView(tableView,viewForHeaderInSection:section) createSectionHeaderWithLabel 'Reminders' end end<file_sep>/app/BRBirthdayDetailViewController.rb class BRBirthdayDetailViewController < BRCoreViewController attr_accessor :birthday def initWithCoder(aDecoder) a = super if a #@birthday = BRDBirthday.new end return a end def viewDidLoad super @photo_view = view.viewWithTag 1 @birthday_label = view.viewWithTag 2 @notes_title_label = view.viewWithTag 3 @notes_text_label = view.viewWithTag 4 @remaining_days_image_view = view.viewWithTag 5 @remaining_days_label = view.viewWithTag 6 @remaining_days_subtext_label = view.viewWithTag 7 @scroll_view = view.viewWithTag 13 @facebook_button = view.viewWithTag 8 @facebook_button.addTarget(self,action:'facebookButtonTapped:',forControlEvents:UIControlEventTouchUpInside) @call_button = view.viewWithTag 9 @call_button.addTarget(self,action:'callButtonTapped:',forControlEvents:UIControlEventTouchUpInside) @sms_button = view.viewWithTag 10 @sms_button.addTarget(self,action:'smsButtonTapped:',forControlEvents:UIControlEventTouchUpInside) @email_button = view.viewWithTag 11 @email_button.addTarget(self,action:'emailButtonTapped:',forControlEvents:UIControlEventTouchUpInside) @delete_button = view.viewWithTag 12 @delete_button.addTarget(self,action:'deleteButtonTapped:',forControlEvents:UIControlEventTouchUpInside) BRStyleSheet.styleRoundCorneredView(@photo_view) BRStyleSheet.styleLabel(@birthday_label,withType:'BRLabelTypeLarge') BRStyleSheet.styleLabel(@notes_title_label,withType:'BRLabelTypeLarge') BRStyleSheet.styleLabel(@notes_text_label,withType:'BRLabelTypeLarge') BRStyleSheet.styleLabel(@remaining_days_label,withType:'BRLabelTypeDaysUntilBirthday') BRStyleSheet.styleLabel(@remaining_days_subtext_label,withType:'BRLabelTypeDaysUntilBirthdaySubText') end def viewWillAppear(animated) super #puts 'viewWillAppear' #name = @birthday['name'] self.title = birthday.name image = UIImage.imageWithData(birthday.imageData) if birthday.imageData == nil if birthday.picURL && birthday.picURL.length > 0 @photo_view.setImageWithRemoteFileURL(birthday.picURL,placeHolderImage:(UIImage.imageNamed('icon-birthday-cake.png'))) else @photo_view.image = UIImage.imageNamed('icon-birthday-cake.png') end else @photo_view.image = UIImage.imageWithData(@birthday.imageData) end days = birthday.remainingDaysUntilNextBirthday if days == 0 @remaining_days_label.text = @remaining_days_subtext_label.text = '' @remaining_days_image_view.image = UIImage.imageNamed 'icon-birthday-cake.png' else @remaining_days_label.text = "#{days}" @remaining_days_subtext_label.text = days == 1 ? 'more day' : 'more days' @remaining_days_image_view.image = UIImage.imageNamed 'icon-days-remaining.png' end @birthday_label.text = birthday.birthdayTextToDisplay notes = (birthday.notes && birthday.notes.length > 0) ? birthday.notes : "" cY = @notes_text_label.frame.origin.y #notesLabelSize = notes.sizeWithFont(@notes_text_label.font, constrainedToSize: [300.0,300.0], lineBreakMode: NSLineBreakByWordWrapping) #frame = @notes_text_label.frame #frame.size.height = notesLabelSize.height #@notes_text_label.frame = frame @notes_text_label.text = notes @notes_text_label.sizeToFit frame = @notes_text_label.frame cY += frame.size.height cY += 10.0 buttonGap = 6.0 cY += buttonGap * 2 buttonsToShow = [@facebook_button,@sms_button,@call_button,@email_button,@delete_button] buttonsToHide = [] if birthday.facebookID == nil buttonsToShow.delete(@facebook_button) buttonsToHide.push(@facebook_button) end if callLink == nil buttonsToShow.delete(@call_button) buttonsToHide.push(@call_button) end if smsLink == nil buttonsToShow.delete(@sms_button) buttonsToHide.push(@sms_button) end if emailLink == nil buttonsToShow.delete(@email_button) buttonsToHide.push(@email_button) end for button in buttonsToHide do button.hidden = true end for button in buttonsToShow do button.hidden = false frame = button.frame frame.origin.y = cY button.frame = frame cY += button.frame.size.height + buttonGap end @scroll_view.contentSize = [320,cY] end def callButtonTapped link = callLink UIApplication.sharedApplication.openURL(NSURL.URLWithString(link)) end def smsButtonTapped link = smsLink UIApplication.sharedApplication.openURL(NSURL.URLWithString(link)) end def emailButtonTapped link = emailLink UIApplication.sharedApplication.openURL(NSURL.URLWithString(link)) end def deleteButtonTapped(sender) actionSheet = UIActionSheet.alloc.initWithTitle(nil, delegate: self, cancelButtonTitle: 'Cancel', destructiveButtonTitle: "Delete #{birthday.name}", otherButtonTitles: nil) actionSheet.showInView view end def facebookButtonTapped(sender) #BRDModel.sharedInstance.authenticateWithFacebook BRDModel.sharedInstance.postToFacebookWall('nil',withFacebookID:self.birthday.facebookID) end def actionSheet(actionSheet,willDismissWithButtonIndex:buttonIndex) return if buttonIndex == actionSheet.cancelButtonIndex context = BRDModel.sharedInstance.managedObjectContext context.deleteObject(self.birthday) BRDModel.sharedInstance.saveChanges navigationController.popViewControllerAnimated(true) end def prepareForSegue(segue,sender:sender) identifier =segue.identifier if identifier == 'EditBirthday' navigation_controller = segue.destinationViewController birthdayEditViewController = navigation_controller.topViewController birthdayEditViewController.birthday = birthday elsif identifier == 'EditNotes' navigationController = segue.destinationViewController birthdayNotesEditViewController =navigationController.topViewController birthdayNotesEditViewController.birthday = birthday end end def telephoneNumber addressBook = ABAddressBookCreateWithOptions(nil,nil) record = ABAddressBookGetPersonWithRecordID(addressBook,birthday.addressBookID) multi = ABRecordCopyValue(record,KABPersonPhoneProperty) if ABMultiValueGetCount(multi) > 0 telephone = ABMultiValueCopyValueAtIndex(multi,0) tel = telephone.gsub(' ','') puts telephone end tel end def callLink if !birthday.addressBookID || birthday.addressBookID == 0 return nil end telnumber = telephoneNumber return nil unless telnumber callLink = "tel:#{telnumber}" if UIApplication.sharedApplication.canOpenURL(NSURL.URLWithString callLink) return callLink else return nil end end def smsLink if !birthday.addressBookID || birthday.addressBookID == 0 return nil end telnumber = telephoneNumber return nil unless telnumber smsLink = "sms:#{telnumber}" if UIApplication.sharedApplication.canOpenURL(NSURL.URLWithString smsLink) return callLink else return nil end end def emailLink addressBook = ABAddressBookCreateWithOptions(nil,nil) record = ABAddressBookGetPersonWithRecordID(addressBook,(birthday.addressBookID || 0)) multi = ABRecordCopyValue(record,KABPersonEmailProperty) if ABMultiValueGetCount(multi) > 0 email = ABMultiValueCopyValueAtIndex(multi,0) em = email.gsub(' ','') puts em end if em emailLink = "mailto:#{em}" emailLink += '?subject=Happy%20Birthday' puts" this is emailLink :#{emailLink}" puts UIApplication.sharedApplication.canOpenURL(NSURL.URLWithString 'mailto:<EMAIL>') if UIApplication.sharedApplication.canOpenURL(NSURL.URLWithString(emailLink)) return emailLink end end return nil end end<file_sep>/app/br_import_address_book_view_controller.rb class BRImportAddressBookViewController < BRImportViewController def viewWillAppear(animated) super BRDModel.sharedInstance.fetchAddressBookBirthdays NSNotificationCenter.defaultCenter.addObserver(self, selector:'handleAddressBookBirthdaysDidUpdate:', name:'BRNotificationAddressBookBirthdaysDidUpdate', object: BRDModel.sharedInstance) puts NSNotificationCenter.defaultCenter true end def viewWillDisappear(animated) puts 'dissappear called' super NSNotificationCenter.defaultCenter.removeObserver(self,name:'BRNotificationAddressBookBirthdaysDidUpdate', object: BRDModel.sharedInstance) end def handleAddressBookBirthdaysDidUpdate(notification) puts 'handleAddressBookBirthdaysDidUpdate' userInfo = notification.userInfo self.birthdays = userInfo['birthdays'] @table_view.reloadData if birthdays.size == 0 alert = UIAlertView.alloc.initWithTitle(nil, message: 'Sorry No Birthdays Found in your addressbook', delegate: nil, cancelButtonTitle: nil, otherButtonTitles:'OK',nil) alert.show end end end<file_sep>/app/br_notification_time_view_controller.rb class BRNotificationTimeViewController < BRCoreViewController def viewDidLoad super @whatTimeLabel = view.viewWithTag 1 @timePicker = view.viewWithTag 2 @timePicker.addTarget(self, action:'didChangeTime', forControlEvents:UIControlEventValueChanged) BRStyleSheet.styleLabel(@whatTimeLabel,withType: 'BRLabelTypeLarge') end def viewWillAppear(animated) super hour = BRDSettings.sharedInstance.notificationHour minute = BRDSettings.sharedInstance.notificationMinute components = NSCalendar.currentCalendar.components(NSHourCalendarUnit|NSMinuteCalendarUnit, fromDate: NSDate.date) components.hour = hour components.minute = minute @timePicker.date = NSCalendar.currentCalendar.dateFromComponents(components) end def didChangeTime components = NSCalendar.currentCalendar.components(NSHourCalendarUnit|NSMinuteCalendarUnit,fromDate:@timePicker.date) BRDSettings.sharedInstance.notificationHour = components.hour BRDSettings.sharedInstance.notificationMinute = components.minute end end<file_sep>/app/brd_birthday.rb class BRDBirthday < NSManagedObject #attr_reader :remainingDaysUntilNextBirthday, #:birthdayTextToDisplay, #:isBirthdayToday def updateNextBirthdayAndAge now = NSDate.date calendar = NSCalendar.currentCalendar dateComponents = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents(dateComponents) dateComponents.day = birthDay.intValue dateComponents.month = birthMonth.intValue birthDayThisYear = calendar.dateFromComponents(dateComponents) if today.compare(birthDayThisYear) == NSOrderedDescending dateComponents.year += 1 self.nextBirthday = calendar.dateFromComponents(dateComponents) else self.nextBirthday = birthDayThisYear.copy end if self.birthYear.intValue > 0 self.nextBirthdayAge = NSNumber.numberWithInt(dateComponents.year - birthYear.intValue) else self.nextBirthdayAge = 0 end end def updateWithDefaults now = NSDate.date dateComponents = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) self.birthDay = dateComponents.day self.birthMonth = dateComponents.month self.birthYear = 0 updateNextBirthdayAndAge end def remainingDaysUntilNextBirthday now = NSDate.date calendar = NSCalendar.currentCalendar componentsToday = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents componentsToday timeDiffSecs = self.nextBirthday.timeIntervalSinceDate now days = (timeDiffSecs/(60.0*60.0*24.0)).floor end def isBirthdayToday remainingDaysUntilNextBirthday == 0 end def birthdayTextToDisplay now = NSDate.date calendar = NSCalendar.currentCalendar componentsToday = NSCalendar.currentCalendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, fromDate:now) today = calendar.dateFromComponents componentsToday components = calendar.components(NSMonthCalendarUnit|NSDayCalendarUnit,fromDate:today,toDate:self.nextBirthday,options:0) if components.month == 0 if components.day == 0 if self.nextBirthdayAge.intValue > 0 return "#{self.nextBirthdayAge} Today!" else return "Today!" end end if components.day == 1 if self.nextBirthdayAge.intValue > 0 return "#{self.nextBirthdayAge} Tomorrow!" else return "Tomorrow!" end end end text = "" if self.nextBirthdayAge > 0 text = "#{self.nextBirthdayAge} on" end dateFormatterPartial ||= NSDateFormatter.alloc.init.setDateFormat("MMM d") return (text + " "+ dateFormatterPartial.stringFromDate(nextBirthday)) end def self.entity @entity ||= begin entity = NSEntityDescription.new entity.name = 'BirthdayReminder' entity.managedObjectClassName = 'BRDBirthday' entity.properties = ['addressBookID', NSInteger16AttributeType, 'birthDay', NSInteger16AttributeType, 'birthMonth', NSInteger16AttributeType, 'birthYear',NSInteger16AttributeType, 'facebookID',NSStringAttributeType, 'imageData', NSBinaryDataAttributeType, 'name',NSStringAttributeType, 'nextBirthday',NSDateAttributeType, 'nextBirthdayAge',NSInteger16AttributeType, 'notes',NSStringAttributeType, 'picURL',NSStringAttributeType, 'uid',NSStringAttributeType ].each_slice(2).map do |name, type| property = NSAttributeDescription.alloc.init property.name = name property.attributeType = type property.optional = true property end @entity = entity end @entity end end
80fd12ee394912d51b01b195312a25a27ec8a3b1
[ "Markdown", "Ruby" ]
22
Ruby
eskadah/birthday_reminder
a16dd2155c8620056635aa941c9d9c2db715b064
1ccb3f491beec3e75c6e1253484aa2c61382c96c
refs/heads/master
<repo_name>jbonofre/blueprint-test<file_sep>/bundle/src/main/java/net/nanthrax/test/blueprint/MyBundle.java package net.nanthrax.test.blueprint; import java.util.Properties; public class MyBundle { private Properties properties; public void setProperties(Properties properties) { this.properties = properties; } public void init() { if (properties == null) { throw new IllegalStateException("NULL"); } for (int i = 1; i <= 50; i++) { if (properties.get("TST" + i) == null) { System.err.println("NULL"); throw new IllegalStateException("TST" + i + " is null"); } if (properties.get("TST" + i).equals("")) { System.err.println("EMPTY"); throw new IllegalStateException("TST" + i + " is empty"); } if (!properties.get("TST" + i).equals("VL" + i)) { System.err.println("NOT MATCH"); throw new IllegalStateException("TST" + i + "/VL" + i + " not match"); } } for (int i = 1; i <= 50; i++) { System.out.println("= TST" + i + "=" + properties.get("TST" + i)); } System.out.println("===> ALL OK"); } } <file_sep>/runner/src/main/java/net/nanthrax/test/blueprint/runner/Runner.java package net.nanthrax.test.blueprint.runner; import org.apache.karaf.features.ConfigInfo; import org.apache.karaf.features.Feature; import org.apache.karaf.features.FeaturesService; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import java.net.URI; import java.util.Dictionary; import java.util.EnumSet; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Optional; public class Runner { private final static URI REPO = URI.create("mvn:net.nanthrax.test/my.features/1.0-SNAPSHOT/xml"); private final static String FEATURE = "test"; private final static String FEATURE_VERSION = "1.0-SNAPSHOT"; private final static String CONFIG_PID = "persistentId"; private FeaturesService featuresService; private ConfigurationAdmin configurationAdmin; public FeaturesService getFeaturesService() { return featuresService; } public void setFeaturesService(FeaturesService featuresService) { this.featuresService = featuresService; } public ConfigurationAdmin getConfigurationAdmin() { return configurationAdmin; } public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { this.configurationAdmin = configurationAdmin; } public void init() throws Exception { System.out.println("Runner.init"); featuresService.addRepository(REPO, false); Feature feature = featuresService.getFeature(FEATURE, FEATURE_VERSION); Map<String, String> properties = new HashMap(); for (ConfigInfo configInfo : feature.getConfigurations()) { for (Map.Entry entry : configInfo.getProperties().entrySet()) { properties.put(entry.getKey().toString(), entry.getValue().toString()); } } Configuration configuration = configurationAdmin.getConfiguration(CONFIG_PID, null); Dictionary<String, Object> dictionary = Optional.ofNullable(configuration.getProperties()).orElse(new Hashtable()); for (Map.Entry entry : properties.entrySet()) { dictionary.put(entry.getKey().toString(), entry.getValue()); } System.out.println("before configuration.update"); configuration.update(dictionary); System.out.println("before featuresService.installFeature"); featuresService.installFeature(FEATURE, FEATURE_VERSION); System.out.println("after featuresService.installFeature"); } public void destroy() throws Exception { System.out.println("Runner.destroy"); featuresService.uninstallFeature(FEATURE, FEATURE_VERSION); Configuration configuration = configurationAdmin.getConfiguration(CONFIG_PID, null); configuration.delete(); featuresService.removeRepository(REPO, false); } }
7f413d2cce00cffdd428e95608af10599c1fbafc
[ "Java" ]
2
Java
jbonofre/blueprint-test
7b595a393a837df02cb82c833ebbc8390bf258f8
da23fea79f611091497453172511e7f589065d49
refs/heads/master
<repo_name>keynumber/vimconf<file_sep>/myscript/plugin/cpp.py function! GenSwitchCase() range python << EOF import vim buffer = vim.current.buffer def GetItems(firstline, lastline): items = [] idx = firstline while (idx < lastline): items = items + buffer[idx].split() idx = idx + 1 return items def GenSwitchCase(item_list, prefix): lines = [prefix + "switch () {"] for item in item_list: lines.append(prefix + "case " + item + ":") lines.append(prefix + "{") lines.append(prefix + " break;") lines.append(prefix + "}") lines.append(prefix + "default:") lines.append(prefix + "{") lines.append(prefix + " break;") lines.append(prefix + "}") lines.append(prefix + "}") return lines firstline = int(vim.eval("a:firstline")) - 1 lastline= int(vim.eval("a:lastline")) tabstop = int(vim.eval("&tabstop")) space_num = 0 for i in buffer[firstline]: if (i == ' '): space_num = space_num + 1 elif (i == '\t'): space_num += tabstop else: break prefix = " " * space_num item_list = GetItems(firstline, lastline) lines = GenSwitchCase(item_list, prefix) del buffer[firstline:lastline] buffer.append(lines, firstline) vim.current.window.cursor = (firstline+1, 0) vim.command("normal f(") EOF endfunction
9e271de88c8f114b35660c157116b87e2a2e8cfc
[ "Python" ]
1
Python
keynumber/vimconf
472ff37dbfcfb10d3520320e454f7db23f5a3754
71d6dc8e65984f634e074010f5176bc4f84320a3
refs/heads/main
<file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/todo/view',['as' => 'todo.view','uses' => 'App\Http\Controllers\TodoController@view']); Route::Post('/todo/save',['as' => 'todo.save','uses' => 'App\Http\Controllers\TodoController@save']); Route::get('/completed/{id}','App\Http\Controllers\TodoController@complete'); Route::get('/notcompleted/{id}','App\Http\Controllers\TodoController@notcomplete'); Route::get('/deleted/{id}','App\Http\Controllers\TodoController@delete');<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Todo; class TodoController extends Controller { // public function view() { $data=Todo::all(); return view('todo')->with('datas',$data); } public function save(Request $request) { $task=new Todo; $this -> validate($request,[ 'task'=>'required', ]); $task->task=$request->task; $task->save(); $data=Todo::all(); return redirect()->back()->with('datas',$data); } public function complete($id) { $task=Todo::find($id); $task->iscompleted=1; $task->save(); return redirect()->back(); } public function notcomplete($id) { $task=Todo::find($id); $task->iscompleted=0; $task->save(); return redirect()->back(); } public function delete($id) { $task=Todo::find($id); $task->delete(); return redirect()->back(); } }
263dfb9180d084d507dc3a44c15a1deffeb4a755
[ "PHP" ]
2
PHP
KanchanaK98/todoApplication
6c46d8c1b311ff429f3f24b1e4ad6dd24e3c78a4
d12258f6ed3f66838cb2ec02b7ebb0ea0e049403
refs/heads/master
<repo_name>josesanchis16/plantillaPHP<file_sep>/src/Kernel.php <?php namespace App; use App\routing\Web; class Kernel { public function __construct() { $logManager = new LogManager(); $logManager->info('Starting app'); $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $routerManager = new RouterManager(); $routerManager->dispatch($httpMethod, $uri, Web::getDispatcher()); } } <file_sep>/src/controllers/AboutController.php <?php namespace App\controllers; use App\ViewManager; class AboutController { public function index() { $viewManager = new ViewManager(); $viewManager->renderTemplate('about.twig.html'); } } <file_sep>/public/index.php <?php require_once dirname(__DIR__).'/vendor/autoload.php'; use App\Kernel; $kernel = new Kernel();<file_sep>/src/controllers/HomeController.php <?php namespace App\controllers; use App\ViewManager; class HomeController { public function index() { $viewManager = new ViewManager(); $viewManager->renderTemplate('index.twig.html'); } } <file_sep>/src/controllers/RegisterController.php <?php namespace App\controllers; use App\ViewManager; class RegisterController { public function index(){ $viewManager = new ViewManager(); $viewManager->renderTemplate('register.twig.html'); } }<file_sep>/README.md # Plantilla PHP Esta es una plantilla para proyectos PHP. ## Sobre En este proyecto utilizamos [Composer](https://getcomposer.org/) para la gestion de dependencias. Lista de paquetes: - [Twig](https://twig.symfony.com/) - [Monolog](https://github.com/Seldaek/monolog) - [Kint](https://github.com/kint-php/kint) - [Fast-Router](https://github.com/nikic/FastRoute)<file_sep>/src/controllers/LoginController.php <?php namespace App\controllers; use App\ViewManager; class LoginController { public function index() { $viewManager = new ViewManager(); $viewManager->renderTemplate('login.twig.html'); } } <file_sep>/src/routing/Web.php <?php namespace App\routing; use FastRoute\Dispatcher; class Web { public static function getDispatcher():Dispatcher{ return \FastRoute\simpleDispatcher( function(\FastRoute\RouteCollector $route){ $route->addRoute('GET', '/', ['App\controllers\HomeController', 'index']); $route->addRoute('GET', '/about', ['App\controllers\AboutController', 'index']); $route->addRoute('GET', '/login', ['App\controllers\LoginController', 'index']); $route->addRoute('GET', '/register', ['App\controllers\RegisterController', 'index']); } ); } }
774429de86e253826381b01470f852de2bf6e601
[ "Markdown", "PHP" ]
8
PHP
josesanchis16/plantillaPHP
fe06488bed8d2b02dd5a0829952b47115b85f036
df957cdb2b94e64588a8abdd031b4f5879aaad8d
refs/heads/master
<repo_name>mipmip/bitbar-hugo<file_sep>/commands/menu.go package commands import ( "fmt" "os" "github.com/johnmccabe/bitbar" "bitbar-hugo/assets" "github.com/spf13/cobra" "bitbar-hugo/config" "bitbar-hugo/hugo" ) func init() { rootCmd.AddCommand(menuCmd) } var menuCmd = &cobra.Command{ Use: "menu", Run: runMenu, Hidden: true, } func themeAppropriateIcon() string { if _, ok := os.LookupEnv("BitBarDarkMode"); ok { return assets.WhiteLogo } return assets.MonoLogo } func runMenu(cmd *cobra.Command, args []string) { ex, _ := os.Executable() menubarIcon := themeAppropriateIcon() plugin := bitbar.New() plugin.StatusLine("").Image(menubarIcon) menu := plugin.NewSubMenu() menu.Line("").Image(assets.Logo) menu.Line("---") if config.ConfigFileExists() { cfg, err := config.Read() if err != nil { menu.Line("Fout in configuratiebestand.") menu.Line("Mail Pim").Bash("/usr/bin/open").Params([]string{"mailto:<EMAIL>?subject=help"}).Terminal(false) } else { if cfg.LiveUrl != "" { menu.Line(fmt.Sprintf("Open %s", cfg.LiveUrl )).Bash("/usr/bin/open").Params([]string{cfg.LiveUrl}).Terminal(false) } if hugo.HugoBinExists() { if hugo.HugoRunning() { menu.Line(fmt.Sprintf("Open %s in conceptversie", cfg.SiteName)).Bash("/usr/bin/open").Params([]string{"http://localhost:1313"}).Terminal(false) menu.Line(fmt.Sprintf("Stop server")).Bash(ex).Params([]string{"killhugo"}).Terminal(false).Refresh(true) } else { menu.Line(fmt.Sprintf("Start server")).Terminal(false).Refresh(true).Bash(fmt.Sprintf(hugo.HugoBinPath())).Params([]string{ "server", "-D", "-s", cfg.HugoDir}) } } else { menu.Line(fmt.Sprintf("Geen Hugo gevonden")) } // menu.Line("submenu") // statsMenu := menu.NewSubMenu() // statsMenu.Line("Actions").Bash("/usr/bin/open").Params([]string{"http://rusland1.nl"}).Terminal(false) // statsMenu.HR() // statsMenu.Line("Blabla") } } else { menu.Line("Geen configuratiebestand.") menu.Line("Mail Pim").Bash("/usr/bin/open").Params([]string{"mailto:<EMAIL>?subject=help"}).Terminal(false) } menu.Line("---") menu.Line("Refresh..").Refresh(true) fmt.Print(plugin.Render()) } <file_sep>/assets/logo.go package assets // Logo base64 encoded OpenFaaS logo const Logo string = "<KEY> // MonoLogo is a base64 representation of a monochrome Logo const MonoLogo string = "<KEY> // BlueLogo is a base64 representation of a monochrome blue log - #067FD1 const BlueLogo string = "<KEY> // RedLogo is a base64 representation of a monochrome red logo - #DA0002 const RedLogo string = "<KEY> // WhiteLogo is a base64 representation of a monochrome white logo - #ffffff const WhiteLogo string = "<KEY> <file_sep>/commands/test.go package commands import ( "fmt" "os" // "os/exec" "bitbar-hugo/config" "bitbar-hugo/hugo" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(killHugoCmd) } var killHugoCmd = &cobra.Command{ Use: "test", Run: runTest, } func runTest(cmd *cobra.Command, args []string) { cfg, err := config.Read() if err != nil { os.Exit(1) } fmt.Println(cfg) fmt.Println(config.File()) if hugo.HugoBinExists() { fmt.Println(hugo.HugoBinPath()) } else { fmt.Println("can't start server") } // out, err := exec.Command("bash", "-c", "/bin/ps ax | /usr/bin/grep \"bitbar-hugo\\/hugo\"| /usr/bin/grep -v grep | /usr/bin/head -n1 | /usr/bin/cut -d\" \" -f 1").Output() //fmt.Println(out) //fmt.Printf("The out is %s", out) //fmt.Println(err) hugo.KillHugo() ex, _ := os.Executable() fmt.Println(ex) } <file_sep>/config/types.go package config type Config struct { HugoDir string SiteName string LiveUrl string } <file_sep>/main.go package main import "bitbar-hugo/commands" //import "github.com/mipmip/bitbar-hugo/commands" func main() { commands.Execute() } <file_sep>/hugo/hugo.go package hugo import ( "bitbar-hugo/config" "os" "os/exec" "fmt" "path" "path/filepath" ) func HugoBinExists() bool { hugofile := path.Clean(filepath.Join(config.Dir(), "hugo")) if stat, err := os.Stat(hugofile); err == nil && stat.Mode().IsRegular() { return true } else { return false } } func HugoBinPath() string { return path.Clean(filepath.Join(config.Dir(), "hugo")) } func KillHugo() bool { pid := HugoPid() fmt.Println(pid) exec.Command("bash", "-c", fmt.Sprintf("/bin/kill %s",pid)).Output() //fmt.Printf("The kill is %s", out2) //fmt.Println(err2) return true } func HugoPid() string { out, _ := exec.Command("bash", "-c", "/bin/ps ax | /usr/bin/grep \"bitbar-hugo\\/hugo\"| /usr/bin/grep -v grep | /usr/bin/head -n1 | /usr/bin/cut -d\" \" -f 1").Output() pid := string(out) if fmt.Sprintf("%s", pid) != "<nil>" { return pid } else { return "" } /* if pid != nil { return pid } else { return "" } */ } func HugoRunning() bool { if HugoPid() != "" { return true } else { return false } } <file_sep>/commands/install.go package commands // defaults read com.matryer.BitBar pluginsDirectory import ( "fmt" "os" "os/exec" "strings" "bitbar-hugo/config" "github.com/spf13/cobra" "gopkg.in/AlecAivazis/survey.v1" ) func init() { rootCmd.AddCommand(installCmd) } var installCmd = &cobra.Command{ Use: "install", Short: "TODO", Example: `TODO`, Long: `TODO`, Run: runInstall, } var defaultRefreshRate = "30s" func runInstall(cmd *cobra.Command, args []string) { ex, _ := os.Executable() installQuestions := []*survey.Question{ { Name: "refreshRate", Prompt: &survey.Input{Message: "Refresh rate?", Default: defaultRefreshRate, Help: "Plugin refresh rate, for example: 30s, 1m, 5m"}, }, } // the answers will be written to this struct answers := struct { RefreshRate string }{} // perform the questions err := survey.Ask(installQuestions, &answers) if err != nil { fmt.Println(err.Error()) os.Exit(1) } pluginDir, err := getPluginDir() if err != nil { fmt.Printf("Did you install bitbar? %v", err) os.Exit(1) } errConfigDir := config.EnsureConfigDir() if(errConfigDir!=nil){ fmt.Printf("can't create configdir") os.Exit(1) } pluginSymlink := fmt.Sprintf("%s/hugo-bitbar.%s", pluginDir, answers.RefreshRate) err = os.Symlink(ex, pluginSymlink) if err != nil { fmt.Printf("Unable to create symlink: %s for binary: %s", pluginSymlink, ex) os.Exit(1) } /* cmdCurl := exec.Command("curl", "https://github.com/gohugoio/hugo/releases/download/v1.55.0/hugo_0.55.0_macOS-64bit.tar.gz", "-L", "-o", config.Dir()+"/hugo.tar.gz") errCurl := cmdCurl.Run() if(errCurl != nil){ fmt.Printf("Unable to download hugo") os.Exit(1) } cmdTar2 := "/usr/bin/tar xzf /tmp/hugo.tar.gz -C ~/.bitbar-hugo" fmt.Printf("%s", cmdTar2) cmdTar := exec.Command("/bin/sh", "-c", "tar", "xzvf", "~/.bitbar-hugo/hugo.tar.gz") errTar := cmdTar.Run() if(errTar != nil){ fmt.Printf("Unable to extract hugo:, %s", errTar) os.Exit(1) } */ } func getPluginDir() (string, error) { cmdName := "/usr/bin/defaults" cmdArgs := []string{"read", "com.matryer.BitBar", "pluginsDirectory"} cmdOut, err := exec.Command(cmdName, cmdArgs...).Output() if err != nil { return "", fmt.Errorf("unable to determine pluginsDirectory: %v, %s", err, string(cmdOut)) } dir := strings.TrimRight(string(cmdOut), "\n") if !dirExists(dir) { return "", fmt.Errorf("unable to check if dir exists: %v, %s", err, dir) } return dir, nil } func dirExists(path string) bool { stat, err := os.Stat(path) if err == nil && stat.IsDir() { return true } return false } <file_sep>/commands/killhugo.go package commands import ( "bitbar-hugo/hugo" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(startHugoCmd) } var startHugoCmd = &cobra.Command{ Use: "killhugo", Run: runKillHugo, } func runKillHugo(cmd *cobra.Command, args []string) { hugo.KillHugo() } <file_sep>/config/config.go package config import ( "os" "path" "path/filepath" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/viper" ) const DefaultDir string = "~/.bitbar-hugo" const yamlFile = "config.yml" func Dir() string { cfgPath, _ := homedir.Expand(DefaultDir) return path.Clean(cfgPath) } func File() string { return path.Clean(filepath.Join(Dir(), yamlFile)) } func ConfigDirExists() bool { dir := Dir() if stat, err := os.Stat(dir); err == nil && stat.IsDir() { return true } else { return false } } func ConfigFileExists() bool { file := File() if stat, err := os.Stat(file); err == nil && stat.Mode().IsRegular() { return true } else { return false } } // EnsureConfigDir creates a configDir() if it doesn't already exist func EnsureConfigDir() error { dir := Dir() if stat, err := os.Stat(dir); err == nil && stat.IsDir() { return nil } err := os.Mkdir(dir, 0700) if err != nil { return err } return nil } // Read config from the specified dir returning a slice of OpenFaaS instances func Read() (Config, error) { viper.SetDefault("hugo_dir", "") viper.SetDefault("site_name", "website") viper.SetDefault("live_url", "") viper.SetConfigName("config") viper.SetConfigFile(File()) err := viper.ReadInConfig() viper.SetConfigType("yaml") if err == nil { return Config{ HugoDir: viper.Get("hugo_dir").(string), SiteName: viper.Get("site_name").(string), LiveUrl: viper.Get("live_url").(string), }, nil } else { return Config{}, err } } <file_sep>/README.md # BitBar Hugo
f9ab215b639a4ccea0dc231bd8aaf11cc907b078
[ "Markdown", "Go" ]
10
Go
mipmip/bitbar-hugo
3eb98f00ce63dbc88a28bc7229be898e7ad0c95d
720702bdacb42fa50c94acc4cd4752693fa22e94
refs/heads/main
<repo_name>matthewmorales401/Uber-Career-Prep-Homework-Matthew-Morales<file_sep>/Assignment-1/Part2/Part2.py from collections import Counter def isStringPermutation(s1: str, s2: str) -> bool: counter = {} counter1 = {} for i in s1: if i in counter: counter[i] += 1 else: counter[i] = 1 for j in s2: if j in counter1: counter1[j] += 1 else: counter1[j] = 1 return counter == counter1 def isStringPermutationAlternative(s1: str, s2: str) -> bool: return Counter(s1) == Counter(s2) def pairsThatEqualSum(inputArray: list, targetSum: int) -> list: hashmap = {} pairs = [] for i in range(len(inputArray)): if inputArray[i] in hashmap: pairs.append((hashmap[inputArray[i]], i+1)) else: hashmap[targetSum-inputArray[i]] = inputArray[i] return pairs print("String Permuation Check: ") print(isStringPermutation("asdf", "fsda")) print(isStringPermutation("asdf", "fsa")) print(isStringPermutation("asdf", "fsax")) # print(isStringPermutationAlternative("asdf", "fsda")) # print(isStringPermutationAlternative("asdf", "fsa")) # print(isStringPermutationAlternative("asdf", "fsax")) print("\nPairs that equal sum:") print(pairsThatEqualSum([1,2,3,4,5], 5)) print(pairsThatEqualSum([1,2,3,4,5], 1)) print(pairsThatEqualSum([1,2,3,4,5], 7))<file_sep>/README.md # Uber-Career-Prep-Homework-Matthew-Morales For Uber Career Prep <file_sep>/HW2/Part1/part1.py class Tree(object): def __init__(self, root): self.root = root class TreeNode(object): def __init__(self, data, left, right): self.data = data self.left = left self.right = right # Ex 1 Print Tree recursively def printTree(node): if node is None: return printTree(node.left) print(node.data) printTree(node.left) # Ex 2 Prints All Employees Iteratively class OrganizationStructure(object): def __init__(self, ceo): self.employee = ceo class Employee(object): def __init__(self, name, title): self.name = name self.title = title self.directReports = [] def printLevel(employees): if employees: level = [employees] while level: queue = [] for employee in level: if employee.left: queue.append(employee.left) if employee.right: queue.append(employee.right) print("Name: " + employee.name + ", Title: " + employee.title) level = queue #Ex 3 Similar to ex 2, but just gauging the level depth: class OrganizationStructure(object): def __init__(self, ceo): self.employee = ceo class Employee(object): def __init__(self, name, title): self.name = name self.title = title self.directReports = [] def printNumberOfLevels(employees): number = 0 if employees: level = [employees] while level: queue = [] number += 1 for employee in level: if employee.left: queue.append(employee.left) if employee.right: queue.append(employee.right) level = queue print(number)
4192dbf5992a15acb57c7cccd3049b08b5b77461
[ "Markdown", "Python" ]
3
Python
matthewmorales401/Uber-Career-Prep-Homework-Matthew-Morales
3f28d8c39f6082138c9cb26af4856c5ed5366262
72c4c71651f3d1177c48ad298830dbdd258ebee8
refs/heads/master
<repo_name>SefaErgin/FinalProject<file_sep>/Core/Utilities/Results/IResult.cs using System; using System.Collections.Generic; using System.Text; namespace Core.Utilities.Results { //Temel voidler için başlangıç //Success Sonuç demek //Bool true false şeklinde kullanılarn bir veri tipi public interface IResult { bool Success { get; } string Message { get; } } }
11656b66e622072de1dffca18c44655cd691a0b6
[ "C#" ]
1
C#
SefaErgin/FinalProject
04a1b4d5d7f7ce88a44e8f6e239f7484837b41a0
5132f931f1c865f9759efbe4d68df5810cf4e2ab
refs/heads/main
<repo_name>EduardoMaxwell/MyFood<file_sep>/settings.gradle rootProject.name = "MyFood" include ':app' <file_sep>/app/src/main/java/com/eduardomaxwell/myfood/ui/RestaurantFragment.kt package com.eduardomaxwell.myfood.ui import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import co.tiagoaguiar.atway.ui.adapter.ATAdapter import com.eduardomaxwell.myfood.R import com.eduardomaxwell.myfood.databinding.FragmentRestarauntBinding import com.eduardomaxwell.myfood.model.Category import com.eduardomaxwell.myfood.model.FilterItem import com.eduardomaxwell.myfood.model.toChip class RestaurantFragment : Fragment(R.layout.fragment_restaraunt) { private var binding: FragmentRestarauntBinding? = null private val categoryAdapter = ATAdapter({ CategoryView(it) }) var filters = arrayOf( FilterItem(1, "Ordernar", closeIcon = R.drawable.ic_baseline_keyboard_arrow_down_24), FilterItem(2, "Para Retirar", icon = R.drawable.ic_baseline_directions_walk_24), FilterItem(3, "Entrega grátis"), FilterItem(4, "Vale-refeição", closeIcon = R.drawable.ic_baseline_keyboard_arrow_down_24), FilterItem(5, "Distância", closeIcon = R.drawable.ic_baseline_keyboard_arrow_down_24), FilterItem(6, "Entrega parceira"), FilterItem(7, "Super restaurante"), FilterItem(8, "Filtros", closeIcon = R.drawable.ic_baseline_filter_list_24) ) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) categoryAdapter.items = arrayListOf( Category( 1, "https://www.ifood.com.br/static/images/categories/market.png", "Mercador", 0xFFB6D048 ), Category( 2, "https://www.ifood.com.br/static/images/categories/restaurant.png", "Restaurante", 0xFFE91D20 ), Category( 3, "https://www.ifood.com.br/static/images/categories/drinks.png", "Bebidas", 0xFFF6D553 ), Category( 4, "https://www.ifood.com.br/static/images/categories/express.png", "Express", 0xFFFF0000 ), Category( 5, "https://parceiros.ifood.com.br/static/media/salad.9db040c0.png", "Saudável", 0xFFBC60C5 ), Category( 6, "https://www.ifood.com.br/static/images/categories/petshop.png", "Petshop", 0xFFE91020 ), ) binding = FragmentRestarauntBinding.bind(view) binding?.let { it.rvCategory.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) it.rvCategory.adapter = categoryAdapter filters.forEach { filter -> it.chipGroupFilter.addView(filter.toChip(requireContext())) } } } }<file_sep>/app/src/main/java/com/eduardomaxwell/myfood/MainActivity.kt package com.eduardomaxwell.myfood import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.eduardomaxwell.myfood.databinding.ActivityMainBinding import com.eduardomaxwell.myfood.ui.RestaurantFragment import com.google.android.material.tabs.TabLayoutMediator class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupViews() } private fun setupViews() { val tabLayout = binding.addTab val viewPager = binding.addViewpager val adapter = TabViewPagerAdapter(this) viewPager.adapter = adapter TabLayoutMediator(tabLayout, viewPager) { tab, position -> tab.text = getString(adapter.tabs[position]) }.attach() } } class TabViewPagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) { val tabs = arrayOf(R.string.restaurants, R.string.marketplaces, R.string.drinks) private val fragments = arrayOf(RestaurantFragment(), MarketplaceFragment(), MarketplaceFragment()) override fun getItemCount() = fragments.size override fun createFragment(position: Int): Fragment { return fragments[position] } } class MarketplaceFragment : Fragment() {}<file_sep>/app/src/main/java/com/eduardomaxwell/myfood/ui/CategoryView.kt package com.eduardomaxwell.myfood.ui import android.graphics.drawable.GradientDrawable import android.view.ViewGroup import co.tiagoaguiar.atway.ui.adapter.ATViewHolder import com.eduardomaxwell.myfood.databinding.CategoryItemBinding import com.eduardomaxwell.myfood.model.Category import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import java.lang.Exception class CategoryView(viewGroup: ViewGroup) : ATViewHolder<Category, CategoryItemBinding>( CategoryItemBinding::inflate, viewGroup ) { override fun bind(item: Category) { binding.txtCategory.text = item.name Picasso.get() .load(item.logoUrl) .into(binding.imgCategory, object : Callback { override fun onSuccess() { val shape = GradientDrawable() shape.cornerRadius = 10f shape.setColor(item.color.toInt()) binding.bgCategory.background = shape } override fun onError(e: Exception?) { } }) } }<file_sep>/app/src/main/java/com/eduardomaxwell/myfood/model/FilterItem.kt package com.eduardomaxwell.myfood.model import android.content.Context import android.content.ContextWrapper import android.view.ContextThemeWrapper import android.view.LayoutInflater import androidx.annotation.DrawableRes import com.eduardomaxwell.myfood.R import com.google.android.material.chip.Chip data class FilterItem( val id: Int, val text: String, @DrawableRes val icon: Int? = null, val iconSize: Float = 32.0f, @DrawableRes val closeIcon: Int? = null, ) fun FilterItem.toChip(context: Context): Chip { val chip = if (closeIcon == null) { LayoutInflater.from(context).inflate(R.layout.chip_choice, null, false) as Chip } else { Chip(ContextThemeWrapper(context, R.style.Widget_MaterialComponents_Chip_Choice)) } if (closeIcon != null) chip.setChipBackgroundColorResource(R.color.white) chip.setChipStrokeColorResource(R.color.lt_grey) chip.chipStrokeWidth = 2f if (icon != null) { chip.chipIconSize = iconSize chip.setChipIconResource(icon) chip.chipStartPadding = 20f } else { chip.chipIcon = null } closeIcon?.let { chip.setCloseIconResource(it) chip.isCloseIconVisible = true } chip.text = text return chip }
58a3537088fdfe0ad3787661491a3421f6689c26
[ "Kotlin", "Gradle" ]
5
Gradle
EduardoMaxwell/MyFood
d27c7b4a2eab444e5681f789d1364e1de9d7163a
f314205c44e2b0c4500e2ed37cbcf510034a4833
refs/heads/master
<repo_name>phodal/phodit-nlp<file_sep>/build-keywords.js var jieba = require('nodejieba'); var data = require('./output'); var contents = ''; for (let item of data) { contents = contents + item.content; } let top500 = 500; let extract = jieba.extract(contents, top500); console.log(JSON.stringify(extract)); <file_sep>/index.js let data = require('./output.json'); let lunr = require('lunr'); let dataWithIndex = []; console.log(new Date()); let idx = lunr(function () { this.field('title', { boost: 10 }); this.field('content'); for (let item of data) { this.add(item); dataWithIndex[item.id] = item; } }); console.log(new Date()); let searchText = "微前端"; let searchResults = idx.search(searchText); console.log(searchResults); for (let result of searchResults) { // console.log(dataWithIndex[result.ref].title); let replaceContent = dataWithIndex[result.ref].content.replace(/\n/g, ''); let content = replaceContent.split(/[,。;!]+/); for (let sentence of content) { if (sentence.includes(searchText)) { console.log(sentence, searchText); } } } <file_sep>/README.md # phodit-nlp
130061ed3da6b55e80de36781161c9105dc8fc04
[ "JavaScript", "Markdown" ]
3
JavaScript
phodal/phodit-nlp
aec95b64c60f1b5abe0e5a4a72ab05fa88667712
b5a041bbff0deda8f55f36d446187b53fe424fa6
refs/heads/main
<repo_name>DevadutSB/Jupyter-Notebook-in-termux<file_sep>/setup.sh #! /bin/bash clr(){ echo -e "\e["$1"m" $2 } clr 31 echo -e "Setting up some shortcut commands" clr 37 cp .bash_aliases -r ~ cp .bashrc -r ~ source ~/.bashrc clr 37 clr 31 "updating and upgrading to eliminate any possible errors regarding versons" echo -e "\e[0m" yes | pkg update yes | pkg upgrade yes | pkg install figlet clr 32 "Bash Code By DSB" figlet RYU CODER clr 32 "This script will install all dependences for notebook" echo -e "\e[0m" yes | pkg update yes | pkg upgrade yes | pkg install clang python fftw libzmq freetype libpng pkg-config libcrypt -y clr 31 "Setting up Environment" echo -e "\e[0m" LDFLAGS="-lm -lcompiler_rt" clr 31 "Installing Jupyter" echo -e "\e[0m" pip install --upgrade pip pip install jupyter clr 36 "I have linked some shortcuts to make your coding life easy" clr 33 "they are" alias clr 33 "To access the notebook, open link in a browser:" echo -e "\e[0m" clr 31 "Clearing all of these in 10 seconds to get a fresh start" for ((i = 1 ; i < 11 ; i++)); do echo $i "Seconds left" sleep 1 done clear clr 32 "Testing notebook" clr 36 jupyter notebook <file_sep>/.bash_aliases #This file can be edited to change cammands clr(){ echo -e "\e["$1"m" $2 } clr-help(){ clr 31 31:Red clr 32 32:Green clr 33 33:Yellow clr 34 34:Blue clr 35 35:Pink clr 36 36:Cyan clr 37 37:Gray } #alias sets a new cammand #Enter alias for listing all alias alias cmd="nano ~/.bash_aliases" alias plf="pip list | grep $1" alias up="pkg update && pkg upgrade" alias c="clear" alias rm="rm -i" alias rf="rm -rf" alias lsf="ls | grep $1" alias pkf="pkg list-all | grep $1" alias pkl="pkg list-all" alias pki="pkg install $1" alias ppi="pip install $1" alias ati="apt install $1" alias ati="apt install $1" alias jn="jupyter notebook" c clr 32
e46e772e2d9d6bae3cc72421e3d1bd685c6df5f9
[ "Shell" ]
2
Shell
DevadutSB/Jupyter-Notebook-in-termux
e8754df09f15e1e6439d5cab20ca0a23aa2dc916
21731b03bd01d75061ac4157627a440aacccf1c6
refs/heads/master
<repo_name>futurist/EmailScanner<file_sep>/wsnode.js #!/usr/bin/env node var fs = require('fs'); var http = require('http'); var express = require('express'); var app = express(); var server = http.Server(app); var node_path = require('path'); var node_url = require('url'); var _=require("underscore"); var WebSocketServer = require('websocket').server; /******* set up http *******/ app.get('/user/:id', function(req, res){ //console.log(req.app); res.send('user ' + req.params.id); }); app.use(express.static(node_path.join(__dirname, './'))); // "public" off of current is root server.listen(8080); /******* set up mongodb *******/ var db; var col; var MongoClient = require('mongodb').MongoClient; var ObjectID = require('mongodb').ObjectID; var assert = require('assert'); // Connection URL var url = 'mongodb://127.0.0.1:15017/testEmail'; // Use connect method to connect to the Server MongoClient.connect(url, function(err, db_instance) { assert.equal(null, err); console.log("Connected correctly to mongodb server"); db = db_instance; }); /******* set up websockets *******/ var clients=[]; wsServer = new WebSocketServer({ httpServer: server, maxReceivedFrameSize : 1024*1024*1, autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } function closeClient(ws){ if(ws.connected) ws.close(); var pos = _.indexOf(clients, ws); if(pos>-1) clients.splice(pos,1 ); } wsServer.on("connect", function(wsCon){ console.log("connected", new Date() ); }); wsServer.on("close", function(wsCon, closeReason, description){ console.log("closed:", new Date, closeReason, description); }); wsServer.on('request', requestFunc); function requestFunc(request) { //console.log(request.resourceURL); var link = request.resourceURL.href; var path = request.resourceURL.pathname; var domain = request.requestedProtocols.join(","); var param = ( node_url.parse(link, true).query ); var ws; console.log( "new request link: ", link ); /* check for if origin is allowed */ if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } /* check for param is right */ if(!param.q || !param.uid ){ console.log(' url is wrong. now exit.', param); return; } var keyword = encodeURIComponent(param.q); col = db.collection( 'q.'+keyword ); console.log('q.'+keyword); /* check for keyword is already exist */ if( _.where(clients, {q: param.q} ).length >=1 ){ console.log(clients.length, "already has same keyword ws:", param.q ," now exit. uid:", param.uid ); return; } /* accept and get connection object: ws */ ws = request.accept(domain, request.origin); //Websocket Connection Object /* init ws connect */ ws.uid = param.uid; ws.q = param.q; ws.link = param.link; clients.push( ws ); ws.sendObj=function(data){ this.sendUTF( typeof data=="string" ? data : JSON.stringify( data ), function ack(error) { if(error) console.log("SEND ERRRRRR!!!!! ", error); } ); } ws.on('close', function(reasonCode, description) { closeClient(ws); console.log((new Date()) + ' Peer ' + ws.remoteAddress + ' disconnected. uid:', ws.uid, " ERRRR!!!!!!! reason:", reasonCode, description); if(reasonCode==1006){ console.log("waiting for reconnect"); return; } }); console.log(new Date(), 'connection successful! total client:', clients.length, path, domain, ws.uid ); ws.on('message', function(message) { //console.log(request, path, domain, param); var thisws = this; var data; if (message.type === 'utf8') { data = message.utf8Data; } if(!data || !db) return; var ret = ''; var msg = data[0]=='{' ? JSON.parse(data) : {} ; switch(msg.action){ case "init": col.update({ keyword: keyword }, { keyword: keyword , date: new Date(), slink:msg.slink } , {upsert:true, w: 1}, function(err, result) { }); break; case "discover": if( msg.q != keyword ) { console.log("keyword not match: ", msg.q ); return; } var timeout = new Date(); timeout.setHours( timeout.getHours() - 24*7 ); //time out 1 day col.find({ link: msg.link, $or:[{"snapshot.status":"new"}, { "snapshot.date": {$gt: timeout} }] }, {limit:5}).count(function(err, count){ console.log("found available: ", count); if(!count){ col.update( { link: msg.link }, { $set:{link: msg.link}, $addToSet: {snapshot: {status:'new', search_idx: msg.idx, title: msg.title, desc:msg.desc, date:new Date(), history_id:0, email:"", html:"", text:""} } }, {upsert:true, w:1}, function(err, r){ if(err)console.log(err); var cursor = col.aggregate( [ { $match:{ link:msg.link}}, {$group: {_id:null, count:{$sum: { $size:"$snapshot" } } } }], {cursor: {batchSize:1} } ); cursor.toArray(function(err, docs){ if(docs.length<1)return; console.log( docs[0].count ); col.update( { link:msg.link,"snapshot.status":"new" }, { $set:{ "snapshot.$.history_id": docs[0].count } } ); }); } ); thisws.sendObj( _.extend(msg, {status:"insert"} )); }else{ thisws.sendObj( _.extend(msg, {status:"exists"} )); } }); break; case "get_new_slot": console.log(msg.link); col.find({ link: msg.link, "snapshot.status":"new" }, {limit:5}).toArray(function(err, docs){ var count = docs.length; console.log("New Slot Total matches: "+ count); var ids = _.map( docs, function(v,i){ return v._id.toString(); }); thisws.sendObj( _.extend(msg, {total: count, o_ids: ids } )); }); break; case "update_email": var o_id = new ObjectID(msg.o_id); col.update({'_id': o_id, "snapshot.status":"new"}, { $set:{"snapshot.$.status":"ok", "snapshot.$.date":new Date(), "snapshot.$.email":msg.email, "snapshot.$.html":msg.html , "snapshot.$.text":msg.text , "snapshot.$.image":msg.image }}, function(){ console.log( "updated email: email ", msg.email, " ,oid ", o_id ); thisws.sendObj( _.extend(msg, {msg: "updated email & html. ", o_id: o_id } )); } ); break; case "timeout": col.find({ link: msg.link, "snapshot.status":"new" }, {limit:5}).toArray(function(err, docs){ var count = docs.length; console.log("Timeout Total matches: "+ count); var ids = _.map( docs, function(v,i){ return v._id.toString(); }); if(count){ var o_id = new ObjectID(ids[0]); col.update({'_id': o_id, "snapshot.status":"new"}, { $set:{"snapshot.$.status":"timeout", "snapshot.$.date":new Date() }}, function(){ console.log( "link timeout: ", msg.link, " ,oid ", o_id ); thisws.sendObj( _.extend(msg, {msg: "link timeout. ", link: msg.link, o_id:o_id } )); } ); } }) ; break; case "refused": col.find({ link: msg.link, "snapshot.status":"new" }, {limit:5}).toArray(function(err, docs){ var count = docs.length; console.log("Refused Total matches: "+ count); var ids = _.map( docs, function(v,i){ return v._id.toString(); }); if(count){ var o_id = new ObjectID(ids[0]); col.update({'_id': o_id, "snapshot.status":"new"}, { $set:{"snapshot.$.status":"refused", "snapshot.$.date":new Date(), "snapshot.$.reason": msg.reason }}, function(){ console.log( "link refused: ", msg.link, " ,oid ", o_id ); thisws.sendObj( _.extend(msg, {msg: "link refused. ", link: msg.link, o_id:o_id } )); } ); } }) ; break; } //fs.appendFile("data.txt", data+'\n'); }); }; <file_sep>/onMessage.js if (!window.hasScreenCapturePage) { window.hasScreenCapturePage = true; function onMessage(request, sender, callback) { //for message of googleEmail.js if (request.msg === 'timeout') { wsend( {action:"timeout", q:encodeURIComponent(param.q), link:request.link } ); if(callback)callback(); } //for Message of page.js if (request.msg === 'scrollPage') { getPositions(callback); } return true; } chrome.runtime.onMessage.addListener(onMessage); } <file_sep>/googleEmail.js // ==UserScript== // @name [Google]Email // @namespace http://your.homepage/ // @version 0.1 // @description enter something useful // @author You // @require http://1111hui.com/js/jquery.js // @require http://1111hui.com/js/underscore.js // @match https://www.google.com* // @match https://*/* // @match http://*/* // ==/UserScript== var lastEl = function(ar) { return ar[ar.length-1]; } function paramToJson(str) { return str.split('&').reduce(function (params, param) { var paramSplit = param.split('=').map(function (value) { return decodeURIComponent(value.replace(/\+/g, ' ')); }); params[paramSplit[0]] = paramSplit[1]; return params; }, {}); } function eve(el, type){ el= ('jquery' in el)? el.get(0) : el ; //(typeof el['jquery']!='undefined') if(typeof type=='undefined') type='click'; var click = document.createEvent("MouseEvents"); click.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); button = el; button.dispatchEvent(click); button.focus(); } function simulateKeyPress(character) { jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) }); } function $$(sel){ return document.querySelector(sel); } function wait(condition, passfunc, failfunc){ var _inter = setInterval(function(){ if( eval(condition) ){ clearInterval(_inter); passfunc.call(); }else{ if(failfunc) failfunc.call(); } },300); return _inter; } var tryCount = 10; var emailRE = /\b(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))\b/igm; var failedCount = 0; var inter1; var totalLinkCount = 0; var domLoaded = false; var param, keyword, startCount; var winList=[]; var winQueryInterval, winQueryCount=0; $(document).ready(function(){ domLoaded = true; }); function main(){ var url = getSearchUrl(); param = paramToJson( url ); if(!param.q ) return; keyword = encodeURIComponent(param.q); startCount = parseInt(param.start); if( isNaN(startCount) ) startCount = 0; failedCount = 0; var v= document.querySelectorAll('li.g h3.r a'); for(i=0; i<v.length; i++){ var idx = (startCount+i); v[i].removeAttribute('onmousedown'); v[i].removeAttribute('target'); v[i].className+=' passed '; //var workerLink = ''+ v[i].href +'#Qoftheworker=q='+ param.q +'&pid='+uid+''; var workerLink = ''+ v[i].href; v[i].setAttribute('data-workerlink',workerLink); //v[i].setAttribute('onclick', 'window.open("'+ workerLink +'", "google|'+ idx +'|'+ v[i].href +'"); return false; ' ); v[i].setAttribute('onclick', 'window.open("'+ v[i].href +'", "google|'+ idx +'|'+ v[i].href +'"); return false; ' ); console.log("ready send: ", idx, v[i].href); } console.log(domLoaded); $('#__opengoogle').remove(); $('#hdtb_msb, #hdtb-msb').append('<div style="position:absolute; top:0; right:-50px;"><input type="button" value="打开" id="__opengoogle"></div>'); $('#__opengoogle').unbind().click(function(){ if(param.gnext!=1) { window.open("https://www.google.com/#newwindow=1&q="+ keyword +"&start="+ startCount + "&gnext=1&filter=0" ); chrome.runtime.sendMessage({msg:"closeMe" }); return; } else { startCrawl(); } }); if(param.gnext==1){ setTimeout( function(){ $('#__opengoogle').click(); }, 1000); } } function wsend(obj, callback){ chrome.runtime.sendMessage( _.extend(obj, {msg:"wsend"} ) , callback); } function startCrawl(){ totalLinkCount=0; window.stop(); var v= document.querySelectorAll('li.g h3.r a'); for(i=0; i<v.length; i++){ var idx = (startCount+i); var link = $( v[i] ); var desc = $( v[i] ).parent().next().find('span.st'); if(!link.size() ) continue; wsend( {action:"discover", q:encodeURIComponent(param.q), idx:idx, link:link.attr('href'), title:link.html(), desc:desc.html() }, function(ret){ console.log("ret: ", ret) totalLinkCount++; if(totalLinkCount==v.length){ openAllLink(); } } ); } } function openAllLink(){ var v= document.querySelectorAll('li.g h3.r a'); winList=[]; for(i=0; i<v.length; i++){ //console.log(i,v[i], v[i].href ); var link = v[i].getAttribute("data-workerlink"); var idx = startCount+i; //var win = window.open(link,"google"+(idx) ); winList.push({link:link, idx: idx, q:param.q }); } //Next Link Info //eve( $('a.pn') ); //The AJAX of google will make big memery. so we open a new window and close it. var nextL = document.querySelector('#pnnext').href.split("?").pop(); var nextP = paramToJson(nextL).start || (startCount+10); var nextLink = "https://www.google.com/#newwindow=1&q="+ keyword +"&start="+ nextP + "&gnext=1&filter=0" ; //open list of urls, and return JSON of winList with tabIds wsend( {action:"init", slink:window.location.href } ); chrome.runtime.sendMessage({msg:"openMe", winList:winList, nextLink:nextLink }, function(){ }); } function checkWindowStatus(winList){ winQueryCount=0; clearInterval(winQueryInterval); winQueryInterval = setInterval( function(){ var allOK = true; winQueryCount++; console.log(winQueryCount, winList); var closedA =_.map(winList, function(v,i){ return v.win.closed; }); console.log(winQueryCount, closedA); _.each(winList, function(v,i){ if ( ! (v.win && v.win.closed) ) { allOK=false; if(winQueryCount>tryCount) { wsend( {action:"timeout", q:encodeURIComponent(param.q), link:v.link } ); //if(v.win) v.win.close(); chrome.runtime.sendMessage({msg:"closeMe", url:v.link }); } } }); if(winQueryCount>tryCount+1 || allOK ){ clearInterval( winQueryInterval ); console.log("all done!!!!", startCount ); _.each(winList, function(v,i){ chrome.runtime.sendMessage({msg:"closeMe", url:v.link }); }); //window.open("https://www.google.com/#newwindow=1&q="+ keyword +"&start="+ nextP + "&gnext=1&filter=0" ); chrome.runtime.sendMessage({msg:"closeMe" }); } }, 1000 ); } var workerObj={}; var isWorker, workerInterval; function monitorGoogleURLChange() { clearInterval(inter1); var url = getSearchUrl(); var param = paramToJson( url ); if(param.q ){ $(window).off('hashchange'); chrome.runtime.sendMessage( {msg:"initWebsocket", param: url, domain: "www.google.com"} ); } failedCount=0; inter1 = wait(' document.querySelectorAll("li.g h3.r") && document.querySelectorAll("li.g h3.r").length>1 && document.querySelectorAll("li.g h3.r a.passed").length==0 ', main, function(){ return; failedCount++; if(failedCount>100 && !domLoaded ){ // && $(".med.card-section").size()==0 clearInterval(inter1); window.location.reload(); } }); } function getSearchUrl(){ return /q=/i.test(window.location.search) ? window.location.search.substr(1) : window.location.hash.substr(1); } function getTextHtml(){ $('*[style]').removeAttr('style'); $('img').each(function(i,e){ $(this).replaceWith(function() { return this.alt || this.title || "image"+i ; }); }); $('object,embed').each(function(i,e){ $(this).replaceWith(function() { return this.alt || this.title || "object"+i ; }); }); $('style,script,noscript,link,img,object,embed').remove(); return $('html')[0].outerHTML; } function getEmail(data) { console.log("ret: ", data); function update_email(name){ if( !(data.o_ids && data.o_ids.length) ) return; o_id = data.o_ids[0]; var html = getTextHtml(); var email = html.match(emailRE); email = email ? email.map(function(v,i){ return v; }).join(";") : ""; wsend({ action:"update_email", o_id:o_id, email: email , html:html, text:$('body').text(), image:name }, function(data){ console.log(data); chrome.runtime.sendMessage({msg:"closeMe", url: window.location.href.split("#")[0] }); }); } if(data.total>0){ chrome.runtime.sendMessage({msg:"monkeyCapture" }, function(name) { //alert("monkey captured"); update_email(name); }); }else{ chrome.runtime.sendMessage({msg:"closeMe", url: window.location.href.split("#")[0] }); } } function init(){ if( window.location.href.match(/google.com/) ){ $(window).on('hashchange', monitorGoogleURLChange ); monitorGoogleURLChange(); return; } //document.referrer.match(/google\.|googleusercontent\./) && //if( window.location.href.match(/Qoftheworker/) ){ if( window.Qoftheworker ) { isWorker = true; var workerA = window.Qoftheworker.split("#Qoftheworker="); workerObj.link = workerA[0]; workerObj.param = lastEl(workerA); workerObj.paramJson = paramToJson(lastEl(workerA) ); //initWebsocket("", "theworker"); console.log("start worker"); //check if we can screen capture and save work. workerInterval=setInterval(function(){ chrome.runtime.sendMessage({ msg:"getScreenQueue"}, function( canDo ){ console.log("canDo",canDo); if(canDo){ clearInterval(workerInterval); wsend({ action:"get_new_slot", link:workerObj.link }, getEmail); } }); }, 300); return; } } init();
ea277dfb163b65031774b5e78f27ae048a1c0cbb
[ "JavaScript" ]
3
JavaScript
futurist/EmailScanner
752609081a925c8c49a1bd0eca4b9a36784b1974
b79411ca8ae254bacf7ae092c7637b835198944c
refs/heads/master
<file_sep> var x,x1,x2,x3,x4,x5; var count,y; document.getElementById("reset").addEventListener("click", function(){ var c=Math.floor(Math.random()*6+1); document.getElementById("blah").innerHTML="Play!" document.getElementById("work").src= randomflag(); x=count; if(c==1){ y=count; x=y; } document.getElementById("work").addEventListener("click", function(){ if(y==x) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); document.getElementById("work1").src= randomflag() while(1){ if(count==x){ document.getElementById("work1").src= randomflag(); x1=count; } else break; } if(c==2){ y=count; x1=y; } document.getElementById("work1").addEventListener("click", function(){ if(y==x1) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); document.getElementById("work2").src=randomflag() while(1){ if(count==x||count==x1){ document.getElementById("work2").src= randomflag(); x2=count; } else break; } if(c==3){ y=count; x2=y; } document.getElementById("work2").addEventListener("click", function(){ if(y==x2) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); document.getElementById("work3").src= randomflag() while(1){ if(count==x||count==x1||count==x2){ document.getElementById("work3").src= randomflag(); x3=count; } else break; } if(c==4){ y=count; x3=y; } document.getElementById("work3").addEventListener("click", function(){ if(y==x3) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); document.getElementById("work4").src= randomflag() while(1){ if(count==x||count==x1||count==x2||count==x3){ document.getElementById("work4").src= randomflag(); x4=count; } else break; } if(c==5){ y=count; x4=y; } document.getElementById("work4").addEventListener("click", function(){ if(y==x4) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); document.getElementById("work5").src=randomflag(); while(1){ if(count==x3||count==x2||count==x1||count==x||count==x4){ document.getElementById("work5").src= randomflag(); x5=count; } else break; } if(c==6){ y=count x5=y; } document.getElementById("work5").addEventListener("click", function(){ if(y==x5) document.getElementById("blah").innerHTML="<p class=\"text-success\">CORRECT!</p>" else document.getElementById("blah").innerHTML="<p class=\"text-danger\">INCORRECT!</p>" }); function randomflag() { count=Math.floor(Math.random()*189); return fnames[count]; } }); document.getElementById("reset").addEventListener("click", function(){ document.getElementById("bleh").innerHTML = cnames[y]; }); <file_sep># Fun-With-Flags A simple flag game to test your knowledge of flags <file_sep>var cnames=["AFGHANISTAN","ALGERIA","ANDORRA","ANGOLA","ALBANIA", "ANTIGUA & BARBUDA","ARGENTINA","ARMENIA","AUSTRALIA","AUSTRIA", "AZERBAIJAN", "BAHAMAS","BAHRAIN","BANGLADESH","BARBADOS","BELARUS","BELGIUM","BELIZE","BENIN","BHUTAN","BOLIVIA","BOSNIA & HERZEGOVINA","BOTSWANA", "BRAZIL","BRUNEI DARUSSALAM","BULGARIA","BURKINA FASO","BURUNDI", "CAMBODIA","CAMEROON","CANADA","CAPE VERDE","CENTRAL AFRICAN REPUBLIC","CHAD","CHILE","CHINA","COLOMBIA","COMOROS","CONGO","COSTA RICA","CROATIA", "CUBA","CYPRUS","CZECH REPUBLIC", "DENMARK","DJIBOUTI","DOMINICAN REPUBLIC","DOMINICA", "ECUADOR","EGYPT","EL SALVADOR","EQUATORIAL GUINEA","ERITREA","ESTONIA","ETHIOPIA", "FIJI","FINLAND","FRANCE", "GABON","GAMBIA","GEORGIA","GERMANY","GHANA","GREAT BRITAIN","GREECE","GRENADA","GUATEMALA","GUINEA","GUINEA-BISSAU","GUYANA", "HAITI","HONDURAS","HUNGARY", "ICELAND","INDIA","INDONESIA","IRAN","IRAQ","IRELAND","ISRAEL AND THE OCCUPIED TERRITORIES","ITALY", "JAMAICA","JAPAN","JORDAN", "KAZAKHSTAN","KENYA","KUWAIT","KYRGYZ REPUBLIC", "LAOS","LATVIA","LEBANON","LESOTHO","LIBERIA","LIBYA","LIECHTENSTEIN","LITHUANIA","LUXEMBOURG", "REPUBLIC OF MACEDONIA","MADAGASCAR","MALAWI","MALAYSIA","MALDIVES","MALI","MALTA","MAURITANIA","MAURITIUS","MEXICO","MOLDOVA","MONACO","MONGOLIA","MONTENEGRO", "MOROCCO","MOZAMBIQUE","MYANMAR", "NAMIBIA","NAURU","NEPAL","NETHERLANDS","NEW ZEALAND","NICARAGUA","NIGER","NIGERIA","NORTH KOREA", "NORWAY","OMAN","PAKISTAN","PALAU","PANAMA", "PAPUA NEW GUINEA","PARAGUAY","PERU","PHILIPPINES","POLAND","PORTUGAL","QATAR","ROMANIA", "RUSSIAN FEDERATION","RWANDA","SAINT KITTS AND NEVIS","SAINT LUCIA","SAINT VINCENT'S & GRENADINES", "SAMOA","SAN MARINO","SAO TOME AND PRINCIPE","SAUDI ARABIA","SENEGAL","SERBIA","SEYCHELLES","SIERRA LEONE","SINGAPORE","SLOVAK REPUBLIC", "SLOVENIA","SOLOMON ISLANDS","SOMALIA","SOUTH AFRICA","SOUTH KOREA","SPAIN","SRI LANKA","SUDAN","SURINAME", "SWAZILAND","SWEDEN","SWITZERLAND","SYRIA","TAJIKISTAN","TAIWAN","TANZANIA","THAILAND","TIMOR LESTE","TOGO","TONGA", "TRINIDAD & TOBAGO","TUNISIA", "TURKEY","TURKMENISTAN","TUVALU","UGANDA","UKRAINE","UNITED ARAB EMIRATES","UNITED STATES OF AMERICA ","URUGUAY" ,"UZBEKISTAN","VANUATU","VENEZUELA","VIETNAM","WESTERN SAHARA","YEMEN","ZAMBIA","ZIMBABWE"] var fnames=["af.png","dz.png","ad.png","ao.png","al.png", "ag.png","ar.png","am.png","au.png","at.png","az.png", "bs.png","bh.png","bd.png","bb.png","by.png","be.png","bz.png","bj.png","bt.png","bo.png","ba.png","bw.png","br.png", "bn.png","bg.png" ,"bf.png","bi.png", "kh.png" ,"cm.png" ,"ca.png" ,"cv.png","cf.png","td.png","cl.png" ,"cn.png" ,"co.png","km.png" ,"cg.png","cr.png","hr.png","cu.png","cy.png","cz.png", "dk.png","dj.png","do.png","dm.png", "ec.png","eg.png","sv.png","gq.png","er.png","ee.png","et.png", "fj.png","fi.png","fr.png", "ga.png","gm.png","ge.png","de.png","gh.png","gb.png","gr.png","gd.png","gt.png","gn.png","gw.png","gy.png", "ht.png","hn.png","hu.png", "is.png","in.png","id.png","ir.png","iq.png","ie.png","il.png","it.png", "jm.png","jp.png","jo.png", "kz.png","ke.png","kw.png","kg.png", "la.png","lv.png","lb.png","ls.png","lr.png","ly.png","li.png","lt.png","lu.png", "mk.png","mg.png","mw.png","my.png","mv.png","ml.png", "mt.png","mr.png","mu.png","mx.png","md.png","mc.png","mn.png","me.png","ma.png","mz.png","mm.png" , "na.png","nr.png","np.png","nl.png","nz.png","ni.png","ne.png","ng.png","kp.png","no.png", "om.png","pk.png","pw.png","pa.png","pg.png","py.png","pe.png","ph.png","pl.png","pt.png","qa.png", "ro.png","ru.png","rw.png","kn.png","lc.png","vc.png","ws.png","sm.png","st.png","sa.png","sn.png","rs.png","sc.png", "sl.png","sg.png","sk.png","si.png","sb.png","so.png","za.png","kr.png","es.png","lk.png","sd.png", "sr.png", "sz.png","se.png","ch.png","sy.png","tj.png","tw.png", "tz.png","th.png","tl.png","tg.png","to.png","tt.png","tn.png","tr.png","tm.png","tv.png","ug.png","ua.png","ae.png", "us.png","uy.png","uz.png","vu.png","ve.png","vn.png","eh.png","ye.png","zm.png","zw.png"]
d4d23a4e3d6ea62370b26fed64fa1dd18a0ad2d5
[ "JavaScript", "Markdown" ]
3
JavaScript
Hemraj97/Fun-With-Flags
df73825ba22cf435a3be979650116122a0724be9
c062c3695ed1198f885eaa4d643855560f5b950b
refs/heads/master
<repo_name>mark-haskins11792/Constructors-Destructors-and-Operator-Overloading<file_sep>/Haskins Lab 10/Cow.h #pragma once class Cow { public: Cow(); Cow(const char* n, double w); Cow(const Cow& c); ~Cow(); Cow& operator=(const Cow& c); void ShowCow() const; private: char* name; double weight; }; <file_sep>/Haskins Lab 10/Cow.cpp //implementation of the cow class. #include "stdafx.h" #include "Cow.h" #include <iostream> using namespace std; Cow::Cow() { cout << "Cow default constructor" << endl; } Cow::Cow(const char* n, double w) { cout << "Cow constructor" << endl; int length = strlen(n); name = new char[length + 1]; strcpy_s(name, length + 1, n); weight = w; } Cow::Cow(const Cow& c) { cout << "Cow explicit copy constructor (Deep Copy)" << endl; int length = strlen(c.name); name = new char[length + 1]; strcpy_s(name, length + 1, c.name); weight = c.weight; } Cow::~Cow() { cout << "Cow destructor" << endl; delete[] name; } Cow& Cow::operator=(const Cow& c) { cout << "Assignment operator overload function" << endl; int length = strlen(c.name); name = new char[length + 1]; strcpy_s(name, length + 1, c.name); weight = c.weight; return *this; } void Cow::ShowCow() const { cout << name << endl; cout << weight << endl; }<file_sep>/Haskins Lab 10/Haskins Lab 10.cpp // Program shows all member functions of the cow class. #include "stdafx.h" #include <iostream> #include "Cow.h" using namespace std; int main() { Cow a; Cow b("Mark", 190.0); Cow c(b); Cow d; d = c; cout << "\nShow Cow C:" << endl; c.ShowCow(); cout << "\nShow Cow D:" << endl; d.ShowCow(); cout << endl; return 0; } <file_sep>/README.md # Constructors-Destructors-and-Operator-Overloading Creating a cow class, instantiating it, assigning it, copying it, etc and overloading the = operator
b8e125869a587a7b8b434f6eb39e3156649ca998
[ "Markdown", "C++" ]
4
C++
mark-haskins11792/Constructors-Destructors-and-Operator-Overloading
79023a476861df3ea9fcb66cf6b3dd399786442f
592364f107e7ae62ca2a8ce8c91fe6e41a4f44eb
refs/heads/master
<repo_name>ahmadhussein01/github-exercise<file_sep>/updated-index.js // write the console.log code with hello in it underneath console.log("hello"); // write the console.log code with goodbye in it underneath console.log("goodbye");
6802560d6497bfbad3301180b478cf0718822a80
[ "JavaScript" ]
1
JavaScript
ahmadhussein01/github-exercise
782bd789050fe63f7d0ad5878391cd42093fbb18
befd2c13d030bd652e3c2596587827dd94e28544
refs/heads/master
<file_sep>( function () { 'use strict'; app.directive( 'backbutton', [ '$window', function ( $window ) { return { template: '<button class="btn back-button">Back</button>', link: function ( scope, elem, attrs ) { elem.bind('click', function () { $window.history.back(); } ); } }; } ] ); // function addTask () { // return { // 'restrict' : 'C', // 'link' : function ($scope, element, attribute) { // } // } // } } () ); <file_sep>( function() { var CustomerProfileController = function ( $scope, $routeParams, customersFactory, $location ) { var self = this; var customerId = $routeParams.customerId; self.init = function() { customersFactory.getCustomer( customerId ) .success( function ( customer ) { $scope.customer = customer; } ) .error( function ( data, status, headers, config ) { //handle errors } ); } self.editCustomer = function ( editedCustomer ) { $scope.submitted = true; if ( $scope.editfrm.$valid ) { customersFactory.editCustomer( editedCustomer ) .success( function () { $location.path( '/' ); } ) } } self.hasError = function( field ) { return ( $scope.editfrm[ field ].$dirty && $scope.editfrm[ field ].$invalid ) || ( $scope.submitted && $scope.editfrm[ field ].$invalid ); }; }; CustomerProfileController.$inject = [ '$scope', '$routeParams', 'customersFactory', '$location' ]; angular.module( 'customersApp' ) .controller( 'CustomerProfileController', CustomerProfileController ); } () ); <file_sep> 'use strict'; var app = angular.module( 'customersApp', [ 'ngRoute', 'ngAnimate', 'ui.bootstrap', 'angularMoment', 'mgcrea.ngStrap.datepicker' ] ); app.config( function ( $routeProvider, $locationProvider, $datepickerProvider ) { angular.extend( $datepickerProvider.defaults, { dateFormat : 'dd/MM/yyyy', autoclose : true } ); //Routes go here $routeProvider .when( '/', { controller : 'CustomersController', controllerAs : 'vm', templateUrl : 'app/customers/views/customers.html' } ) .when( '/orders/:customerId', { controller : 'OrdersController', templateUrl : 'app/customers/views/orders.html' } ) .when( '/custprofile/:customerId', { controller : 'CustomerProfileController', controllerAs : 'vm', templateUrl : 'app/customers/views/customer.html' } ) .when( '/orders', { controller : 'AllOrdersController', controllerAs : 'vm', templateUrl : 'app/customers/views/allorders.html' } ) .otherwise( { redirectTo: '/' } ); } ); <file_sep>Angular Customer Management =========== Stack: AngularJS, Mongodb, Node To use: npm install && bower install <file_sep>( function () { 'use strict'; var CustomersController = function ( $scope, customersFactory, $log, $modal ) { var self = this; $scope.sortBy = 'fname'; $scope.reverse = false; $scope.addCustomerModal = function () { var modalInstance = $modal.open( { templateUrl : 'app/customers/views/addCustomers.html', controller : 'addCustomerController', windowClass : 'app-modal-window', scope : $scope } ); modalInstance.result.then( function ( data ) { $scope.customers.push( data ); ++$scope.custLength; } ); }; //add scope.watch for added customer $scope.init = function() { customersFactory.getCustomers() .success( function ( customers ) { $scope.customers = customers; $scope.custLength = customers.length; } ) .error( function ( data, status, headers, config ) { //handle errors console.log( data + status ); } ); } self.deleteCustomer = function ( customerId ) { customersFactory.deleteCustomer( customerId ) .success( function ( ) { for ( var i=0; i < $scope.customers.length; i++ ) { if ( $scope.customers[ i ]._id === customerId ) { $scope.customers.splice( i, 1 ); break; } } $scope.custLength = $scope.customers.length; console.log( 'Success deleting' ); } ) .error ( function ( data, status, headers, config ) { console.log( 'Error deleting' ); } ) }, $scope.doSort = function ( propName ) { $scope.sortBy = propName; $scope.reverse = !$scope.reverse; }; }; CustomersController.$inject = [ '$scope', 'customersFactory', '$log', '$modal' ]; angular.module( 'customersApp' ).controller( 'CustomersController', CustomersController ); } () ); <file_sep>var customerAPI = require( './controllers/customerAPI.js' ); var schema = require( './models/Customer' ); module.exports = function( app ) { app.get( '/getcustomers', customerAPI.displayCustomers ); app.post( '/addcustomer', customerAPI.addCustomer ); app.get( '/orders', customerAPI.getAllOrders ); app.get( '/customer/:id', customerAPI.getCustomer ); app.delete( '/customer/:id', customerAPI.deleteCustomer ); app.put( '/customer/:id', customerAPI.editCustomer ); app.put( '/addorder/:id', customerAPI.addCustomerOrder ); }; <file_sep>( function () { 'use strict'; requirejs.config( { baseUrl : ' js', paths : { 'jquery' : '../bower_components/jquery/dist/jquery', 'underscore' : '../bower_components/underscore/underscore', 'angular' : '../bower_components/angular/angular' }, shim : { underscore : { exports : "_" }, angular : { exports: 'angular' } } } ); } () ); <file_sep>( function() { var OrdersController = function ( $scope, $routeParams, customersFactory ) { var customerId = $routeParams.customerId; $scope.customer = null; $scope.sortBy = 'product'; $scope.reverse = false; $scope.newOrder = {} $scope.init = function () { customersFactory.getCustomer( customerId ) .success( function ( customer ) { console.log( customer ) $scope.customer = customer; } ) .error( function( data, status, headers, config ) { //handle errors } ); } $scope.doSort = function ( propName ) { $scope.sortBy = propName; $scope.reverse = !$scope.reverse; }; $scope.addOrder = function ( order ) { $scope.submitted = true; if ( $scope.addOrderForm.$valid ) { var newOrder = JSON.stringify( order ); customersFactory.addOrder( $scope.customer,newOrder ) .success( function ( data ) { $scope.customer = data; // clear form $scope.newOrder = {}; $scope.addOrderForm.$setPristine(); $scope.submitted = false; } ) .error( function ( data ) { alert( data ) } ) } }; $scope.hasError = function( field, validation ) { if ( validation ) { return ( $scope.addOrderForm[ field ].$dirty && $scope.addOrderForm[ field ].$error[ validation ] ) || ( $scope.submitted && $scope.addOrderForm[ field ].$error[ validation ] ); } return ( $scope.addOrderForm[ field ].$dirty && $scope.addOrderForm[ field ].$invalid ) || ( $scope.submitted && $scope.addOrderForm[ field ].$invalid ); }; }; OrdersController.$inject = [ '$scope', '$routeParams', 'customersFactory' ]; angular.module( 'customersApp' ) .controller( 'OrdersController', OrdersController ); } () ); <file_sep>( function () { 'use strict'; var mongoose = require( 'mongoose' ); var customerSchema = mongoose.Schema( { joined : { type: String, required: true }, fname : { type: String, required: true }, lname : { type: String, required: true }, city : { type: String, required: true }, orderTotal : Number, orders : [ { product : String, cost : Number, quantity : Number, total : Number } ] } ); mongoose.model( 'customers', customerSchema ); module.exports = { customers : mongoose.model( 'customers' ) }; } () ); <file_sep>( function () { 'use strict'; var addCustomerController = function ( $scope, $modalInstance, customersFactory ) { var self = $scope; $scope.addCustomer = function ( user ) { $scope.submitted = true; console.log( $scope.addCustomerform ); if ( $scope.addCustomerform.$valid ) { var newCustomer = JSON.stringify( user ); customersFactory.addCustomer( newCustomer ) .success( function ( data ) { $modalInstance.close( data ); } ) .error( function ( data ) { alert( data ) } ) } }; $scope.hasError = function( field ) { return ( $scope.addCustomerform[ field ].$dirty && $scope.addCustomerform[ field ].$invalid ) || ( $scope.submitted && $scope.addCustomerform[ field ].$invalid ); }; $scope.cancel = function () { $modalInstance.dismiss( 'cancel' ); }; }; addCustomerController.$inject = [ '$scope', '$modalInstance', 'customersFactory' ]; angular.module( 'customersApp' ).controller( 'addCustomerController', addCustomerController ); } () );
47c3da54fd4a7b52843071d25f4be0d9604a2b10
[ "JavaScript", "Markdown" ]
10
JavaScript
xxryan1234/angularCustomerManagement
84544b2c457ac77b4f65384a4299f4ba0ec3f487
f218dac75704704372a2a5299a9f4b994b34c713
refs/heads/master
<file_sep>package com.lj.app.cardmanage.bulletin.service; import com.lj.app.cardmanage.base.service.BaseService; public interface BulletinService<Bulletin> extends BaseService { } <file_sep>package com.lj.app.cardmanage.postcard.service; import java.util.List; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.service.BaseServiceImpl; import com.lj.app.cardmanage.postcard.model.PostCard; @Service("postCardService") public class PostCardServiceImpl extends BaseServiceImpl implements PostCardService{ /** * 生成post机器卡片编号 * @return */ @Override public String generatePostCardNo(int userId,String userName){ String postCardNo = ""; String queryPostCardNo = ""; PostCard queryPostCard = new PostCard(); queryPostCard.setCreateBy(userId); queryPostCard.setUserName(userName); PostCard postCard = new PostCard(); List<PostCard> postCardList = this.queryForList("getUserPostCardList", queryPostCard); if(postCardList!=null && postCardList.size()>0) { postCard = postCardList.get(0); } queryPostCardNo = postCard.getPostCardNo(); if(queryPostCardNo==null || "".equals(queryPostCardNo)){ postCardNo = userName + "_" + "001"; return postCardNo; } String subStringUserNamePostCard = queryPostCardNo.substring(userName.length()+1); if(subStringUserNamePostCard.startsWith("0")&&!subStringUserNamePostCard.startsWith("00")){ String cardNoStr = subStringUserNamePostCard.substring(1); int cardNo = Integer.parseInt(cardNoStr) +1; if(cardNo>=100) { postCardNo = userName+"_"+cardNo; }else { postCardNo = userName+"_"+"0"+cardNo; } return postCardNo; } if(subStringUserNamePostCard.startsWith("00")){ String cardNoStr = subStringUserNamePostCard.substring(2); int cardNo = Integer.parseInt(cardNoStr) +1; if(cardNo>=10) { postCardNo = userName+"_"+"0"+cardNo; }else { postCardNo = userName+"_"+"00"+cardNo; } return postCardNo; } return postCardNo; } } <file_sep>package com.lj.app.cardmanage.base.service; import java.util.List; import java.util.Map; import org.springframework.dao.DataAccessException; import com.lj.app.cardmanage.base.model.BaseModel; import com.lj.app.core.common.pagination.Page; public interface BaseService<T> { public void insertObject(Object obj); public void insertObject(String sqlId, Object obj); public void updateObject(Object obj); public void updateObject(String sqlId, Object obj); public BaseModel findObject(String sqlId, Object obj); public BaseModel getInfoByKey(String sqlId, Object obj); public BaseModel getInfoByKey(Object obj); public Object queryObject(String sqlId, Object obj); public Object queryForObject(String sqlId, Object obj); public List<T> findBaseModeList(Object obj); public List<T> findBaseModeList(String sqlId, Object obj); public List<T> findBaseModePageList(Object obj); public List<T> findBaseModePageList(String sqlId, Object obj); public void delete(Object obj); public void delete(String sqlId, Object obj); public String getSqlMapNameSpace(); public List<T> queryForList(String statementName) throws DataAccessException; public List<T> queryForList(String statementName, Object parameterObject); public List<T> queryForList(String statementName, int skipResults, int maxResults) throws DataAccessException; public List<T> queryForList(String statementName, Object parameterObject,int skipResults, int maxResults) throws DataAccessException; public Page<T> findPageList(Page<T> page,Map<String,Object> condition, String sqlId); public Page<T> findPageList(Page<T> page,Map<String,Object> condition); public int countObject(String sqlId, Object obj); } <file_sep>package com.lj.app.cardmanage.base.service; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.dao.BaseDao; import com.lj.app.cardmanage.base.model.BaseModel; import com.lj.app.core.common.pagination.Page; import com.lj.app.core.common.util.ValidateUtil; @Service("baseService") public abstract class BaseServiceImpl<T> implements BaseService { private static final String NAMESPACE_SPLIT="."; private static final String PAGE_QUERY_SUBFIX = "_count"; private static final String DEFAULT_PAGENATION_NAME = "pagenate"; @Autowired private BaseDao baseDao; @Override public void insertObject(Object obj) { insertObject("insert",obj); } @Override public void insertObject(String sqlid, Object obj) { baseDao.insertObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlid,obj); } @Override public void updateObject(Object obj) { updateObject("update",obj); } @Override public void updateObject(String sqlId, Object obj) { baseDao.updateObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } @Override public BaseModel findObject(String sqlId, Object obj) { return baseDao.findObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } @Override public BaseModel getInfoByKey(String sqlId, Object obj) { return baseDao.getInfoByKey(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } @Override public BaseModel getInfoByKey(Object obj) { return baseDao.getInfoByKey(getSqlMapNameSpace()+NAMESPACE_SPLIT+"getInfoByKey",obj); } @Override public Object queryObject(String sqlId, Object obj){ return baseDao.findObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } @Override public Object queryForObject(String sqlId, Object obj){ return baseDao.queryForObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } @Override public List<BaseModel> findBaseModeList(Object obj) { return findBaseModeList("select",obj); } @Override public List<BaseModel> findBaseModeList(String sqlId, Object obj) { return baseDao.findBaseModeList(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId, obj); } @Override public List<BaseModel> findBaseModePageList(Object obj) { return findBaseModePageList("select", obj); } @Override public List<BaseModel> findBaseModePageList(String sqlId, Object obj) { return baseDao.findBaseModePageList(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId, obj); } @Override public void delete(Object obj) { delete("delete", obj); } @Override public void delete(String sqlId, Object obj) { baseDao.deleteObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId, obj); } @Override public String getSqlMapNameSpace() { String nameSpace= ""; try{ Class clazz = getClass(); String clazzName = clazz.getName(); int startPos = clazzName.lastIndexOf("."); if(startPos!=-1){ int endPost = clazzName.length()-"serviceImpl".length(); nameSpace = clazzName.substring(startPos+1,endPost); nameSpace = nameSpace.substring(0,1).toLowerCase()+nameSpace.substring(1); } }catch(Exception e) { e.printStackTrace(); } return nameSpace; } @Override public List queryForList(String statementName) throws DataAccessException { return queryForList(statementName,"select"); } @Override public List queryForList(String statementName, Object parameterObject) { return baseDao.queryForList(getSqlMapNameSpace()+NAMESPACE_SPLIT+statementName,parameterObject); } @Override public List queryForList(String statementName, int skipResults, int maxResults) throws DataAccessException { return baseDao.queryForList(statementName,skipResults,maxResults); } @Override public List queryForList(String statementName, Object parameterObject, int skipResults, int maxResults) throws DataAccessException { return baseDao.queryForList(statementName,parameterObject,skipResults,maxResults); } @Override public Page findPageList(Page page, Map condition, String sqlId) { String countQuery = getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId+PAGE_QUERY_SUBFIX; String findQuery = getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId; Number totalCount = (Number) baseDao.queryForObject(countQuery, condition); if(totalCount == null || totalCount.intValue() <= 0) { return page; } if(ValidateUtil.isEmpty(page.getSortColumns())) { } else { condition.put("sortColumns", page.getSortColumns()); } page.setTotalCount(totalCount.intValue()); List list = baseDao.queryForList(findQuery,condition,page.getFirstResult(), page.getPageSize()); page.setResult(list); return page; } @Override public Page findPageList(Page page, Map condition) { return findPageList(page,condition,DEFAULT_PAGENATION_NAME); } @Override public int countObject(String sqlId, Object obj) { return baseDao.countObject(getSqlMapNameSpace()+NAMESPACE_SPLIT+sqlId,obj); } public BaseDao getBaseDao() { return baseDao; } public void setBaseDao(BaseDao baseDao) { this.baseDao = baseDao; } } <file_sep>package com.lj.app.cardmanage.plan.model; import com.lj.app.cardmanage.base.model.BaseModel; public class Plan extends BaseModel{ private int id; /** * 批次编号 */ private String batchNo; private int userId; /** * 信用卡编号 */ private int creditCardId; /** * post机编号 */ private int postCardId; /** * 消费日期 */ private String saleDate; /** * 总金额 */ private int sumAllMoney; /** * 存款金额 */ private int inMoney; /** * 刷卡金额 */ private int outMoney; /** * 剩余金额 */ private int remainMoney; /** * 服务费率 */ private float serviceRate; /** * 手续费 */ private double poundage; /** * 收益金额 */ private float incomeMoney; /** * 计划是否执行 */ private String excuteFlag = "F"; /** * 服务费率统计 */ private String serviceRateSumFormat; /** * 手续费统计 */ private String poundageSumFormat; /** * 收益金额统计 */ private String incomeMoneySumFormat; /** * 还款统计 */ private String inMoneySumFormat; /** * 消费统计 */ private String outMoneySumFormat; /** * 自定义编号 */ private String cardNoProfile; private String bankNo; private String userName; private String postCardNo; private String manName; private float rate; private int billDate; private int repaymentDate; private int maxLimit; private String cardNo; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBatchNo() { return batchNo; } public void setBatchNo(String batchNo) { this.batchNo = batchNo; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getCreditCardId() { return creditCardId; } public void setCreditCardId(int creditCardId) { this.creditCardId = creditCardId; } public int getPostCardId() { return postCardId; } public void setPostCardId(int postCardId) { this.postCardId = postCardId; } public String getSaleDate() { return saleDate; } public void setSaleDate(String saleDate) { this.saleDate = saleDate; } public int getSumAllMoney() { return sumAllMoney; } public void setSumAllMoney(int sumAllMoney) { this.sumAllMoney = sumAllMoney; } public int getInMoney() { return inMoney; } public void setInMoney(int inMoney) { this.inMoney = inMoney; } public int getOutMoney() { return outMoney; } public void setOutMoney(int outMoney) { this.outMoney = outMoney; } public int getRemainMoney() { return remainMoney; } public void setRemainMoney(int remainMoney) { this.remainMoney = remainMoney; } public String getExcuteFlag() { return excuteFlag; } public void setExcuteFlag(String excuteFlag) { this.excuteFlag = excuteFlag; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPostCardNo() { return postCardNo; } public void setPostCardNo(String postCardNo) { this.postCardNo = postCardNo; } public String getManName() { return manName; } public void setManName(String manName) { this.manName = manName; } public float getRate() { return rate; } public void setRate(float rate) { this.rate = rate; } public int getBillDate() { return billDate; } public void setBillDate(int billDate) { this.billDate = billDate; } public int getRepaymentDate() { return repaymentDate; } public void setRepaymentDate(int repaymentDate) { this.repaymentDate = repaymentDate; } public int getMaxLimit() { return maxLimit; } public void setMaxLimit(int maxLimit) { this.maxLimit = maxLimit; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public double getPoundage() { return poundage; } public void setPoundage(double poundage) { this.poundage = poundage; } public float getServiceRate() { return serviceRate; } public void setServiceRate(float serviceRate) { this.serviceRate = serviceRate; } public float getIncomeMoney() { return incomeMoney; } public void setIncomeMoney(float incomeMoney) { this.incomeMoney = incomeMoney; } public String getServiceRateSumFormat() { return serviceRateSumFormat; } public void setServiceRateSumFormat(String serviceRateSumFormat) { this.serviceRateSumFormat = serviceRateSumFormat; } public String getPoundageSumFormat() { return poundageSumFormat; } public void setPoundageSumFormat(String poundageSumFormat) { this.poundageSumFormat = poundageSumFormat; } public String getIncomeMoneySumFormat() { return incomeMoneySumFormat; } public void setIncomeMoneySumFormat(String incomeMoneySumFormat) { this.incomeMoneySumFormat = incomeMoneySumFormat; } public String getCardNoProfile() { return cardNoProfile; } public void setCardNoProfile(String cardNoProfile) { this.cardNoProfile = cardNoProfile; } public String getInMoneySumFormat() { return inMoneySumFormat; } public void setInMoneySumFormat(String inMoneySumFormat) { this.inMoneySumFormat = inMoneySumFormat; } public String getOutMoneySumFormat() { return outMoneySumFormat; } public void setOutMoneySumFormat(String outMoneySumFormat) { this.outMoneySumFormat = outMoneySumFormat; } public String getBankNo() { return bankNo; } public void setBankNo(String bankNo) { this.bankNo = bankNo; } } <file_sep>package com.lj.app.cardmanage.plan.service; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ibatis.common.logging.Log; import com.ibatis.common.logging.LogFactory; import com.lj.app.cardmanage.base.service.BaseServiceImpl; import com.lj.app.cardmanage.creditcard.model.CreditCard; import com.lj.app.cardmanage.creditcard.service.CreditCardService; import com.lj.app.cardmanage.plan.model.Plan; import com.lj.app.core.common.util.DateUtil; @Service("planService") public class PlanServiceImpl extends BaseServiceImpl<Plan> implements PlanService<Plan>{ public Log log = LogFactory.getLog(PlanServiceImpl.class); private String batchNo;//批次编号 private String currentDate;//当前日期 private String currentDateOfDD;//当天日期 private int billDate;//账单日期 private String nextMonthToday;//下个月今天 private String preMonthToday;//上个月今天 private int getIntervalDaysOfBill;//下一个账单日-当前日期相差时间 private int credit_bill_date_count;//信用卡账单日是今天的数量 private int repaymentDate;//还款日 private List selectUserAndCardOfBillDayList; private int sumAllMoney;//信用卡总金额 private int cuurentSaleSumMoney;//当月消费总金额 private int billSaleRate;//费率 private int remainMoney;//剩余金额 private int outMoney;//单笔消费金额 private int inMoney;//单笔还款金额 private int currentMonthSumInMoney;//当月还款总金额 private int preMonthOutMoney;//上个月消费总金额 private int preMonthInMoney;//上个月还款金额 private int preMonthOutSubInMoney;//上个月帐号金额 private int preMonthOutSubInMoneySubcurrentMonthSumInMoney;//上月欠款,当月应还金额 private int realRemainMoney;//实际剩余金额 private int planRemainMoney;//计划剩余金额 private int checkSaleDay;//是否是消费日 private int getMaxSaleDay = 0;//最大消费日 private int postCardId;//post机器id private int userId; private String saleDate = ""; private int checkIsAlreadyRunPaln = 0;//是否已经生计划 private static final int SIGLE_SALE_MIN_MONEY = 100;//单笔消费最小金额 private float initRemainMoney;//初始剩余金额 @Autowired private CreditCardService creditCardService; @Override public void exceutePlanCron() { log.debug("Start to exceutePlanFromJava ........"); exceutePlanFromJava(); log.debug("End exceutePlanFromJava ........"); } @Override public String generateBatchNo() { return DateUtil.getNowDateYYYYMMddHHMMSS(); } @Override public String getCurrentDateOfDD() { return DateUtil.getNowDate("dd"); } /** * 获取账单日 * @param CurrentDateOfDD * @return */ @Override public int getBillDay(String CurrentDateOfDD){ int billDay = 0; if(CurrentDateOfDD!=null) { if(CurrentDateOfDD.length()>1&&CurrentDateOfDD.startsWith("0")){ billDay = Integer.parseInt(CurrentDateOfDD.substring(1,CurrentDateOfDD.length())); }else{ billDay = Integer.parseInt(CurrentDateOfDD); } } return billDay; } @Override public String getNextMonthToday() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); return DateUtil.formatDate(calendar.getTime(),DateUtil.DATE_FOMRAT_yyyyMMddhhMMss); } @Override public String getPreMonthToday() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); return DateUtil.formatDate(calendar.getTime(),DateUtil.DATE_FOMRAT_yyyyMMddhhMMss); } @Override public String getCurrentDate() { return DateUtil.getNowDateYYYYMMddHHMMSS(); } @Override public int getIntervalDaysOfBill(String nextMonthToday, String currentDate) { return DateUtil.getIntervalDays(nextMonthToday, currentDate); } /** * 查找账单日中要生成计划的帐号、卡信息 * @param billDay * @return */ @Override public List<Plan> selectUserAndCardOfBillDay(int billDay){ return queryForList("selectUserAndCardOfBillDay", billDay); } /** * 生成消费费率 * @return */ @Override public int generateBillSaleRate(){ //BigDecimal d = new BigDecimal(Math.round(Math.random()*5)+90); int rate = 100; return rate; } /** * 获得最大的消费日期 * @return */ @Override public int getMaxSaleDay(){ int result = 0; try{ Map obj = (HashMap)queryForObject("getMaxSaleDay", null); result = Integer.parseInt(String.valueOf(obj.get("F_GETMAXSALEDAY"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 生成计划消费的日期 * @param days * @return */ @Override public void generatePlanDayTmp(int days) { Map<String,Integer> queryMap = new HashMap<String,Integer>(); queryMap.put("days", days); queryForObject("generatePlanDayTmp", queryMap); } /** *是否是消费日 * @return */ @Override public int checkSaleDay(int day) { int result = 0; try{ Map<String,Integer> queryMap = new HashMap<String,Integer>(); queryMap.put("day", day); Map obj = (HashMap)queryForObject("checkSaleDay", queryMap); result = Integer.parseInt(String.valueOf(obj.get("F_CHECK_SALE_DAY"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 获取机具器编号 * @param outMoney * @param userId * @return */ @Override public int getPostCardId(int outMoney,int userId){ int result = 0; try{ Map<String,Integer> queryMap = new HashMap<String,Integer>(); queryMap.put("outMoney", outMoney); queryMap.put("userId", userId); Map obj = (HashMap) queryForObject("getPostCardId", queryMap); result = Integer.parseInt(String.valueOf(obj.get("F_GET_POST_CARDID"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 获取下一个日期 * @param outMoney * @param userId * @return */ @Override public String getSaleDay(String saleDay,int interOfDay){ Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtil.formatDate(saleDay,DateUtil.DATE_FOMRAT_yyyyMMddhhMMss)); calendar.add(Calendar.DAY_OF_MONTH, interOfDay); return DateUtil.formatDate(calendar.getTime(),DateUtil.DATE_FOMRAT_yyyyMMddhhMMss); } /** * 检验是否已经生成账单 * @param creditCardId * @param saleDate * @return */ @Override public int checkIsAlreadyRunPaln(int creditCardId, String saleDate){ int result = 0; try{ Map<String,Object> queryMap = new HashMap<String,Object>(); queryMap.put("creditCardId", creditCardId); queryMap.put("saleDate", saleDate); Map obj = (HashMap) queryForObject("checkIsAlreadyRunPaln", queryMap); result = Integer.parseInt(String.valueOf(obj.get("userCreditCardAndPlanCount"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 上个月消费总金额 * @param preMonthToday * @param saleDate * @param creditCardId * @return */ @Override public int getPreMonthOutMoney(String preMonthToday,String saleDate,int creditCardId) { int result = 0; try{ Map<String,Object> queryMap = new HashMap<String,Object>(); queryMap.put("preMonthToday", preMonthToday); queryMap.put("saleDate", saleDate); queryMap.put("creditCardId", creditCardId); Map obj = (HashMap) queryForObject("queryPreMonthOutMoney", queryMap); result = Integer.parseInt(String.valueOf(obj.get("preMonthOutMoney"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 上个月还款金额 * @param preMonthToday * @param saleDate * @param creditCardId * @return */ @Override public int getPreMonthInMoney(String preMonthToday,String saleDate,int creditCardId) { int result = 0; try{ Map<String,Object> queryMap = new HashMap<String,Object>(); queryMap.put("preMonthToday", preMonthToday); queryMap.put("saleDate", saleDate); queryMap.put("creditCardId", creditCardId); Map obj = (HashMap) queryForObject("queryPreMonthInMoney", queryMap); result = Integer.parseInt(String.valueOf(obj.get("preMonthInMoney"))); }catch(Exception e){ e.printStackTrace(); } return result; } /** * 上个月帐号金额 * @param preMonthToday * @param saleDate * @param creditCardId * @return */ @Override public int getPreMonthOutSubInMoney(String preMonthToday,String saleDate,int creditCardId) { int result = 0; try{ Map<String,Object> queryMap = new HashMap<String,Object>(); queryMap.put("preMonthToday", preMonthToday); queryMap.put("saleDate", saleDate); queryMap.put("creditCardId", creditCardId); Map obj = (HashMap) queryForObject("queryPreMonthOutSubInMoney", queryMap); result = Integer.parseInt(String.valueOf(obj.get("preMonthOutSubInMoney"))); }catch(Exception e){ e.printStackTrace(); } return result; } @Override public void exceutePlanFromJava() { batchNo = generateBatchNo(); currentDate = getCurrentDate(); currentDateOfDD = getCurrentDateOfDD(); nextMonthToday = getNextMonthToday(); preMonthToday = getPreMonthToday(); billDate = getBillDay(currentDateOfDD); getIntervalDaysOfBill = getIntervalDaysOfBill(nextMonthToday,currentDate)-1; credit_bill_date_count = creditCardService.getCreditBillDateCount(billDate); billSaleRate = generateBillSaleRate();//70-80 inMoney = 0; saleDate = getCurrentDate(); //生计划消费日 generatePlanDayTmp(getIntervalDaysOfBill); getMaxSaleDay=getMaxSaleDay(); if(credit_bill_date_count>0) { //账单日数量大于0,开始排计划 selectUserAndCardOfBillDayList = this.selectUserAndCardOfBillDay(billDate); for(int i = 0; i<selectUserAndCardOfBillDayList.size();i++){ Plan p = (Plan)selectUserAndCardOfBillDayList.get(i); preMonthOutMoney = getPreMonthOutMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月消费总金额 preMonthInMoney= getPreMonthInMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月还款金额 preMonthOutSubInMoney=getPreMonthOutSubInMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月帐号金额 repaymentDate = p.getRepaymentDate(); for(int j=0; j<getIntervalDaysOfBill;j++){ sumAllMoney = p.getMaxLimit(); checkSaleDay =checkSaleDay(j+1); if(j==0){ cuurentSaleSumMoney = sumAllMoney*billSaleRate/100; //remainMoney = sumAllMoney-preMonthOutSubInMoney; remainMoney = sumAllMoney; saleDate = getCurrentDate(); planRemainMoney = sumAllMoney-cuurentSaleSumMoney; currentMonthSumInMoney = 0; //preMonthOutSubInMoneySubcurrentMonthSumInMoney=preMonthOutSubInMoney-currentMonthSumInMoney; preMonthOutSubInMoneySubcurrentMonthSumInMoney=sumAllMoney; } userId = p.getUserId(); //还款操作 inMoney = PlanGenerateRuleFactory.getRandompInMoney(preMonthOutSubInMoney,currentMonthSumInMoney,inMoney,j,repaymentDate,preMonthOutSubInMoneySubcurrentMonthSumInMoney); currentMonthSumInMoney = currentMonthSumInMoney +inMoney; if(inMoney>0){//还款了,必须刷出, //outMoney = outMoney+inMoney-5; outMoney = inMoney-5; //remainMoney =Math.abs(remainMoney-inMoney+5); //remainMoney =Math.abs(remainMoney-outMoney+inMoney); } //outMoney = PlanGenerateRuleFactory.getRadomOutMoneyHasBill(remainMoney,j+1,getMaxSaleDay); if(outMoney<=SIGLE_SALE_MIN_MONEY){ outMoney = 0; } if(checkSaleDay != 1){ outMoney = 0; } if(inMoney>0){//还款了,必须刷出, outMoney = inMoney-5; } /*if(remainMoney<=planRemainMoney){ remainMoney =Math.abs(remainMoney+outMoney); outMoney=0; }*/ remainMoney =Math.abs(remainMoney-outMoney+inMoney); if(outMoney ==0){ postCardId = getPostCardId(SIGLE_SALE_MIN_MONEY,userId); }else { postCardId = getPostCardId(outMoney,userId); } saleDate = getSaleDay(saleDate,1); //realRemainMoney = remainMoney+planRemainMoney;//实际剩余金额 if(inMoney==0){ outMoney = realRemainMoney; if (outMoney<0){ outMoney=0; } remainMoney =0; } if(remainMoney>0) { realRemainMoney = remainMoney-sumAllMoney; }else { realRemainMoney=0; } /*if(j==0){ realRemainMoney = remainMoney; }*/ p.setBatchNo(batchNo); p.setUserId(userId); p.setPostCardId(postCardId); p.setSaleDate(saleDate); p.setSumAllMoney(sumAllMoney); p.setInMoney(inMoney); p.setOutMoney(outMoney); p.setRemainMoney(realRemainMoney); p.setExcuteFlag("F"); p.setCreateBy(userId); p.setPostCardId(postCardId); p.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); checkIsAlreadyRunPaln = this.checkIsAlreadyRunPaln(p.getCreditCardId(), saleDate); if(checkIsAlreadyRunPaln == 1){ }else{ insertObject(p); } } } } } @Override public void exceutePlanFromJava2() { batchNo = generateBatchNo(); currentDate = getCurrentDate(); currentDateOfDD = getCurrentDateOfDD(); nextMonthToday = getNextMonthToday(); preMonthToday = getPreMonthToday(); billDate = getBillDay(currentDateOfDD); getIntervalDaysOfBill = getIntervalDaysOfBill(nextMonthToday,currentDate)-1; credit_bill_date_count = creditCardService.getCreditBillDateCount(billDate); billSaleRate = generateBillSaleRate();//70-80 inMoney = 0; saleDate = getCurrentDate(); //生计划消费日 generatePlanDayTmp(getIntervalDaysOfBill); getMaxSaleDay=getMaxSaleDay(); if(credit_bill_date_count>0) { //账单日数量大于0,开始排计划 selectUserAndCardOfBillDayList = this.selectUserAndCardOfBillDay(billDate); for(int i = 0; i<selectUserAndCardOfBillDayList.size();i++){ Plan p = (Plan)selectUserAndCardOfBillDayList.get(i); preMonthOutMoney = getPreMonthOutMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月消费总金额 preMonthInMoney= getPreMonthInMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月还款金额 preMonthOutSubInMoney=getPreMonthOutSubInMoney(preMonthToday,getCurrentDate(),p.getCreditCardId());//上个月帐号金额 repaymentDate = p.getRepaymentDate(); if(preMonthOutSubInMoney<=0) {//上个月没呀欠费,消费金额=0||还款金额>消费金额. for(int j=0; j<getIntervalDaysOfBill;j++){ sumAllMoney = p.getMaxLimit(); checkSaleDay =checkSaleDay(j+1); userId = p.getUserId(); if(j==0){ cuurentSaleSumMoney = sumAllMoney*billSaleRate/100; remainMoney = cuurentSaleSumMoney; saleDate = getCurrentDate(); planRemainMoney = sumAllMoney-remainMoney; initRemainMoney = ((CreditCard)creditCardService.getInfoByKey(p.getCreditCardId())).getInitRemainMoney(); //outMoney=sumAllMoney-new BigDecimal(initRemainMoney).intValue(); outMoney=0; checkSaleDay=1; }else { outMoney = PlanGenerateRuleFactory.getRadomOutMoney(remainMoney,j+1,getMaxSaleDay); } if(outMoney<=SIGLE_SALE_MIN_MONEY){ outMoney = 0; } if(checkSaleDay != 1){ outMoney = 0; } remainMoney =remainMoney-outMoney; if(outMoney ==0){ postCardId = getPostCardId(SIGLE_SALE_MIN_MONEY,userId); }else { postCardId = getPostCardId(outMoney,userId); } saleDate = getSaleDay(saleDate,1); realRemainMoney = remainMoney+planRemainMoney;//实际剩余金额 p.setBatchNo(batchNo); p.setUserId(userId); p.setPostCardId(postCardId); p.setSaleDate(saleDate); p.setSumAllMoney(sumAllMoney); p.setInMoney(inMoney); p.setOutMoney(outMoney); p.setRemainMoney(realRemainMoney); p.setExcuteFlag("F"); p.setCreateBy(userId); p.setPostCardId(postCardId); p.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); checkIsAlreadyRunPaln = this.checkIsAlreadyRunPaln(p.getCreditCardId(), saleDate); if(checkIsAlreadyRunPaln == 1){ }else{ insertObject(p); } } }else {//上个月有消费,欠款. for(int j=0; j<getIntervalDaysOfBill;j++){ sumAllMoney = p.getMaxLimit(); checkSaleDay =checkSaleDay(j+1); if(j==0){ cuurentSaleSumMoney = sumAllMoney*billSaleRate/100; remainMoney = sumAllMoney-preMonthOutSubInMoney; saleDate = getCurrentDate(); planRemainMoney = sumAllMoney-cuurentSaleSumMoney; currentMonthSumInMoney = 0; preMonthOutSubInMoneySubcurrentMonthSumInMoney=preMonthOutSubInMoney-currentMonthSumInMoney; } userId = p.getUserId(); //还款操作 inMoney = PlanGenerateRuleFactory.getRandompInMoney(preMonthOutSubInMoney,currentMonthSumInMoney,inMoney,j,repaymentDate,preMonthOutSubInMoneySubcurrentMonthSumInMoney); currentMonthSumInMoney = currentMonthSumInMoney +inMoney; outMoney = PlanGenerateRuleFactory.getRadomOutMoneyHasBill(remainMoney,j+1,getMaxSaleDay); if(outMoney<=SIGLE_SALE_MIN_MONEY){ outMoney = 0; } if(checkSaleDay != 1){ outMoney = 0; } remainMoney =Math.abs(remainMoney-outMoney+inMoney); if(remainMoney<=planRemainMoney){ remainMoney =Math.abs(remainMoney+outMoney); outMoney=0; } if(outMoney ==0){ postCardId = getPostCardId(SIGLE_SALE_MIN_MONEY,userId); }else { postCardId = getPostCardId(outMoney,userId); } saleDate = getSaleDay(saleDate,1); //realRemainMoney = remainMoney+planRemainMoney;//实际剩余金额 if(inMoney>0){//还款了,必须刷出, outMoney = outMoney+inMoney-5; remainMoney =Math.abs(remainMoney-inMoney+5); } realRemainMoney = remainMoney; /*if(j==0){ realRemainMoney = remainMoney; }*/ p.setBatchNo(batchNo); p.setUserId(userId); p.setPostCardId(postCardId); p.setSaleDate(saleDate); p.setSumAllMoney(sumAllMoney); p.setInMoney(inMoney); p.setOutMoney(outMoney); p.setRemainMoney(realRemainMoney); p.setExcuteFlag("F"); p.setCreateBy(userId); p.setPostCardId(postCardId); p.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); checkIsAlreadyRunPaln = this.checkIsAlreadyRunPaln(p.getCreditCardId(), saleDate); if(checkIsAlreadyRunPaln == 1){ }else{ insertObject(p); } } } } } } /** * 更新计划 * @param plan * @param planId */ @Override @Transactional public void updatePlan(Plan plan, int planId){ updateObject(plan); int currentRemainMoney = plan.getRemainMoney(); Plan planParam =(Plan)getInfoByKey(planId); planParam.setBatchNo(planParam.getBatchNo().substring(0, 10)); List<Plan> updatePlanList = queryForList("getPlanInfoForUpdate",planParam); for(Plan planTmp : updatePlanList){ int inMoney = planTmp.getInMoney(); int outMoney = planTmp.getOutMoney(); int remainMoney = planTmp.getRemainMoney(); remainMoney = currentRemainMoney+ inMoney -outMoney; currentRemainMoney = remainMoney; planTmp.setRemainMoney(remainMoney); updateObject(planTmp); } } } <file_sep>package com.lj.app.core.common.util; import java.util.HashMap; public class CacheUtil { public static HashMap<String, Object> cache = new HashMap<String ,Object>(); public static void store(String key ,Object obj){ cache.put(key, obj); } public static Object find(String key){ return cache.get(key); } public static void removeCache(String key){ cache.remove(key); } public static boolean hasStore(String key){ return cache.get(key) != null ; } public static int getCacheSize(){ return cache.size(); } public static void clealAll() { cache.clear(); } } <file_sep>package com.lj.app.core.common.exception; public class InterfaceException extends Exception { private static final long serialVersionUID = 3583566093089790852L; public InterfaceException() { super(); } public InterfaceException(String e) { super(e); } public InterfaceException(Throwable cause) { super(cause); } public InterfaceException(String message, Throwable cause) { super(message, cause); } }<file_sep>package com.lj.app.core.common.security; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * DES安全编码组件 * * @version 1.0 */ public abstract class DESCoder { public static final String KEY_ALGORITHM = "DES"; public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding"; /*** * 转换密钥 * @param key * @return * @throws Exception */ public static Key toKey(byte []key) throws Exception { DESKeySpec keySpec = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey; } /** * 解密 * @param data * @param key * @return * @throws Exception */ public static byte[] decrypt(byte []data, byte []key) throws Exception { Key k = toKey(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, k); return cipher.doFinal(data); } /** * 加密操作 * @param data * @param key * @return * @throws Exception */ public static byte[] encrypt(byte []data, byte []key) throws Exception { Key k = toKey(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, k); return cipher.doFinal(data); } /** * 生成密钥 * @return * @throws Exception */ public static byte[] initKey() throws Exception { KeyGenerator kg = KeyGenerator.getInstance(CIPHER_ALGORITHM); kg.init(56); SecretKey secrectKey = kg.generateKey(); return secrectKey.getEncoded(); } } <file_sep>package com.lj.app.cardmanage.creditcard.service; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.service.BaseServiceImpl; import com.lj.app.cardmanage.creditcard.model.CreditCard; @Service("creditCardService") public class CreditCardServiceImpl extends BaseServiceImpl implements CreditCardService{ @Override public int getCreditBillDateCount(int billDate) { return countObject("getCreditBillDateCount",billDate); } /** * 动态查询用户的新信用卡数量 * @param creditCard * @return */ @Override public int getUserCreditBillDateCount(CreditCard creditCard){ return countObject("getUserCreditBillDateCount",creditCard); } } <file_sep>package com.lj.app.core.common.security; public abstract class RSACoder { } <file_sep><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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lj.app</groupId> <artifactId>cardmanage</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>cardmanage </name> <url>http://localhost:8080</url> <description> cardmanage </description> <developers> <developer> <id>liujie</id> <name>liujie</name> <url>http://localhost:8080/cardmanage</url> <organization>http://localhost:8080/cardmanage</organization> <organizationUrl>http://localhost:8080/cardmanage</organizationUrl> <email><EMAIL></email> <timezone>8</timezone> <roles> <role>Java Developer</role> </roles> </developer> </developers> <scm> <connection>scm:git:https://github.com/liujie15838028035/cardmanage.git</connection> <developerConnection>scm:git:https://github.com/liujie15838028035/cardmanage.git</developerConnection> <url>scm:git:https://github.com/liujie15838028035/cardmanage.git</url> </scm> <properties> <!-- 主要依赖库的版本定义 --> <junit.version>4.11</junit.version> <spring.version>3.2.11.RELEASE</spring.version> <struts.version>2.3.16.3</struts.version> <ibatis.version>2.0.8</ibatis.version> <aspectjrt.version>1.5.4</aspectjrt.version> <aspectjweaver.version>1.5.4</aspectjweaver.version> <cglib-nodep.version>2.2</cglib-nodep.version> <maven-antrun-plugin.version>1.6</maven-antrun-plugin.version> <selenium.version>2.44.0</selenium.version> <fitnesse.version>20130530</fitnesse.version> <fitnesse.port>8000</fitnesse.port> <fitnesse.expiration>0</fitnesse.expiration> <orgjson.version>20140107</orgjson.version> <maven-classpath-plugin.version>1.7</maven-classpath-plugin.version> <slf4j.version>1.6.4</slf4j.version> <operadriver.version>1.1</operadriver.version> <phantomjsdriver.version>1.2.1</phantomjsdriver.version> <commons-lang.version>2.6</commons-lang.version> <!-- Plugin的属性定义 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.6</jdk.version> <project.name>cardmanage</project.name> <project.build.finalName>cardmanage</project.build.finalName> </properties> <!-- 设定除中央仓库(repo1.maven.org/maven2/)外的其他仓库,按设定顺序进行查找. --> <repositories> <repository> <id>central</id> <name>Central Repository</name> <url>http://repo.maven.apache.org/maven2</url> <!-- <url>http://search.maven.org</url> --> <!-- <url>http://repository.jboss.com/maven2/</url> --> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <distributionManagement> <repository> <id>project-release</id> <name>project-release</name> <url>file://${project.basedir}/target/deploy</url> </repository> <snapshotRepository> <id>project-release</id> <name>project-release</name> <url>file://${project.basedir}/target/deploy</url> </snapshotRepository> </distributionManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.4</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-junit-plugin</artifactId> <version>${struts.version}</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.18</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>20030825.184428</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-ibatis</artifactId> <version>${ibatis.version}</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>2.3.4.726</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>20030211.134440</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>ehcache</groupId> <artifactId>ehcache</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.6</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>com.sun.xml.messaging.saaj</groupId> <artifactId>saaj-impl</artifactId> <version>1.3.23</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4-beta1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <!-- Sppring AOP --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectjweaver.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectjrt.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>${cglib-nodep.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.fitnesse</groupId> <artifactId>fitnesse</artifactId> <version>${fitnesse.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> </dependencies> <build> <!-- <directory>${project.basedir}/target</directory> --> <testSourceDirectory>${project.basedir}/src/test/java,${project.basedir}/src/acceptancetest/java</testSourceDirectory> <outputDirectory>${project.basedir}/src/main/webapp/Web-INF/classes</outputDirectory> <testOutputDirectory>${project.basedir}/target/test-classes</testOutputDirectory> <resources> <resource> <directory>${project.basedir}/src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>${project.basedir}/src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resouces-plugin</artifactId> <version>2.4.3</version> <configuration> <encoding>project.build.sourceEncoding</encoding> </configuration> </plugin> <!-- compiler插件, 设定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <showWarnings>true</showWarnings> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-changelog-plugin</artifactId> <version>2.2</version> <configuration> <type>range</type> <range>60</range> </configuration> </plugin> <!-- test插件, 仅测试名称为*Test的类,使用支持分组测试的surefire-junit47 driver --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <includes> <include>**/*Test.java</include> </includes> <excludes> <exclude>**/*AcceptanceTest.java</exclude> </excludes> <testFailureIgnore>true</testFailureIgnore> <argLine>-Xmx1024M</argLine> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.12.4</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-fitnesse-server-plugin</artifactId> <version>1.0</version> <configuration> <executions> <execution> <id>pre-run-integration-test</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> </execution> </executions> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.5.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <webResources> <resource> <!-- 元配置文件的目录,相对于pom.xml文件的路径 --> <!-- <directory>WebRoot/WEB-INF</directory> --> <!-- 是否过滤文件,也就是是否启动auto-config的功能 --> <!-- <filtering>false</filtering> --> <!-- 目标路径 --> <!-- <targetPath>WEB-INF</targetPath> --> <!-- <directory>WebRoot</directory> --> <directory>${project.basedir}/src/main/webapp</directory> </resource> </webResources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> <configuration> <locales>zh_CN</locales> <outPutEncoding>UTF-8</outPutEncoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>2.0-beta-1</version> <configuration> <url>http://localhost:8080/manager</url> <server>tomcat</server> <username>admin</username> <password><PASSWORD>> <path>/cardmanage</path> <contextReloadable>true</contextReloadable> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory> ${project.basedir}/src/main/webapp/WEB-INF/lib </outputDirectory> </configuration> </execution> </executions> <configuration> <excludeScope>provided</excludeScope> <excludeArtifactIds>jsp-api,servlet-api</excludeArtifactIds> <includeScope>runtime</includeScope> </configuration> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>${maven-antrun-plugin.version}</version> <executions> <execution> <phase> package </phase> <configuration> <target> <checksum> <fileset dir="${project.basedir}/src/main/webapp/WEB-INF/classes"> <include name="*" /> </fileset> </checksum> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>${project.basedir}/src/test/java</source> <source>${project.basedir}/src/acceptancetest/java</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.6</version> <reportSets> <reportSet> <reports> <report>index</report> <report>project-team</report> <report>plugins</report> <report>summary</report> <report>dependencies</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.14.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-changelog-plugin</artifactId> <version>2.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.3</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.0.1</version> <configuration> <sourceEncoding>${project.build.sourceEncoding}</sourceEncoding> <minimumTokens>100</minimumTokens> <targetJdk>${jdk.version}</targetJdk> <excludes> <exclude>**/xsd/*/*.java</exclude> </excludes> </configuration> </plugin> </plugins> </reporting> <profiles> <profile> <id>dev</id> <properties> <jdbc.url.server>jdbc:mysql://localhost:3306/cardmanage?</jdbc.url.server> <jdbc.username>root</jdbc.username> <jdbc.password><PASSWORD></jdbc.password> <jdbc.useUnicode>useUnicode=true</jdbc.useUnicode> <jdbc.urlEncoding>characterEncoding=UTF-8</jdbc.urlEncoding> </properties> </profile> <profile> <id>local</id> <properties> <jdbc.url.server>jdbc:mysql://localhost:3306/cardmanage?</jdbc.url.server> <jdbc.username>root</jdbc.username> <jdbc.password></jdbc.password> <jdbc.useUnicode>useUnicode=true</jdbc.useUnicode> <jdbc.urlEncoding>characterEncoding=UTF-8</jdbc.urlEncoding> </properties> </profile> <profile> <id>product</id> <properties> <jdbc.url.server>jdbc:mysql://localhost:3306/cardmanage?</jdbc.url.server> <jdbc.username>root</jdbc.username> <jdbc.password></jdbc.password> <jdbc.useUnicode>useUnicode=true</jdbc.useUnicode> <jdbc.urlEncoding>characterEncoding=UTF-8</jdbc.urlEncoding> </properties> </profile> <profile> <id>jar-with-dependencies</id> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2.1</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-jar</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>fitnesse</id> <build> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.6</version> <executions> <execution> <id>start-fitnesse</id> <phase>test</phase> <configuration> <tasks> <echo taskname="fitnesse" message="Starting FitNesse ${fitnesse.version}... (Selenium ${selenium.version})" /> <property file="saucelabs.properties" /> <!-- "Sensible" defaults --> <property name="sauce.user" value="[provide user through saucelabs.properties]" /> <property name="sauce.accesskey" value="[provide accesskey through saucelabs.properties]" /> <java classname="fitnesseMain.FitNesseMain" classpathref="maven.runtime.classpath" fork="true"> <arg line="-p ${fitnesse.port}" /> <arg line="-d ." /> <arg line="-e ${fitnesse.expiration}" /> <jvmarg value="-DBROWSER=firefox" /> <jvmarg value="-Dsauce.user=${sauce.user}" /> <jvmarg value="-Dsauce.accesskey=${sauce.accesskey}" /> </java> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.fitnesse.plugins</groupId> <artifactId>maven-classpath-plugin</artifactId> <version>${maven-classpath-plugin.version}</version> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>fitnesse-integration</id> <activation> <activeByDefault>false</activeByDefault> </activation> <build> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.6</version> <executions> <execution> <id>start-fitnesse-integration</id> <phase>integration-test</phase> <configuration> <tasks> <echo taskname="fitnesse" message="Starting FitNesse..." /> <java classname="fitnesseMain.FitNesseMain" classpathref="maven.runtime.classpath" fork="true" failonerror="true"> <arg line="-p 8001" /> <arg line="-c CardManage.CardManageAcceptanceTestSuites&amp;format=text" /> <arg line="-d ." /> <jvmarg value="-DBROWSER=phantomjs" /> </java> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.fitnesse.plugins</groupId> <artifactId>maven-classpath-plugin</artifactId> <version>${maven-classpath-plugin.version}</version> <scope>runtime</scope> </dependency> </dependencies> </profile> </profiles> </project><file_sep>package com.lj.app.core.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static final String DATE_FOMRAT_yyyyMMddhhMMss = "yyyy-MM-dd hh:mm:ss"; public static final String DATE_FORMAT_YYYYMMDDHHMMSS ="yyyyMMdd hhmmss"; public static final String getNowDateYYYYMMddHHMMSS() { return getNowDate(DATE_FOMRAT_yyyyMMddhhMMss); } /**得到当前时间 * @param format 时间格式 * @return */ public static String getNowDate(String format) { SimpleDateFormat sd = new SimpleDateFormat(format); String date = sd.format(new Date(System.currentTimeMillis())); return date; } /**格式化字符串为Date对象 * @param date * @param format * @return */ public static Date formatDate(String date, String format) { SimpleDateFormat sd = new SimpleDateFormat(format); Date d = null; try { d = sd.parse(date); } catch (ParseException e) { e.printStackTrace(); } return d; } /**格式化Date对象为string * @param date * @param format * @return */ public static String formatDate(Date date, String format){ SimpleDateFormat sDateFormat = new SimpleDateFormat(format); return sDateFormat.format(date); } public static int getIntervalDays(Date fDate, Date oDate) { if (null == fDate || null == oDate) { return -1; } long intervalMilli = oDate.getTime() - fDate.getTime(); return (int) (intervalMilli / (24 * 60 * 60 * 1000)); } public static int getIntervalDays(String fDateStr, String oDateStr) { if (null == fDateStr || null == oDateStr) { return -1; } Date fDate = formatDate(fDateStr,DATE_FOMRAT_yyyyMMddhhMMss); Date oDate = formatDate(oDateStr,DATE_FOMRAT_yyyyMMddhhMMss); long intervalMilli = fDate.getTime() - oDate.getTime(); return (int) (intervalMilli / (24 * 60 * 60 * 1000)); } } <file_sep>package com.lj.app.core.common.util; import static org.junit.Assert.assertEquals; import org.junit.Test; public class AjaxResultTest { @Test public void setOpResultTest() { AjaxResult ajaxResult = new AjaxResult(); ajaxResult.setOpResult("success"); assertEquals("success", ajaxResult.getOpResult()); } } <file_sep>package com.lj.app.core.common.pagination; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; public class PageTool { private static final String JSONPAGE = "page"; private static final String JSONROWS = "rows"; public static String convert(String str) { if ((str == null) || (str.equals(""))) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if ((c >= 'A') && (c <= 'Z')) { if (i == 0) sb.append(Character.toLowerCase(c)); else sb.append("_" + Character.toLowerCase(c)); } else { sb.append(c); } } return sb.toString(); } public static String pageToJsonJQGrid(Page page) { Map<String,Object> mapResult = new HashMap<String,Object>(); mapResult.put("page", page.getPageNumber()); mapResult.put("total", page.getTotalPages()); mapResult.put("records", page.getTotalCount()); mapResult.put("rows", page.getResult()); JSONObject jsonObj = new JSONObject(); //return jsonObjectToJsonJQGrid(jsonObj.fromObject(mapResult)); return Page.toJsonString(mapResult); } public static String mapPageToJsonJQGrid(Page page) { Map<String,Object> mapResult = new HashMap<String,Object>(); mapResult.put("page", page.getPageNumber()); mapResult.put("total", page.getTotalPages()); mapResult.put("records", page.getTotalCount()); mapResult.put("rows", page.getResult()); return toJsonString(page,mapResult); } public static String jsonObjectToJsonJQGrid(JSONObject jsonObject) { String jsonResult = null; try { if(jsonObject==null){ return null; } jsonResult=jsonObject.toString(); } catch (Exception e) { e.printStackTrace(); } return jsonResult; } public static String pageToJsonJQGridWithNoDateFormat(Page page) { Map<String,Object> mapResult = new HashMap<String,Object>(); mapResult.put("page", page.getPageNumber()); mapResult.put("total", page.getTotalPages()); mapResult.put("records", page.getTotalCount()); mapResult.put("rows", page.getResult()); JSONObject jsonObj = new JSONObject(); return jsonObjectToJsonJQGrid(JSONObject.fromObject(mapResult)); } public static String toJsonString(Page page,Object object){ return Page.toJsonString(object); } public String toJsonString(Page page,List list){ return page.toJsonString(list); } } <file_sep>package com.lj.app.core.common.security; /** * 常量定义. */ public class SecurityConstants { public static final String INDEX = "index"; public static final String LOGIN = "login"; public static final String NOPERMISSION = "noPermission"; public static final String SECURITY_CONTEXT = "securityContext"; public static final String SYSERROR = "syserror"; public static final int PRIVILEGE_MENU = 1; public static final int PRIVILEGE_BUTTON = 2; public static final String DOMAIN_CARD_MANAGE = "CM"; }<file_sep>package com.lj.app.cardmanage.base.dao; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.stereotype.Component; import com.ibatis.sqlmap.client.SqlMapClient; import com.lj.app.cardmanage.base.model.BaseModel; @Component("baseDao") public class BaseDaoImpl<T> extends SqlMapClientDaoSupport implements BaseDao{ @Resource(name = "sqlMapClient") private SqlMapClient sqlMapClient; @PostConstruct public void initSqlMapClient(){ super.setSqlMapClient(sqlMapClient); } @Override public void insertObject(String sqlId, Object obj) { getSqlMapClientTemplate().insert(sqlId, obj); } @Override public void updateObject(String sqlId, Object obj) { getSqlMapClientTemplate().update(sqlId,obj); } @Override public void deleteObject(String sqlId, Object obj) { getSqlMapClientTemplate().delete(sqlId, obj); } @Override public BaseModel findObject(String sqlId, Object obj) { return (BaseModel)getSqlMapClientTemplate().queryForObject(sqlId, obj); } @Override public Object queryForObject(String sqlId, Object obj) { return getSqlMapClientTemplate().queryForObject(sqlId, obj); } @Override public BaseModel getInfoByKey(String sqlId, Object obj) { return (BaseModel)getSqlMapClientTemplate().queryForObject(sqlId, obj); } @Override public List<BaseModel> findBaseModeList(String sqlId, Object obj) { return getSqlMapClientTemplate().queryForList(sqlId,obj); } @Override public List<BaseModel> findBaseModePageList(String sqlId, Object obj) { return getSqlMapClientTemplate().queryForList(sqlId,obj); } @Override public List queryForList(String statementName) throws DataAccessException { return getSqlMapClientTemplate().queryForList(statementName); } @Override public List queryForList(String statementName, Object parameterObject) { return getSqlMapClientTemplate().queryForList(statementName,parameterObject); } @Override public List queryForList(String statementName, int skipResults,int maxResults) throws DataAccessException { return getSqlMapClientTemplate().queryForList(statementName,skipResults,maxResults); } @Override public List queryForList(String statementName, Object parameterObject,int skipResults, int maxResults) throws DataAccessException { return getSqlMapClientTemplate().queryForList(statementName,parameterObject,skipResults,maxResults); } @Override public int countObject(String sqlId, Object obj) { int count = (Integer)getSqlMapClientTemplate().queryForObject(sqlId, obj); return count; } } <file_sep>/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50519 Source Host : localhost:3306 Source Database : cardmanage Target Server Type : MYSQL Target Server Version : 50519 File Encoding : 65001 Date: 2015-09-12 11:01:10 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `batch` -- ---------------------------- DROP TABLE IF EXISTS `batch`; CREATE TABLE `batch` ( `id` int(11) NOT NULL AUTO_INCREMENT, `batchCode` varchar(20) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT NULL, `enableFlag` varchar(2) DEFAULT NULL, `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of batch -- ---------------------------- -- ---------------------------- -- Table structure for `cmpermission` -- ---------------------------- DROP TABLE IF EXISTS `cmpermission`; CREATE TABLE `cmpermission` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` varchar(200) DEFAULT NULL, `name` varchar(200) DEFAULT NULL, `url` varchar(400) DEFAULT NULL, `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` date DEFAULT NULL, `enableFlag` varchar(2) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of cmpermission -- ---------------------------- INSERT INTO `cmpermission` VALUES ('1', 'S0101', '用户登录', '/jsp/user/userList.jsp', '0', null, null, null, '0', null); -- ---------------------------- -- Table structure for `creditcard` -- ---------------------------- DROP TABLE IF EXISTS `creditcard`; CREATE TABLE `creditcard` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cardNo` varchar(50) DEFAULT NULL, `bankNo` varchar(100) DEFAULT NULL, `userName` varchar(20) DEFAULT NULL, `maxLimit` float DEFAULT NULL, `secNo` varchar(20) DEFAULT NULL, `validateDate` varchar(30) DEFAULT NULL, `billDate` int(11) DEFAULT NULL, `repaymentDate` int(11) DEFAULT NULL, `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` varchar(20) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT '0', `enableFlag` varchar(2) DEFAULT 'T', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of creditcard -- ---------------------------- INSERT INTO `creditcard` VALUES ('1', 'C1001', '郑州银行', '张三', '300', '2', '2015-06-20', '21', '15', '0', '2015-07-05', null, null, '0', 'T'); INSERT INTO `creditcard` VALUES ('2', 'S001', 'S001', 'S001', '3000', '205', '2015-06-20', '3', '20', '0', '2015-07-05', '0', '2015-07-05 10:51:02', '0', 'T'); INSERT INTO `creditcard` VALUES ('3', 'U2001000000000000000', 'U2001', 'U2001', '30000', '200', '2015-06-20', '28', '20', '0', '2015-07-05', '0', '2015-08-22 03:52:51', '0', 'T'); INSERT INTO `creditcard` VALUES ('4', '11111', '11', '??', '133', '333', '33', '3', '20', '0', '2015-08-09', '0', '2015-08-09 01:21:18', '0', 'T'); INSERT INTO `creditcard` VALUES ('6', '11', '11', '测试用户01', '33', '333', '33', '3', '20', '0', '2015-08-09', null, null, '0', 'T'); INSERT INTO `creditcard` VALUES ('7', 'user222', '33', '测试02', '30', '33', '33', '2', '20', '0', '2015-08-09', '0', '2015-08-09 01:29:31', '0', 'T'); INSERT INTO `creditcard` VALUES ('9', '44444444444444444444', '招商银行', '11111111111111', '33', '333', '1', '2', '20', '0', '2015-08-15', '0', '2015-08-15 04:37:35', '0', 'T'); INSERT INTO `creditcard` VALUES ('10', '12345671234455555555', '中国银行', '张三', '20000', '345', '2015-06-20', '16', '6', '0', '2015-08-16', '0', '2015-08-16 09:45:06', '0', 'T'); -- ---------------------------- -- Table structure for `dayplantmpresult` -- ---------------------------- DROP TABLE IF EXISTS `dayplantmpresult`; CREATE TABLE `dayplantmpresult` ( `id` int(11) NOT NULL AUTO_INCREMENT, `day` int(11) DEFAULT NULL, `orderId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=36850 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of dayplantmpresult -- ---------------------------- INSERT INTO `dayplantmpresult` VALUES ('36819', '20', '20'); INSERT INTO `dayplantmpresult` VALUES ('36820', '26', '26'); INSERT INTO `dayplantmpresult` VALUES ('36821', '2', '2'); INSERT INTO `dayplantmpresult` VALUES ('36822', '6', '6'); INSERT INTO `dayplantmpresult` VALUES ('36823', '14', '14'); INSERT INTO `dayplantmpresult` VALUES ('36824', '8', '8'); INSERT INTO `dayplantmpresult` VALUES ('36825', '4', '4'); INSERT INTO `dayplantmpresult` VALUES ('36826', '9', '9'); INSERT INTO `dayplantmpresult` VALUES ('36827', '13', '13'); INSERT INTO `dayplantmpresult` VALUES ('36828', '22', '22'); INSERT INTO `dayplantmpresult` VALUES ('36829', '16', '16'); INSERT INTO `dayplantmpresult` VALUES ('36830', '18', '18'); INSERT INTO `dayplantmpresult` VALUES ('36831', '12', '12'); INSERT INTO `dayplantmpresult` VALUES ('36832', '19', '19'); INSERT INTO `dayplantmpresult` VALUES ('36833', '7', '7'); INSERT INTO `dayplantmpresult` VALUES ('36834', '25', '25'); INSERT INTO `dayplantmpresult` VALUES ('36835', '24', '24'); INSERT INTO `dayplantmpresult` VALUES ('36836', '28', '28'); INSERT INTO `dayplantmpresult` VALUES ('36837', '10', '10'); INSERT INTO `dayplantmpresult` VALUES ('36838', '21', '21'); -- ---------------------------- -- Table structure for `plan` -- ---------------------------- DROP TABLE IF EXISTS `plan`; CREATE TABLE `plan` ( `id` int(11) NOT NULL AUTO_INCREMENT, `batchNo` varchar(30) DEFAULT NULL, `userId` int(11) DEFAULT NULL, `creditCardId` int(11) DEFAULT NULL, `postCardId` int(11) DEFAULT NULL, `saleDate` date DEFAULT NULL, `sumAllMoney` int(11) DEFAULT NULL, `inMoney` int(11) DEFAULT NULL, `outMoney` int(11) DEFAULT NULL, `remainMoney` int(11) DEFAULT NULL, `excuteFlag` varchar(2) DEFAULT NULL, `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` date DEFAULT NULL, `enableFlag` varchar(2) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1300 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of plan -- ---------------------------- INSERT INTO `plan` VALUES ('511', '2015-08-24 08:30:00', '0', '3', '1', '2015-08-25', '30000', '0', '5000', '25000', 'T', '0', '2015-08-24', null, null, null, null); INSERT INTO `plan` VALUES ('512', '2015-08-24 08:30:00', '0', '3', '14', '2015-08-26', '30000', '0', '0', '25000', 'T', '0', '2015-08-24', null, null, null, null); INSERT INTO `plan` VALUES ('661', '2015-08-28 10:05:00', '0', '3', '14', '2015-08-29', '30000', '1650', '160', '28190', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('662', '2015-08-28 10:05:00', '0', '3', '14', '2015-08-30', '30000', '1139', '0', '15329', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('663', '2015-08-28 10:05:00', '0', '3', '1', '2015-08-31', '30000', '641', '4284', '11686', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('664', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-01', '30000', '533', '0', '12219', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('665', '2015-08-28 10:05:00', '0', '3', '1', '2015-09-02', '30000', '217', '5121', '7315', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('666', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-03', '30000', '246', '1379', '6182', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('667', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-04', '30000', '160', '1611', '4731', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('668', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-05', '30000', '120', '0', '4851', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('669', '2015-08-28 10:05:00', '0', '3', '1', '2015-09-06', '30000', '0', '2200', '2651', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('670', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-07', '30000', '0', '654', '1997', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('671', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-08', '30000', '294', '0', '2291', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('672', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-09', '30000', '0', '726', '1565', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('673', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-10', '30000', '0', '1556', '9', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('674', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-11', '30000', '0', '463', '-454', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('675', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-12', '30000', '0', '597', '-1051', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('676', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-13', '30000', '0', '337', '-1388', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('677', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-14', '30000', '0', '0', '-1388', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('678', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-15', '30000', '0', '0', '-1388', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('679', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-16', '30000', '0', '554', '-1942', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('680', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-17', '30000', '0', '258', '-2200', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('681', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-18', '30000', '0', '132', '-2332', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('682', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-19', '30000', '0', '0', '-2332', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('683', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-20', '30000', '0', '0', '-2332', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('684', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-21', '30000', '0', '0', '-2332', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('685', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-22', '30000', '0', '0', '-2332', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('686', '2015-08-28 10:05:00', '0', '3', '13', '2015-09-23', '30000', '0', '309', '-2641', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('687', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-24', '30000', '0', '0', '-2641', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('688', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-25', '30000', '0', '0', '-2641', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('689', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-26', '30000', '0', '105', '-2746', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('690', '2015-08-28 10:05:00', '0', '3', '14', '2015-09-27', '30000', '0', '0', '-2746', 'F', '0', '2015-08-28', null, null, null, null); INSERT INTO `plan` VALUES ('1213', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-04', '3000', '0', '0', '3000', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1214', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-05', '3000', '0', '0', '3000', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1215', '2015-09-03 10:50:00', '0', '2', '13', '2015-09-06', '3000', '0', '438', '2562', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1216', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-07', '3000', '0', '280', '2282', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1217', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-08', '3000', '0', '0', '2282', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1218', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-09', '3000', '0', '0', '2282', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1219', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-10', '3000', '0', '103', '2179', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1220', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-11', '3000', '0', '0', '2179', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1221', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-12', '3000', '0', '232', '1947', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1222', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-13', '3000', '0', '0', '1947', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1223', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-14', '3000', '0', '0', '1947', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1224', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-15', '3000', '0', '216', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1225', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-16', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1226', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-17', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1227', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-18', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1228', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-19', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1229', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-20', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1230', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-21', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1231', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-22', '3000', '0', '0', '1731', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1232', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-23', '3000', '0', '110', '1621', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1233', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-24', '3000', '0', '113', '1508', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1234', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-25', '3000', '0', '0', '1508', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1235', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-26', '3000', '0', '118', '1390', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1236', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-27', '3000', '0', '179', '1211', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1237', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-28', '3000', '0', '128', '1083', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1238', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-29', '3000', '0', '0', '1083', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1239', '2015-09-03 10:50:00', '0', '2', '14', '2015-09-30', '3000', '0', '0', '1083', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1240', '2015-09-03 10:50:00', '0', '2', '14', '2015-10-01', '3000', '0', '0', '1083', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1241', '2015-09-03 10:50:00', '0', '2', '14', '2015-10-02', '3000', '0', '0', '1083', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1242', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-04', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1243', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-05', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1244', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-06', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1245', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-07', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1246', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-08', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1247', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-09', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1248', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-10', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1249', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-11', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1250', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-12', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1251', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-13', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1252', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-14', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1253', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-15', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1254', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-16', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1255', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-17', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1256', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-18', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1257', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-19', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1258', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-20', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1259', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-21', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1260', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-22', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1261', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-23', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1262', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-24', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1263', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-25', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1264', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-26', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1265', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-27', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1266', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-28', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1267', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-29', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1268', '2015-09-03 10:50:00', '0', '4', '14', '2015-09-30', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1269', '2015-09-03 10:50:00', '0', '4', '14', '2015-10-01', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1270', '2015-09-03 10:50:00', '0', '4', '14', '2015-10-02', '133', '0', '0', '133', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1271', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-04', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1272', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-05', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1273', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-06', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1274', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-07', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1275', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-08', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1276', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-09', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1277', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-10', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1278', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-11', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1279', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-12', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1280', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-13', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1281', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-14', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1282', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-15', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1283', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-16', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1284', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-17', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1285', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-18', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1286', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-19', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1287', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-20', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1288', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-21', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1289', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-22', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1290', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-23', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1291', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-24', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1292', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-25', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1293', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-26', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1294', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-27', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1295', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-28', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1296', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-29', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1297', '2015-09-03 10:50:00', '0', '6', '14', '2015-09-30', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1298', '2015-09-03 10:50:00', '0', '6', '14', '2015-10-01', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); INSERT INTO `plan` VALUES ('1299', '2015-09-03 10:50:00', '0', '6', '14', '2015-10-02', '33', '0', '0', '33', 'F', '0', '2015-09-03', null, null, null, null); -- ---------------------------- -- Table structure for `plandaytmp` -- ---------------------------- DROP TABLE IF EXISTS `plandaytmp`; CREATE TABLE `plandaytmp` ( `id` int(11) NOT NULL AUTO_INCREMENT, `day` int(11) DEFAULT NULL, `orderId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=176 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of plandaytmp -- ---------------------------- INSERT INTO `plandaytmp` VALUES ('147', '1', '1'); INSERT INTO `plandaytmp` VALUES ('148', '2', '2'); INSERT INTO `plandaytmp` VALUES ('149', '3', '3'); INSERT INTO `plandaytmp` VALUES ('150', '4', '4'); INSERT INTO `plandaytmp` VALUES ('151', '5', '5'); INSERT INTO `plandaytmp` VALUES ('152', '6', '6'); INSERT INTO `plandaytmp` VALUES ('153', '7', '7'); INSERT INTO `plandaytmp` VALUES ('154', '8', '8'); INSERT INTO `plandaytmp` VALUES ('155', '9', '9'); INSERT INTO `plandaytmp` VALUES ('156', '10', '10'); INSERT INTO `plandaytmp` VALUES ('157', '11', '11'); INSERT INTO `plandaytmp` VALUES ('158', '12', '12'); INSERT INTO `plandaytmp` VALUES ('159', '13', '13'); INSERT INTO `plandaytmp` VALUES ('160', '14', '14'); INSERT INTO `plandaytmp` VALUES ('161', '15', '15'); INSERT INTO `plandaytmp` VALUES ('162', '16', '16'); INSERT INTO `plandaytmp` VALUES ('163', '17', '17'); INSERT INTO `plandaytmp` VALUES ('164', '18', '18'); INSERT INTO `plandaytmp` VALUES ('165', '19', '19'); INSERT INTO `plandaytmp` VALUES ('166', '20', '20'); INSERT INTO `plandaytmp` VALUES ('167', '21', '21'); INSERT INTO `plandaytmp` VALUES ('168', '22', '22'); INSERT INTO `plandaytmp` VALUES ('169', '23', '23'); INSERT INTO `plandaytmp` VALUES ('170', '24', '24'); INSERT INTO `plandaytmp` VALUES ('171', '25', '25'); INSERT INTO `plandaytmp` VALUES ('172', '26', '26'); INSERT INTO `plandaytmp` VALUES ('173', '27', '27'); INSERT INTO `plandaytmp` VALUES ('174', '28', '28'); INSERT INTO `plandaytmp` VALUES ('175', '29', '29'); -- ---------------------------- -- Table structure for `postcard` -- ---------------------------- DROP TABLE IF EXISTS `postcard`; CREATE TABLE `postcard` ( `id` int(11) NOT NULL AUTO_INCREMENT, `postCardNo` varchar(50) DEFAULT NULL, `manName` varchar(200) DEFAULT NULL, `rate` float DEFAULT NULL, `minMoney` float DEFAULT NULL, `maxMoney` float DEFAULT NULL, `trade` varchar(100) DEFAULT NULL, `bindBank` varchar(100) DEFAULT NULL, `cardNo` varchar(50) DEFAULT NULL, `userName` varchar(20) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT NULL, `enableFlag` varchar(2) DEFAULT NULL, `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of postcard -- ---------------------------- INSERT INTO `postcard` VALUES ('1', 'system_001', 'manName', '0.8', '2000', '10000', '行业01', '建设银行', '444444444444444444444', '张三', null, null, '0', '2015-07-05', null, null); INSERT INTO `postcard` VALUES ('2', 'system_002', 'manName', '0.8', '2000', '10000', '行业01', '建设银行', '444444444444444444444', '张三', null, null, '0', '2015-07-05', null, null); INSERT INTO `postcard` VALUES ('12', 'system_004', '商户01', '0.8', '300', '100', '餐饮', '建设银行', '44444444444444444', '张三', null, null, '0', '2015-07-05', null, null); INSERT INTO `postcard` VALUES ('13', 'system_005', 'U2001', '0.5', '300', '4000', '行业01', '建设银行', '44444444444', '张三', '0', 'T', '0', '2015-07-05', null, null); INSERT INTO `postcard` VALUES ('14', 'system_006', '商户01', '0.38', '0', '100000', '111', '1111', '111111111111111111', '1111', '0', 'T', '0', '2015-08-15', '0', '2015-08-15'); INSERT INTO `postcard` VALUES ('15', 'system_007', '张三家电超市', '0.38', '500', '2000', '家电', '建设银行', '11111111111111111111', '张三', '0', 'T', '0', '2015-08-16', null, null); INSERT INTO `postcard` VALUES ('16', 'system_008', '张三美发', '0.78', '100', '800', '美容', '张三', '11111111111111111111', '张三', '0', 'T', '0', '2015-08-16', null, null); INSERT INTO `postcard` VALUES ('17', 'liujie_001', 'liujie', '0.38', '100', '10000', '超市', '建行', 'C0000000000000000000', '刘杰', '0', 'T', '49', '2015-08-22', null, null); INSERT INTO `postcard` VALUES ('18', 'liujie_002', '刘杰', '0.49', '1000', '500000', '餐饮', '建行', 'C0000000000000000002', 'liuji', '0', 'T', '49', '2015-08-22', null, null); INSERT INTO `postcard` VALUES ('19', 'liujie_003', '刘杰', '0.78', '500', '500000', 'KTV', '建行', 'C3333333333333333333', '刘杰', '0', 'T', '49', '2015-08-22', null, null); INSERT INTO `postcard` VALUES ('21', 'liujie_004', '刘杰', '0.59', '5000', '60000', '保险', '建行', 'C4444444444444444444', '刘杰', '0', 'T', '49', '2015-08-22', null, null); -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `loginNo` varchar(50) DEFAULT NULL, `pwd` varchar(200) DEFAULT NULL, `userName` varchar(50) DEFAULT NULL, `cardNo` varchar(50) DEFAULT NULL, `address` varchar(200) DEFAULT NULL, `mobile` varchar(50) DEFAULT NULL, `lockStatus` varchar(2) DEFAULT '', `enableFlag` varchar(2) DEFAULT 'T', `createBy` int(11) DEFAULT NULL, `createDate` date DEFAULT NULL, `updateBy` int(11) DEFAULT NULL, `updateDate` date DEFAULT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('0', 'system', 'B3r19IYVtJU=', 'system', '41222419878809', 'address', '15838028035', '0', 'T', '1', '2015-07-04', '1', '2015-08-22'); INSERT INTO `user` VALUES ('23', 'user2', 'B3r19IYVtJU=', 'user2', 'user2', 'user2', 'user2', '0', 'T', '1', '2015-07-05', '0', '2015-08-08'); INSERT INTO `user` VALUES ('24', 'user3', 'G9YZLEvvN/o=', 'user3', 'user3', 'user3', 'user3', '0', 'T', '1', '2015-07-05', null, null); INSERT INTO `user` VALUES ('25', 'user22', '848awTWMv6c=', 'user22', 'user22', 'user22', 'user22', '0', 'T', '0', '2015-07-05', null, null); INSERT INTO `user` VALUES ('26', 'user222', 'Xa+Q9J/DIHg=', 'user222', 'user222', 'user222', 'user222', '0', 'T', '0', '2015-07-05', null, null); INSERT INTO `user` VALUES ('31', 'user4', '5iyKvtt6vc2KXN/cj1HMbw==', 'user44', 'user4', 'user4', 'user4', '0', 'T', '0', '2015-07-05', null, null); INSERT INTO `user` VALUES ('32', 'user5', 'B3r19IYVtJU=', 'user5', '3333', '33333333333333', '15833887796', '0', 'T', '0', '2015-07-19', null, null); INSERT INTO `user` VALUES ('44', '111', 'caplhhj5SHw=', '测试用户01', '333333', '33', '33333', '0', 'T', '0', '2015-08-09', null, null); INSERT INTO `user` VALUES ('47', 'user6', 'B3r19IYVtJU=', 'user6', '11111111111111111111', '河南省郑州市区', '444444444444444', '0', 'T', '0', '2015-08-16', null, null); INSERT INTO `user` VALUES ('49', 'liujie', 'B3r19IYVtJU=', 'liujie', 'U0000000000000000000', 'zhengzhou', '15838028035', '0', 'T', '0', '2015-08-22', null, null); -- ---------------------------- -- Procedure structure for `exceutePlanCron` -- ---------------------------- DROP PROCEDURE IF EXISTS `exceutePlanCron`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `exceutePlanCron`(in param1 varchar(20),in param2 varchar(20),out p_val int) BEGIN DECLARE v_pre_month_bill_sum_money int ; -- 上月账单总额度 DECLARE v_pre_month_bill_sale_money int; -- 上月消费总金额 DECLARE v_pre_month_bill_pay_money int ; -- 上月还款总金额 DECLARE v_pre_month_not_pay_bill_money int; -- 上月欠款总金额 DECLARE v_cur_month_bill_sum_money int ; -- 当月账单总额度 DECLARE v_cur_month_bill_sale_money int; -- 当月消费总金额 DECLARE v_cur_month_bill_pay_money int ; -- 当月还款总金额 DECLARE v_cur_month_not_pay_bill_money int; -- 当月欠款总金额 DECLARE v_billDATE int; -- 账单日 DECLARE v_credit_bill_date_count int; -- 账单日信用卡数量 DECLARE v_pre_bill_sum_money int ; -- 前一个帐号总金额 DECLARE v_current_sale_sum_money int; -- 当前消费总金额 DECLARE v_current_pay_sum_money int; -- 当前还款总金额 DECLARE v_bill_count int; -- 每张信用卡的账单数量 DECLARE v_bill_sale_rate double; -- 账单消费比率(总金额的70%-80%) DECLARE v_bill_credit_no VARCHAR(30); -- 信用卡号 DECLARE v_pre_bill_date date; -- 前一个月帐号日 DECLARE v_current_bill_day date; -- 当前日期 DECLARE v_next_bill_day date; -- 下一个账单日期 DECLARE v_bill_sum_days int; -- 账单总天数 DECLARE v_credit_no VARCHAR(30); -- 信用卡编号 DECLARE i INT; DECLARE v_day_count INT; DECLARE v_sale_day date; SELECT DAYOFMONTH( DATE_FORMAT(NOW(),'%Y-%m-%d %h:%i:%s')) into v_billDATE ; select date_format(now(),'%y-%m-%d') into v_current_bill_day; select date_format(date_add(NOW(), interval 1 MONTH),'%y-%m-%d') into v_next_bill_day; SELECT v_next_bill_day - v_current_bill_day INTO v_bill_sum_days; SELECT count(1) INTO v_credit_bill_date_count FROM CREDITCARD F where f.billDate=v_billDate; select date_add(NOW(), interval 1 MONTH) ; -- 获取下一个月的今天 select date_sub(NOW(), interval 1 MONTH); -- 获取上一个月的今天 if v_credit_bill_date_count >0 then SELECT * FROM CREDITCARD F where f.billDate=v_billDate; SET v_credit_no='C001'; loop_label: LOOP SET i=i+1; IF v_day_count>i then select DATE_ADD(now(), Interval +i day) INTO v_sale_day; if f_check_sale_day(i) =1 then INSERT INTO Plan(crditId,saleDate,outmoney) VALUES(i,iv_sale_day,100); else INSERT INTO Plan(crditId,saleDate,outmoney) VALUES(i,iv_sale_day,0); end if; END IF; if i>dayCount then LEAVE loop_label; end if; END LOOP loop_label; end if; if v_credit_bill_date_count is null then SELECT * FROM CREDITCARD F where f.billDate=v_billDate; end if; COMMIT; END ;; DELIMITER ; -- ---------------------------- -- Procedure structure for `executePlanProc` -- ---------------------------- DROP PROCEDURE IF EXISTS `executePlanProc`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `executePlanProc`() BEGIN DECLARE v_pre_month_bill_sum_money INT ; -- 上月账单总额度 DECLARE v_pre_month_bill_sale_money INT; -- 上月消费总金额 DECLARE v_pre_month_bill_pay_money INT ; -- 上月还款总金额 DECLARE v_pre_month_not_pay_bill_money INT; -- 上月欠款总金额 DECLARE v_cur_month_bill_sum_money INT ; -- 当月账单总额度 DECLARE v_cur_month_bill_sale_money INT; -- 当月消费总金额 DECLARE v_cur_month_bill_pay_money INT ; -- 当月还款总金额 DECLARE v_cur_month_not_pay_bill_money INT; -- 当月欠款总金额 DECLARE v_billDATE INT; -- 账单日 DECLARE v_credit_bill_date_count INT; -- 账单日信用卡数量 DECLARE v_pre_bill_sum_money INT ; -- 前一个帐号总金额 DECLARE v_current_sale_sum_money INT; -- 当前消费总金额 DECLARE v_current_pay_sum_money INT; -- 当前还款总金额 DECLARE v_bill_count INT; -- 每张信用卡的账单数量 DECLARE v_bill_sale_rate DOUBLE; -- 账单消费比率(总金额的70%-80%) DECLARE v_bill_credit_no VARCHAR(30); -- 信用卡号 DECLARE v_pre_bill_date DATE; -- 前一个月帐号日 DECLARE v_current_bill_day DATE; -- 当前日期 DECLARE v_next_bill_day DATE; -- 下一个账单日期 DECLARE v_bill_sum_days INT; -- 账单总天数 DECLARE v_credit_no VARCHAR(30); -- 信用卡编号 DECLARE i INT; DECLARE dayCount INT; DECLARE v_day_count INT; DECLARE v_sale_day DATE; DECLARE v_is_sale_date INT; SELECT DAYOFMONTH( DATE_FORMAT(NOW(),'%Y-%m-%d %h:%i:%s')) into v_billDATE ; select date_format(now(),'%y-%m-%d') into v_current_bill_day; select date_format(date_add(NOW(), interval 1 MONTH),'%y-%m-%d') into v_next_bill_day; SELECT v_next_bill_day - v_current_bill_day INTO v_bill_sum_days; SELECT count(1) INTO v_credit_bill_date_count FROM CREDITCARD F where f.billDate=v_billDate; select date_add(NOW(), interval 1 MONTH) ; -- 获取下一个月的今天 select date_sub(NOW(), interval 1 MONTH); -- 获取上一个月的今天 SEt dayCount=30; SET i=0; SET v_is_sale_date = 0; SET v_sale_day = now(); if v_credit_bill_date_count >0 then SELECT * FROM CREDITCARD F where f.billDate=v_billDate; SET v_credit_no='C001'; SET v_day_count =1; IF v_day_count>i then loop_label: LOOP SET i=i+1; SELECT f_check_sale_day(i) INTO v_is_sale_date; select DATE_ADD(now(), Interval i day) INTO v_sale_day; if v_is_sale_date =1 then INSERT INTO Plan(creditCardId,saleDate,outmoney) VALUES(i,v_sale_day,100); COMMIT; else INSERT INTO Plan(creditCardId,saleDate,outmoney) VALUES(i,v_sale_day,0); COMMIT; end if; if i>dayCount then LEAVE loop_label; end if; END LOOP loop_label; end if; end if; if v_credit_bill_date_count is null then SELECT * FROM CREDITCARD F where f.billDate=v_billDate; end if; COMMIT; END ;; DELIMITER ; -- ---------------------------- -- Function structure for `f_check_sale_day` -- ---------------------------- DROP FUNCTION IF EXISTS `f_check_sale_day`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `f_check_sale_day`(`day` int) RETURNS int(11) BEGIN #Routine body goes here... DECLARE i int ; DECLARE v_count int; SET i = 0; SELECT count(day) INTO v_count FROM dayplantmpresult d WHERE d.day=day; IF v_count is null OR v_count =0 then SET i = 0; else SET i = 1; end if; RETURN i; END ;; DELIMITER ; -- ---------------------------- -- Function structure for `f_generate_plan_day_tmp` -- ---------------------------- DROP FUNCTION IF EXISTS `f_generate_plan_day_tmp`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `f_generate_plan_day_tmp`(dayCount int) RETURNS int(11) BEGIN DECLARE i int; SET i=0; /** loop_label: LOOP SET i=i+1; IF dayCount>i then INSERT INTO PlanDayTmp(day,orderId) VALUES(i,i); END IF; if i>dayCount then LEAVE loop_label; end if; END LOOP loop_label; */ DELETE FROM dayplantmpresult; -- 删除数据 INSERT INTO dayplantmpresult(day,orderId) SELECT T.day,t.orderId FROM planDayTmp T where t.orderId<dayCount order by RAND() LIMIT 20; return i; END ;; DELIMITER ; -- ---------------------------- -- Function structure for `f_get_post_cardId` -- ---------------------------- DROP FUNCTION IF EXISTS `f_get_post_cardId`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `f_get_post_cardId`(`money` int,`userId` int) RETURNS int(11) BEGIN #Routine body goes here... DECLARE v_post_cardId int; SET v_post_cardId = 0; SELECT P.ID into v_post_cardId FROM POSTCARD P WHERE P.CREATEBY=userId AND P.MINMONEY<money AND P.MAXMONEY>=money ORDER BY RAND() LIMIT 1 ; return v_post_cardId; END ;; DELIMITER ; <file_sep>package com.lj.app.cardmanage.user.service; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.service.BaseServiceImpl; @Service("userService") public class UserServiceImpl<User> extends BaseServiceImpl<User> implements UserService<User>{ } <file_sep>package com.lj.app.cardmanage.creditcard.model; import com.lj.app.cardmanage.base.model.BaseModel; public class CreditCard extends BaseModel{ private int id; private String cardNo; private String bankNo; private String userName; private float maxLimit;//额度 private String secNo;//安全码 private String validateDate;//有效期 private int billDate;//账单日期 private int repaymentDate;//还款日 private float serviceRate;//服务费率 private float initRemainMoney;//初始剩余金额 private String cardNoProfile;//自定义编号 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getBankNo() { return bankNo; } public void setBankNo(String bankNo) { this.bankNo = bankNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public float getMaxLimit() { return maxLimit; } public void setMaxLimit(float maxLimit) { this.maxLimit = maxLimit; } public String getSecNo() { return secNo; } public void setSecNo(String secNo) { this.secNo = secNo; } public String getValidateDate() { return validateDate; } public void setValidateDate(String validateDate) { this.validateDate = validateDate; } public int getBillDate() { return billDate; } public void setBillDate(int billDate) { this.billDate = billDate; } public int getRepaymentDate() { return repaymentDate; } public void setRepaymentDate(int repaymentDate) { this.repaymentDate = repaymentDate; } public float getServiceRate() { return serviceRate; } public void setServiceRate(float serviceRate) { this.serviceRate = serviceRate; } public float getInitRemainMoney() { return initRemainMoney; } public void setInitRemainMoney(float initRemainMoney) { this.initRemainMoney = initRemainMoney; } public String getCardNoProfile() { return cardNoProfile; } public void setCardNoProfile(String cardNoProfile) { this.cardNoProfile = cardNoProfile; } } <file_sep>// JavaScript Document var contral_4A_dialog= function(){ //首页锁屏 function indexLockPing(){ $("#TopMenu .indexLockPing").click(function(){ $('#indexLockPing').dialog('open'); return false; }); $('#indexLockPing').dialog({ autoOpen: false, bgiframe:true, title:"锁定屏幕", modal:true, position:"center", width:400, height:200, buttons:{ "登录":function(){ $("#indexLockPing").dialog("close");//关闭dialog } } }); } return{ indexLockPing:indexLockPing } }();<file_sep>package com.lj.app.core.common.util; import com.lj.app.cardmanage.user.model.UserSetUpFixtureAcceptanceTest; public class SetupContextUtil extends AbstractAcceptanceTestBaseTestCase{ private static UserSetUpFixtureAcceptanceTest userSetUpFixtureAcceptanceTest; public static void setupContext(){ userSetUpFixtureAcceptanceTest = new UserSetUpFixtureAcceptanceTest(); userSetUpFixtureAcceptanceTest.setUpFixture(); } public static void tearDonwContext(){ System.out.println("Tear down context ......"); } } <file_sep>package com.lj.app.cardmanage.creditcard.web; import java.util.HashMap; import java.util.Map; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.lj.app.cardmanage.creditcard.model.CreditCard; import com.lj.app.cardmanage.creditcard.service.CreditCardService; import com.lj.app.core.common.pagination.PageTool; import com.lj.app.core.common.util.AjaxResult; import com.lj.app.core.common.util.DateUtil; import com.lj.app.core.common.web.AbstractBaseAction; import com.lj.app.core.common.web.Struts2Utils; @Controller @Namespace("/jsp/creditCard") @Results({ @Result(name = AbstractBaseAction.INPUT, location = "/jsp/creditCard/creditCard-input.jsp"), @Result(name = AbstractBaseAction.SAVE, location = "creditCardAction!edit.action",type=AbstractBaseAction.REDIRECT), @Result(name = AbstractBaseAction.LIST, location = "/jsp/creditCard/creditCardList.jsp" ,type=AbstractBaseAction.REDIRECT), }) @SuppressWarnings("unchecked") @Action("creditCardAction") public class CreditCardAction extends AbstractBaseAction<CreditCard> { @Autowired private CreditCardService creditCardService; private CreditCard creditCard; private int id; private String cardNo; private String bankNo; private String userName; private float maxLimit;//额度 private String secNo;//安全码 private String validateDate;//有效期 private int billDate;//账单日期 private int repaymentDate;//还款日 private float serviceRate;//服务费率 private float initRemainMoney;//初始剩余金额 private String cardNoProfile;//自定义编号 private String lockStatus = "0"; @Override public CreditCard getModel() { creditCard = (CreditCard)creditCardService.getInfoByKey(id); return creditCard; } @Override public String list() throws Exception { try { Map condition = new HashMap(); condition.put("cardNo",cardNo); condition.put("userName", userName); condition.put("bankNo", bankNo); condition.put("cardNoProfile", cardNoProfile); condition.put(CREATE_BY, getLoginUserId()); this.creditCardService.findPageList(page, condition); Struts2Utils.renderText(PageTool.pageToJsonJQGrid(this.page),new String[0]); return null; } catch (Exception e) { e.printStackTrace(); throw e; } } @Override public String input() throws Exception { return INPUT; } @Override public String save() throws Exception { boolean isSave = true;//是否保存操作 try{ if (operate != null && operate.equals("edit")) { isSave = false; creditCard = new CreditCard(); creditCard.setId(id); creditCard.setCardNo(cardNo); creditCard.setBankNo(bankNo); creditCard.setUserName(userName); creditCard.setMaxLimit(maxLimit); creditCard.setSecNo(secNo); creditCard.setValidateDate(validateDate); creditCard.setBillDate(billDate); creditCard.setRepaymentDate(repaymentDate); creditCard.setUpdateBy(getLoginUserId()); creditCard.setUpdateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); creditCard.setServiceRate(serviceRate); creditCard.setInitRemainMoney(initRemainMoney); creditCard.setCardNoProfile(cardNoProfile); creditCard.setLockStatus(lockStatus); creditCardService.updateObject(creditCard); returnMessage = UPDATE_SUCCESS; }else{ creditCard = new CreditCard(); creditCard.setId(id); creditCard.setCardNo(cardNo); creditCard.setBankNo(bankNo); creditCard.setUserName(userName); creditCard.setMaxLimit(maxLimit); creditCard.setSecNo(secNo); creditCard.setValidateDate(validateDate); creditCard.setBillDate(billDate); creditCard.setRepaymentDate(repaymentDate); creditCard.setCreateBy(getLoginUserId()); creditCard.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); creditCard.setServiceRate(serviceRate); creditCard.setInitRemainMoney(initRemainMoney); creditCard.setCardNoProfile(cardNoProfile); creditCard.setLockStatus(lockStatus); creditCardService.insertObject(creditCard); returnMessage = CREATE_SUCCESS; } return INPUT; }catch(Exception e){ returnMessage = CREATE_FAILURE; e.printStackTrace(); throw e; }finally{ } } @Override public String delete() throws Exception { return null; } @Override protected void prepareModel() throws Exception { creditCard = (CreditCard)creditCardService.getInfoByKey(id); if(creditCard == null) { creditCard = new CreditCard(); } } public String multidelete() throws Exception { String returnMessage = ""; String[] multideleteTemp; if (multidelete.indexOf(",") > 0) { multideleteTemp = multidelete.split(","); } else{ multideleteTemp = new String[]{multidelete}; } for (int i = 0; i < multideleteTemp.length; i++) { int deleteId = Integer.parseInt(multideleteTemp[i].trim()); try{ // 循环删除 creditCardService.delete(deleteId); }catch(Exception e){ returnMessage = "删除失败"; e.printStackTrace(); throw e; }finally{ } } AjaxResult ar = new AjaxResult(); if (returnMessage.equals("")) { ar.setOpResult(DELETE_SUCCESS);//删除成功! }else{ ar.setOpResult(DELETE_FAILURE); } Struts2Utils.renderJson(ar); return null; } @Override public String getMultidelete() { return multidelete; } @Override public void setMultidelete(String multidelete) { this.multidelete = multidelete; } public CreditCardService getCreditCardService() { return creditCardService; } public void setCreditCardService(CreditCardService creditCardService) { this.creditCardService = creditCardService; } public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard creditCard) { this.creditCard = creditCard; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getBankNo() { return bankNo; } public void setBankNo(String bankNo) { this.bankNo = bankNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public float getMaxLimit() { return maxLimit; } public void setMaxLimit(float maxLimit) { this.maxLimit = maxLimit; } public String getSecNo() { return secNo; } public void setSecNo(String secNo) { this.secNo = secNo; } public String getValidateDate() { return validateDate; } public void setValidateDate(String validateDate) { this.validateDate = validateDate; } public int getBillDate() { return billDate; } public void setBillDate(int billDate) { this.billDate = billDate; } public int getRepaymentDate() { return repaymentDate; } public void setRepaymentDate(int repaymentDate) { this.repaymentDate = repaymentDate; } public float getServiceRate() { return serviceRate; } public void setServiceRate(float serviceRate) { this.serviceRate = serviceRate; } public float getInitRemainMoney() { return initRemainMoney; } public void setInitRemainMoney(float initRemainMoney) { this.initRemainMoney = initRemainMoney; } public String getCardNoProfile() { return cardNoProfile; } public void setCardNoProfile(String cardNoProfile) { this.cardNoProfile = cardNoProfile; } public String getLockStatus() { return lockStatus; } public void setLockStatus(String lockStatus) { this.lockStatus = lockStatus; } } <file_sep>/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50519 Source Host : localhost:3306 Source Database : cardmanage Target Server Type : MYSQL Target Server Version : 50519 File Encoding : 65001 Date: 2016-03-26 10:12:56 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `bulletin` -- ---------------------------- DROP TABLE IF EXISTS `bulletin`; CREATE TABLE `bulletin` ( `bulletinId` int(11) NOT NULL AUTO_INCREMENT, `typeName` varchar(50) DEFAULT NULL COMMENT '类别名称', `levelName` varchar(50) DEFAULT NULL COMMENT '等级名称', `title` varchar(200) DEFAULT NULL COMMENT '标题', `targetTypeName` varchar(200) DEFAULT NULL COMMENT '目标类别名称', `targetName` varchar(2000) DEFAULT NULL COMMENT '目标名称', `isNestedName` varchar(200) DEFAULT NULL COMMENT '是否内部名称', `userId` int(11) DEFAULT NULL COMMENT '账号ID', `state` varchar(20) DEFAULT NULL COMMENT '状态', `effDate` datetime DEFAULT NULL COMMENT '生效日期', `expDate` datetime DEFAULT NULL COMMENT '有效期', `createTime` datetime DEFAULT NULL COMMENT '建创日期', `operator` varchar(50) DEFAULT NULL COMMENT '操作者', `optDate` datetime DEFAULT NULL COMMENT '操作日期', PRIMARY KEY (`bulletinId`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of bulletin -- ---------------------------- INSERT INTO `bulletin` VALUES ('3', '11', '22', '33', '11', '22', '11', '45', '1', '2016-03-26 00:00:00', '2016-03-26 00:00:00', '2016-03-26 09:46:22', 'system', '2016-03-26 09:46:22'); <file_sep>package com.lj.app.core.common.security; /** * 证书组件 * *@version 1.0 */ public abstract class CertificationCoder { } <file_sep>package com.lj.app.core.common.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import com.lj.app.cardmanage.user.model.User; public class SessionUtilTest { @Before public void setUp() { User user = new User(); user.setUserId(0); user.setUserName("system"); SessionUtil.setuser(user); } @Test public void getUserTest() { User user = new User(); user.setUserId(0); user.setUserName("system"); SessionUtil.setuser(user); assertTrue(SessionUtil.getMainAcctId()==0); assertEquals("system",SessionUtil.getUserName()); } @Test public void setuserTest() { User user = new User(); user.setUserId(0); user.setUserName("system"); SessionUtil.setuser(user); assertTrue(SessionUtil.getMainAcctId()==0); assertEquals("system",SessionUtil.getUserName()); } @Test public void getMainAcctIdTest() { assertTrue(SessionUtil.getMainAcctId()==0); } @Test public void getUserNameTest() { assertEquals("system",SessionUtil.getUserName()); } @Test public void getSessionAttributeTest() { assertNotNull(SessionUtil.getSessionAttribute(SessionCode.MAIN_ACCT)); } @Test public void getSessionMapTest() { assertNotNull(SessionUtil.getSessionMap()); assertNotNull(SessionUtil.getSessionMap().containsKey(SessionCode.LOGIN_NAME)); } } <file_sep>package com.lj.app.cardmanage.sysconfig.service; import java.util.Set; import com.lj.app.cardmanage.base.service.BaseService; public interface CMPermissionService<CMPermission> extends BaseService{ /** * 根据domainId查询所有权限对应的URL列表 * @return 权限点对应的URL集合 */ public Set<String> findPermissionUrl(); } <file_sep>package com.lj.app.cardmanage.batch.service; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.service.BaseServiceImpl; import com.lj.app.core.common.util.DateUtil; @Service("batchService") public class BatchServiceImpl<Batch> extends BaseServiceImpl<Batch> implements BatchService<Batch>{ public static final int BATCH_CODE_RANDOM_LENGTH = 8; @Override public String getGenerateBatchCode() { //TODO:修改代码,产生固定长度的编码 return DateUtil.getNowDate(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS).replaceAll(" ", "")+"_"+Math.random()*10000; } @Override public int getMaxBatchId() { int batchId = this.countObject("selectMaxId", null); return batchId; } } <file_sep>jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url.server=jdbc:mysql://localhost:3306/cardmanage?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password= app.basedir=. isFirstLoadExecute=T<file_sep>package com.lj.app.cardmanage.user.web; import org.apache.struts2.StrutsSpringTestCase; import org.junit.Test; import com.opensymphony.xwork2.ActionProxy; public class LoginActionTest extends StrutsSpringTestCase{ private static final String DEFAULT_CONTEXT_LOCATION = "classpath*:spring-base.xml"; private LoginAction loginAction; private ActionProxy proxy; @Override protected String[] getContextLocations() { return new String[] {DEFAULT_CONTEXT_LOCATION}; } @Test public void testLogin() { ActionProxy proxy = null; request.setParameter("param", "test..."); request.setParameter("loginNo", "system"); request.setParameter("pwd", "<PASSWORD>"); proxy=getActionProxy("/loginAction!login.action"); loginAction = (LoginAction)proxy.getAction(); try { loginAction.login(); } catch (Exception e) { e.printStackTrace(); } assertEquals("success", "success"); } } <file_sep>package com.lj.app.core.common.security; import java.util.HashSet; import java.util.Set; @SuppressWarnings("unchecked") public class CMSecurityContext { private Long mainAcctId; private String loginName; private Set<String> urls = new HashSet(); private Set<String> codes = new HashSet(); private String loginTime; public String getLoginTime() { return loginTime; } public void setLoginTime(String loginTime) { this.loginTime = loginTime; } /**是否有url访问权限 * @param requestUrl * @return */ public boolean hasUrlPermission(String requestUrl) { for (String url : urls) { if(requestUrl.indexOf(url) != -1) { return true; } } return false; } /**是否有显示的权限 * @param requestCode * @return */ public boolean hasDisplayPermission(String requestCode) { return codes.contains(requestCode); } public Set<String> getCodes() { return codes; } public void setCodes(Set<String> codes) { this.codes = codes; } public Long getMainAcctId() { return mainAcctId; } public void setMainAcctId(Long mainAcctId) { this.mainAcctId = mainAcctId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public void setUrls(Set<String> urls) { this.urls = urls; } } <file_sep>package com.lj.app.cardmanage.user.web; import java.util.HashMap; import java.util.Map; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.lj.app.cardmanage.user.model.User; import com.lj.app.cardmanage.user.service.UserService; import com.lj.app.core.common.pagination.PageTool; import com.lj.app.core.common.util.AjaxResult; import com.lj.app.core.common.util.DateUtil; import com.lj.app.core.common.util.SessionCode; import com.lj.app.core.common.util.des.DesUtil; import com.lj.app.core.common.web.AbstractBaseAction; import com.lj.app.core.common.web.Struts2Utils; @Controller @Namespace("/jsp/user") @Results({ @Result(name = AbstractBaseAction.INPUT, location = "/jsp/user/user-input.jsp"), @Result(name = AbstractBaseAction.SAVE, location = "userAction!edit.action",type=AbstractBaseAction.REDIRECT), @Result(name = AbstractBaseAction.LIST, location = "/jsp/user/userList.jsp", type=AbstractBaseAction.REDIRECT) }) @Action("userAction") public class UserAction extends AbstractBaseAction<User> { private int userId=-1; private String loginNo; private String pwd; private String userName; private String cardNo; private String address; private String mobile; private String lockStatus; private String enableFlag; private String oldPwd; private String newPwd; @Autowired private UserService userService; private User user; @Override public User getModel() { user = (User)userService.getInfoByKey(userId); return user; } @Override public String list() throws Exception { try { Map condition = new HashMap(); condition.put("userName", userName); condition.put("cardNo", cardNo); condition.put("address", address); condition.put("mobile", mobile); condition.put(CREATE_BY, getLoginUserId()); this.userService.findPageList(page, condition); Struts2Utils.renderText(PageTool.pageToJsonJQGrid(this.page),new String[0]); return null; } catch (Exception e) { e.printStackTrace(); throw e; } } @Override public String input() throws Exception { return INPUT; } @Override public String save() throws Exception { boolean isSave = true;//是否保存操作 try{ if (operate != null && operate.equals("edit")) { isSave = false; User user = new User(); user.setUserId(userId); user.setLoginNo(loginNo); user.setPwd(DesUtil.encrypt(pwd)); user.setUserName(userName); user.setCardNo(cardNo); user.setAddress(address); user.setMobile(mobile); user.setUpdateBy(getLoginUserId()); user.setUpdateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); userService.updateObject(user); returnMessage = UPDATE_SUCCESS; }else{ User user = new User(); user.setUserId(userId); user.setLoginNo(loginNo); user.setPwd(DesUtil.encrypt(pwd)); user.setUserName(userName); user.setCardNo(cardNo); user.setAddress(address); user.setMobile(mobile); user.setCreateBy(getLoginUserId()); user.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); userService.insertObject(user); returnMessage = CREATE_SUCCESS; } return LIST; }catch(Exception e){ returnMessage = CREATE_FAILURE; e.printStackTrace(); throw e; }finally{ } } @Override public String delete() throws Exception { return null; } public String multidelete() throws Exception { String operateResult = null;//操作结果:1失败,0成功 String returnMessage = ""; String[] multideleteTemp; if (multidelete.indexOf(",") > 0) { multideleteTemp = multidelete.split(","); } else{ multideleteTemp = new String[]{multidelete}; } for (int i = 0; i < multideleteTemp.length; i++) { int deleteId = Integer.parseInt(multideleteTemp[i].trim()); try{ // 循环删除 userService.delete(deleteId); }catch(Exception e){ returnMessage = "删除失败"; e.printStackTrace(); throw e; }finally{ } } AjaxResult ar = new AjaxResult(); if (returnMessage.equals("")) { ar.setOpResult("删除成功");//删除成功! }else{ ar.setOpResult(returnMessage); } Struts2Utils.renderJson(ar); return null; } public String updateAcctPwd() throws Exception { AjaxResult ar = new AjaxResult(); try{ User loginUser = (User)Struts2Utils.getSession().getAttribute(SessionCode.MAIN_ACCT); if(!loginUser.getPwd().equals(DesUtil.encrypt(oldPwd))){ ar.setOpResult("对不起!旧密码不正确,请重新输入"); Struts2Utils.renderJson(ar); return null; } if(!pwd.equals(newPwd)){ ar.setOpResult("对不起!输入新密码两次不一致,请重新输入"); Struts2Utils.renderJson(ar); return null; } loginUser.setUserId(getLoginUserId()); loginUser.setPwd(DesUtil.encrypt(pwd)); loginUser.setUpdateBy(getLoginUserId()); loginUser.setUpdateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); userService.updateObject(loginUser); Struts2Utils.getSession().setAttribute(SessionCode.MAIN_ACCT,loginUser); ar.setOpResult(UPDATE_SUCCESS); Struts2Utils.renderJson(ar); }catch(Exception e){ ar.setOpResult(UPDATE_FAILURE); Struts2Utils.renderJson(ar); throw e; } return null; } @Override protected void prepareModel() throws Exception { user = (User)userService.getInfoByKey(userId); } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getLoginNo() { return loginNo; } public void setLoginNo(String loginNo) { this.loginNo = loginNo; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getLockStatus() { return lockStatus; } public void setLockStatus(String lockStatus) { this.lockStatus = lockStatus; } public String getEnableFlag() { return enableFlag; } public void setEnableFlag(String enableFlag) { this.enableFlag = enableFlag; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getOldPwd() { return oldPwd; } public void setOldPwd(String oldPwd) { this.oldPwd = oldPwd; } public String getNewPwd() { return newPwd; } public void setNewPwd(String newPwd) { this.newPwd = newPwd; } } <file_sep>package com.lj.app.core.common.util; import java.util.Arrays; import java.util.List; import java.util.Map; public class HtmlUtil { private static final char[] realChar = { '<', '>', '&', '"' }; private static final String[] htmlString = { "&lt;", "&gt;", "&amp;", "&quot;"}; public static String list2Select(String id ,List list){ //<select></select> StringBuffer sb = new StringBuffer("<select id=\"").append(id == null ? "" : id).append("\">"); for (Object s : list) { sb.append("<option value=\"").append( s ).append("\">").append( s ).append("</option>"); } sb.append("</select>"); return sb.toString(); } public static String array2Select(String id ,String[] array){ return list2Select(id ,Arrays.asList(array)); } public static String getButton(String type ,String value,String attribute){ StringBuffer sb = new StringBuffer(); sb.append("<input type=\"button\" value=\"").append(value == null ? "button" : value).append("\"") .append(attribute == null ? "" : attribute) .append("/>"); return sb.toString() ; } public static String mapList2Select(String selectId ,List<Map> list){ StringBuffer sb = new StringBuffer("<select id=\"").append(selectId == null ? "" : selectId).append("\">"); for( Map map : list){ sb.append("<option value=\"").append( map.get("value") ).append("\">").append( map.get("label")).append("</option>"); } sb.append("</select>"); return sb.toString(); } public static String htmlStringToRealChar(String toChangeStr){ for (int i=0; i<htmlString.length; i++) { toChangeStr = toChangeStr.replace(htmlString[i], String.valueOf(realChar[i])); } return toChangeStr; } public static String realCharToHtmlString(String toChangeStr){ for (int i=0; i<realChar.length; i++) { toChangeStr = toChangeStr.replace(String.valueOf(realChar[i]), htmlString[i]); } return toChangeStr; } } <file_sep>package com.lj.app.cardmanage.base.model; public class BaseModel { private int createBy; private String createDate; private int updateBy; private String updateDate; private String enableFlag="T"; private String lockStatus = "0"; public int getCreateBy() { return createBy; } public void setCreateBy(int createBy) { this.createBy = createBy; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public int getUpdateBy() { return updateBy; } public void setUpdateBy(int updateBy) { this.updateBy = updateBy; } public String getUpdateDate() { return updateDate; } public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } public String getEnableFlag() { return enableFlag; } public void setEnableFlag(String enableFlag) { this.enableFlag = enableFlag; } public String getLockStatus() { return lockStatus; } public void setLockStatus(String lockStatus) { this.lockStatus = lockStatus; } } <file_sep>package com.lj.app.core.common.util; public class AjaxResult{ private String opResult; public String getOpResult() { return opResult; } public void setOpResult(String opResult) { this.opResult = opResult; } }<file_sep>package com.lj.app.cardmanage.postcard.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.lj.app.cardmanage.postcard.model.PostCard; import com.lj.app.core.common.pagination.Page; import com.lj.app.core.common.pagination.PageTool; import com.lj.app.core.common.util.AbstractBaseSpringTransactionTestCase; import com.lj.app.core.common.util.DateUtil; public class PostCardServiceTest extends AbstractBaseSpringTransactionTestCase { @Autowired private PostCardService postCardService; @Test public void findBaseModeListTest() { assertTrue(postCardService.findBaseModeList(null).size()>0); } @Test public void findTest(){ assertNotNull(postCardService.getInfoByKey(1)); } @Test public void pagtnateTest() { Map condition = new HashMap(); Page<PostCard> page = new Page<PostCard>(10); Page<PostCard> pageList = postCardService.findPageList(page, condition); List<PostCard> list = pageList.getResult(); Assert.assertEquals(10, list.size()); String result = PageTool.pageToJsonJQGrid(pageList); System.out.println("result=" +result); } @Test public void insetTest() { PostCard postCard = new PostCard(); postCard.setId(1); postCard.setPostCardNo("USER1_001"); postCard.setManName("商户01"); postCard.setRate(0.38F); postCard.setMinMoney(100); postCard.setMaxMoney(30000); postCard.setTrade("餐饮"); postCard.setBindBank("中国银行"); postCard.setCardNo("C001"); postCard.setUserName("U001"); postCard.setCreateBy(1); postCard.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); postCardService.insertObject(postCard); } @Test public void updateTest() { PostCard postCard = new PostCard(); postCard.setId(1); postCard.setPostCardNo("USER1_001"); postCard.setManName("商户01"); postCard.setRate(0.38F); postCard.setMinMoney(100); postCard.setMaxMoney(30000); postCard.setTrade("餐饮"); postCard.setBindBank("中国银行"); postCard.setCardNo("C001"); postCard.setUserName("U001"); postCard.setUpdateBy(1); postCard.setUpdateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); postCardService.updateObject(postCard); } } <file_sep>git使用记录 git是分布式的代码管理工具,远程的代码管理是基于ssh的,所以要使用远程的git则需要ssh的配置。 github的ssh配置如下: 一 、 设置git的user name和email: $ git config --global user.name "ShichaoXu" $ git config --global user.email "<EMAIL>" 查看git配置 $git config --lis 二、生成SSH密钥过程: 1.查看是否已经有了ssh密钥:cd ~/.ssh 如果没有密钥则不会有此文件夹,有则备份删除 2.生存密钥: $ ssh-keygen -t rsa -C "<EMAIL>" 按3个回车,密码为空这里一般不使用密钥。 [plain] view plain copy print?在CODE上查看代码片派生到我的代码片 Your identification has been saved in /home/tekkub/.ssh/id_rsa. Your public key has been saved in /home/tekkub/.ssh/id_rsa.pub. The key fingerprint is: ……………… 最后得到了两个文件:id_rsa和id_rsa.pub 3.添加 私密钥 到ssh:ssh-add id_rsa 需要之前输入密码(如果有)。 4.在github上添加ssh密钥,这要添加的是“id_rsa.pub”里面的公钥。 打开 http://github.com,登陆xushichao,然后添加ssh。 注意在这里由于直接复制粘帖公钥,可能会导致增加一些字符或者减少些字符,最好用系统工具xclip来做这些事情。 --xclip -selection c id_rsa.pub clip<~/.ssh/id_rsa.pub 5.测试: ssh git@github.com [plain] view plain copy print?在CODE上查看代码片派生到我的代码片 PTY allocation request failed on channel 0 Hi xushichao! You've successfully authenticated, but GitHub does not provide shell access. Connection to github.com closed. 三、 开始使用github 1.获取源码: $ git clone <EMAIL>:username/gitproj.git 2.这样你的机器上就有一个repo了。 3.git于svn所不同的是git是分布式的,没有服务器概念。所有的人的机器上都有一个repo,每次提交都是给自己机器的repo 仓库初始化: 也可一用如下方式创建git 工程: git init 生成快照并存入项目索引: git add file 还有git rm,git mv等等… 项目索引提交: git commit 4.协作编程: 将本地repo于远程的origin的repo合并, 推送本地更新到远程: git push origin master 更新远程更新到本地: git pull origin master 1) 在一个本地工程下 git checkout 到一个新分支之后,对新分支做了些修改之后需要用 git add 增加这些修改,然后再 git commit -m 提交修改。之后才可以 git checkout 到一个新的分支,否则会把checkout到的新分支也给修改。 2) git branch new master 基于master 分支创建一个新的分支 new。当切换到 master 分支后做了些修改并 commit之后, 再 chekcout 到 new 分支,此时用 git merge --squash master.这样可以把 master 分支的修改合并到 new 分支上。 见 《版本控制之道----使用git》 合并分支间的修改一章节。 注意这些密钥要保存好! <file_sep>package com.lj.app.cardmanage.batch.model; import com.lj.app.cardmanage.base.model.BaseModel; public class Batch extends BaseModel{ private int id; private String batchCode; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBatchCode() { return batchCode; } public void setBatchCode(String batchCode) { this.batchCode = batchCode; } } <file_sep>package com.lj.app.core.common.security; /** * BASE64安全编码组件 * * @version 1.0 */ public abstract class Base64Coder { } <file_sep>package com.lj.app.core.common.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class ValidateUtilTest { private ValidateUtil ValidateUtil; @Before public void setUp() { ValidateUtil = new ValidateUtil(); } @Test public void isNotEmptyTest() { assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty("AA")); assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty("A A")); assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(" B B")); assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(" ")); assertFalse(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(null)); } @Test public void isEmptyTest() { assertFalse(com.lj.app.core.common.util.ValidateUtil.isNotEmpty("AA")); assertFalse(com.lj.app.core.common.util.ValidateUtil.isNotEmpty("A A")); assertFalse(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(" B B")); assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(" ")); assertTrue(com.lj.app.core.common.util.ValidateUtil.isNotEmpty(null)); } } <file_sep>package com.lj.app.cardmanage.plan.web; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.lj.app.cardmanage.plan.model.Plan; import com.lj.app.cardmanage.plan.service.PlanService; import com.lj.app.cardmanage.postcard.model.PostCard; import com.lj.app.cardmanage.postcard.service.PostCardService; import com.lj.app.core.common.pagination.PageTool; import com.lj.app.core.common.util.AjaxResult; import com.lj.app.core.common.util.DateUtil; import com.lj.app.core.common.util.ExcelUtil; import com.lj.app.core.common.web.AbstractBaseAction; import com.lj.app.core.common.web.Struts2Utils; @Controller @Namespace("/jsp/plan") @Results({ @Result(name = AbstractBaseAction.INPUT, location = "/jsp/plan/plan-input.jsp"), @Result(name = AbstractBaseAction.SAVE, location = "planAction!edit.action",type=AbstractBaseAction.REDIRECT), @Result(name = AbstractBaseAction.LIST, location = "/jsp/plan/planList.jsp",type=AbstractBaseAction.REDIRECT) }) @SuppressWarnings("unchecked") @Action("planAction") public class PlanAction extends AbstractBaseAction<Plan> { private int id=-1; private String lockStatus; private String enableFlag; private String userName; private String cardNo; private String saleDate; private String saleDateStratParam; private String saleDateEndParam; private String postCardNo; private int inMoney; private int outMoney; private int remainMoney; private String cardNoProfile;//自定义编号 /** * post机编号 */ private int postCardId; /** * 服务费率统计 */ private String serviceRateSumFormat; /** * 手续费统计 */ private String poundageSumFormat; /** * 收益金额统计 */ private String incomeMoneySumFormat; @Autowired private PlanService planService; private Plan plan; private List<PostCard> postCardList; @Autowired private PostCardService postCardService; @Override public Plan getModel() { plan = (Plan)planService.getInfoByKey(id); return plan; } @Override public String list() throws Exception { try { Map condition = new HashMap(); condition.put("userName", userName); condition.put("cardNo", cardNo); condition.put("cardNoProfile", cardNoProfile); condition.put("saleDateStratParam", saleDateStratParam); condition.put("saleDateEndParam", saleDateEndParam); condition.put("postCardNo", postCardNo); condition.put(CREATE_BY, getLoginUserId()); this.planService.findPageList(page, condition); Struts2Utils.renderText(PageTool.pageToJsonJQGrid(this.page),new String[0]); return null; } catch (Exception e) { e.printStackTrace(); throw e; } } @Override public String input() throws Exception { return INPUT; } @Override public String save() throws Exception { boolean isSave = true;//是否保存操作 try{ //TODO:FIXME 修改代码,实现计划管理功能 if (operate != null && operate.equals("edit")) { isSave = false; Plan plan = new Plan(); plan.setId(id); plan.setInMoney(inMoney); plan.setOutMoney(outMoney); plan.setRemainMoney(remainMoney); plan.setPostCardId(postCardId); plan.setUpdateBy(getLoginUserId()); plan.setUpdateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); planService.updatePlan(plan, id); returnMessage = UPDATE_SUCCESS; }else{ Plan plan = new Plan(); plan.setId(id); plan.setInMoney(inMoney); plan.setOutMoney(outMoney); plan.setRemainMoney(remainMoney); plan.setCreateBy(getLoginUserId()); plan.setCreateDate(DateUtil.getNowDateYYYYMMddHHMMSS()); planService.insertObject(plan); returnMessage = CREATE_SUCCESS; } return INPUT; }catch(Exception e){ returnMessage = CREATE_FAILURE; e.printStackTrace(); throw e; }finally{ } } @Override public String delete() throws Exception { return null; } public String multidelete() throws Exception { String operateResult = null;//操作结果:1失败,0成功 String returnMessage = ""; String[] multideleteTemp; if (multidelete.indexOf(",") > 0) { multideleteTemp = multidelete.split(","); } else{ multideleteTemp = new String[]{multidelete}; } for (int i = 0; i < multideleteTemp.length; i++) { int deleteId = Integer.parseInt(multideleteTemp[i].trim()); try{ // 循环删除 planService.delete(deleteId); }catch(Exception e){ returnMessage = "删除失败"; e.printStackTrace(); throw e; }finally{ } } AjaxResult ar = new AjaxResult(); if (returnMessage.equals("")) { ar.setOpResult("删除成功");//删除成功! }else{ ar.setOpResult(returnMessage); } Struts2Utils.renderJson(ar); return null; } public String multiExecute() throws Exception { String operateResult = null;//操作结果:1失败,0成功 String returnMessage = ""; String[] multideleteTemp; if (multidExecute.indexOf(",") > 0) { multideleteTemp = multidExecute.split(","); } else{ multideleteTemp = new String[]{multidExecute}; } for (int i = 0; i < multideleteTemp.length; i++) { int multidExecuteId = Integer.parseInt(multideleteTemp[i].trim()); try{ Plan p = new Plan(); p.setId(multidExecuteId); p.setExcuteFlag("T"); planService.updateObject("updateExecuteState",p); }catch(Exception e){ returnMessage = "执行失败"; e.printStackTrace(); throw e; }finally{ } } AjaxResult ar = new AjaxResult(); if (returnMessage.equals("")) { ar.setOpResult("执行成功"); }else{ ar.setOpResult(returnMessage); } Struts2Utils.renderJson(ar); return null; } public String exportExcel() throws Exception{ ExcelUtil excel=new ExcelUtil(); Map condition = new HashMap(); condition.put("userName", java.net.URLDecoder.decode(userName, "UTF-8")); condition.put("cardNo", cardNo); condition.put("cardNoProfile", cardNoProfile); condition.put("saleDateStratParam", saleDateStratParam); condition.put("saleDateEndParam", saleDateEndParam); condition.put("postCardNo", java.net.URLDecoder.decode(postCardNo, "UTF-8")); condition.put(CREATE_BY, getLoginUserId()); List<Object> li=planService.queryForList("exportExcel",condition); String[] Title={"编号","信用卡卡号","银行","消费日期","总金额","还款金额","消费金额","剩余金额","用户名","机具编号","商户名","费率","账单日","还款日","服务费","手续费","收益","执行"}; ExcelUtil.exportExcel("计划信息.xls",Title, li); return null; } public String exportSumExcel() throws Exception{ ExcelUtil excel=new ExcelUtil(); Map condition = new HashMap(); condition.put("userName", java.net.URLDecoder.decode(userName, "UTF-8")); condition.put("cardNo", cardNo); condition.put("cardNoProfile", cardNoProfile); condition.put("saleDateStratParam", saleDateStratParam); condition.put("saleDateEndParam", saleDateEndParam); condition.put("postCardNo", java.net.URLDecoder.decode(postCardNo, "UTF-8")); condition.put(CREATE_BY, getLoginUserId()); List<Object> li=planService.queryForList("exportSumExcel",condition); String[] Title={"商铺名字","法人名字","刷卡金额","刷卡费率","到账金额","手续费"}; ExcelUtil.exportExcel("计划统计信息.xls",Title, li); return null; } public String sumCalc() throws Exception{ String operateResult = null;//操作结果:1失败,0成功 String returnMessage = ""; AjaxResult ar = new AjaxResult(); Map condition = new HashMap(); condition.put("userName", java.net.URLDecoder.decode(userName, "UTF-8")); condition.put("cardNo", cardNo); condition.put("cardNoProfile", cardNoProfile); condition.put("saleDateStratParam", saleDateStratParam); condition.put("saleDateEndParam", saleDateEndParam); condition.put("postCardNo", java.net.URLDecoder.decode(postCardNo, "UTF-8")); condition.put(CREATE_BY, getLoginUserId()); List<Plan> planCalcList = this.planService.queryForList("planCalc", condition); if(planCalcList!=null&&planCalcList.size()>0){ Plan planCalc = planCalcList.get(0); String inMoneySumFormat = planCalc.getInMoneySumFormat(); String outMoneySumFormat = planCalc.getOutMoneySumFormat(); returnMessage="还款总金额:"+inMoneySumFormat+"<br/> 消费总金额:"+outMoneySumFormat+"<br/> 服务费总计:" + planCalc.getServiceRateSumFormat() + "<br/> 手续费总计:"+planCalc.getPoundageSumFormat()+ "<br/> 收益总计:"+planCalc.getIncomeMoneySumFormat()+"<br/>"; } if (!returnMessage.equals("")) { ar.setOpResult(returnMessage); }else{ returnMessage="服务费总计:0,手续费总计:0,收益总计:0"; ar.setOpResult(returnMessage); } Struts2Utils.renderJson(ar); return null; } @Override protected void prepareModel() throws Exception { plan = (Plan)planService.getInfoByKey(id); Map<String,Object> filterMap = new HashMap<String,Object>(); filterMap.put("createBy", this.getLoginUserId()); filterMap.put("lockStatus", "0"); postCardList = postCardService.queryForList("select",filterMap); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLockStatus() { return lockStatus; } public void setLockStatus(String lockStatus) { this.lockStatus = lockStatus; } public String getEnableFlag() { return enableFlag; } public void setEnableFlag(String enableFlag) { this.enableFlag = enableFlag; } public PlanService getPlanService() { return planService; } public void setPlanService(PlanService planService) { this.planService = planService; } public Plan getPlan() { return plan; } public void setPlan(Plan plan) { this.plan = plan; } public int getInMoney() { return inMoney; } public void setInMoney(int inMoney) { this.inMoney = inMoney; } public int getOutMoney() { return outMoney; } public void setOutMoney(int outMoney) { this.outMoney = outMoney; } public int getRemainMoney() { return remainMoney; } public void setRemainMoney(int remainMoney) { this.remainMoney = remainMoney; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getSaleDate() { return saleDate; } public void setSaleDate(String saleDate) { this.saleDate = saleDate; } public String getSaleDateStratParam() { return saleDateStratParam; } public void setSaleDateStratParam(String saleDateStratParam) { this.saleDateStratParam = saleDateStratParam; } public String getSaleDateEndParam() { return saleDateEndParam; } public void setSaleDateEndParam(String saleDateEndParam) { this.saleDateEndParam = saleDateEndParam; } public String getServiceRateSumFormat() { return serviceRateSumFormat; } public void setServiceRateSumFormat(String serviceRateSumFormat) { this.serviceRateSumFormat = serviceRateSumFormat; } public String getPoundageSumFormat() { return poundageSumFormat; } public void setPoundageSumFormat(String poundageSumFormat) { this.poundageSumFormat = poundageSumFormat; } public String getIncomeMoneySumFormat() { return incomeMoneySumFormat; } public void setIncomeMoneySumFormat(String incomeMoneySumFormat) { this.incomeMoneySumFormat = incomeMoneySumFormat; } public String getCardNoProfile() { return cardNoProfile; } public void setCardNoProfile(String cardNoProfile) { this.cardNoProfile = cardNoProfile; } public String getPostCardNo() { return postCardNo; } public void setPostCardNo(String postCardNo) { this.postCardNo = postCardNo; } public List<PostCard> getPostCardList() { return postCardList; } public void setPostCardList(List<PostCard> postCardList) { this.postCardList = postCardList; } public PostCardService getPostCardService() { return postCardService; } public void setPostCardService(PostCardService postCardService) { this.postCardService = postCardService; } public int getPostCardId() { return postCardId; } public void setPostCardId(int postCardId) { this.postCardId = postCardId; } } <file_sep>package com.lj.app.core.common.tags; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class SecurityTag3 extends TagSupport { private String permissionId; public void setPermissionId(String permissionId) { this.permissionId = permissionId; } private String required; public void setRequired(String required) { this.required = required; } @Override public int doStartTag() throws JspException { return SKIP_BODY; } } <file_sep> 1.环境准备准备, 按照以下工具,配置环境变量,确保maven可以正常运行。 MyEclipse 10. apache-maven-3.2.3 jkd1.6 2.修改数据库配置文件 cardmanage\src\main\resources\env.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url.server=jdbc:mysql://localhost:3306/cardmanage?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=<PASSWORD> 修改数据库和登录帐号和密码。 3.执行数据库脚本 cardmanage\src\main\scripts\cardmanage.sql 4.执行maven命令,打包mvn package 5.将打好的包放在tomcat目录下,启动tomcat. 登录地址:http://localhost:8080/cardmanage/login.jsp 默认用户名:system 默认密码:<PASSWORD> 备注: (1)执行验收测试 mvn -Pfitnesse test http://localhost:8000 mvn -Pfitnesse-integration integration-test http://localhost:8001 (2)验收测试java代码目录: cardmanage\src\acceptancetest\java 验收测试java代码请继承基类AbstractAcceptanceTestBaseTestCase.该基类拥有事物控制功能,验收测试执行完后,数据会自动回滚。 <file_sep>package com.lj.app.core.common.notify.email; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 调用方法: * IEmailSender emailSender = EmailSenderFactory.createEmailSenderImpl(); * boolean isSuccess = emailSender.sendEmail("目标邮箱地址","邮件标题", "邮件正文内容"); * */ public class EmailSenderImpl implements IEmailSender { private static Log logger = LogFactory.getLog(EmailSenderImpl.class); public EmailSenderImpl() { } //FIXME: 修改地址 @Override public boolean sendEmail(String sendTo, String subject, String content) { try { if(sendTo==null||sendTo.equals("")) { logger.warn("======mail address is null,not send mail======"); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } } <file_sep>package com.lj.app.cardmanage.bulletin.model; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.lj.app.cardmanage.base.model.BaseModel; public class Bulletin extends BaseModel{ /** * ID */ private Integer bulletinId; /** * 类别名称 */ private String typeName; /** * 等级名称 */ private String levelName; /** * 标题 */ private String title; /** * 目标类别名称 */ private String targetTypeName; /** * 目标名称 */ private String targetName; /** * 是否内部名称 */ private String isNestedName; /** * 账号ID */ private Integer userId; /** * 状态 */ private String state; /** * 生效日期 */ private java.util.Date effDate; /** * 生效日期Begin */ private String effDateBegin; /** * 生效日期End */ private String effDateEnd; /** * 有效期 */ private java.util.Date expDate; /** * 有效期Begin */ private String expDateBegin; /** * 有效期End */ private String expDateEnd; /** * 建创日期 */ private java.util.Date createTime; /** * 建创日期Begin */ private String createTimeBegin; /** * 建创日期End */ private String createTimeEnd; /** * 操作者 */ private String operator; /** * 操作日期 */ private java.util.Date optDate; /** * 操作日期Begin */ private String optDateBegin; /** * 操作日期End */ private String optDateEnd; public void setBulletinId(Integer value) { this.bulletinId = value; } public Integer getBulletinId() { return this.bulletinId; } public void setTypeName(String value) { this.typeName = value; } public String getTypeName() { return this.typeName; } public void setLevelName(String value) { this.levelName = value; } public String getLevelName() { return this.levelName; } public void setTitle(String value) { this.title = value; } public String getTitle() { return this.title; } public void setTargetTypeName(String value) { this.targetTypeName = value; } public String getTargetTypeName() { return this.targetTypeName; } public void setTargetName(String value) { this.targetName = value; } public String getTargetName() { return this.targetName; } public void setIsNestedName(String value) { this.isNestedName = value; } public String getIsNestedName() { return this.isNestedName; } public void setUserId(Integer value) { this.userId = value; } public Integer getUserId() { return this.userId; } public void setState(String value) { this.state = value; } public String getState() { return this.state; } public void setEffDate(java.util.Date value) { this.effDate = value; } public java.util.Date getEffDate() { return this.effDate; } public void setExpDate(java.util.Date value) { this.expDate = value; } public java.util.Date getExpDate() { return this.expDate; } public void setCreateTime(java.util.Date value) { this.createTime = value; } public java.util.Date getCreateTime() { return this.createTime; } public void setOperator(String value) { this.operator = value; } public String getOperator() { return this.operator; } public void setOptDate(java.util.Date value) { this.optDate = value; } public java.util.Date getOptDate() { return this.optDate; } @Override public String toString() { return new ToStringBuilder(this) .append("BulletinId",getBulletinId()) .append("TypeName",getTypeName()) .append("LevelName",getLevelName()) .append("Title",getTitle()) .append("TargetTypeName",getTargetTypeName()) .append("TargetName",getTargetName()) .append("IsNestedName",getIsNestedName()) .append("UserId",getUserId()) .append("State",getState()) .append("EffDate",getEffDate()) .append("ExpDate",getExpDate()) .append("CreateTime",getCreateTime()) .append("Operator",getOperator()) .append("OptDate",getOptDate()) .toString(); } @Override public int hashCode() { return new HashCodeBuilder() .append(getBulletinId()) .append(getTypeName()) .append(getLevelName()) .append(getTitle()) .append(getTargetTypeName()) .append(getTargetName()) .append(getIsNestedName()) .append(getUserId()) .append(getState()) .append(getEffDate()) .append(getExpDate()) .append(getCreateTime()) .append(getOperator()) .append(getOptDate()) .toHashCode(); } @Override public boolean equals(Object obj) { if(obj instanceof Bulletin == false) return false; if(this == obj) return true; Bulletin other = (Bulletin)obj; return new EqualsBuilder() .append(getBulletinId(),other.getBulletinId()) .append(getTypeName(),other.getTypeName()) .append(getLevelName(),other.getLevelName()) .append(getTitle(),other.getTitle()) .append(getTargetTypeName(),other.getTargetTypeName()) .append(getTargetName(),other.getTargetName()) .append(getIsNestedName(),other.getIsNestedName()) .append(getUserId(),other.getUserId()) .append(getState(),other.getState()) .append(getEffDate(),other.getEffDate()) .append(getExpDate(),other.getExpDate()) .append(getCreateTime(),other.getCreateTime()) .append(getOperator(),other.getOperator()) .append(getOptDate(),other.getOptDate()) .isEquals(); } } <file_sep>package com.lj.app.cardmanage.bulletin.service; import org.springframework.stereotype.Service; import com.lj.app.cardmanage.base.service.BaseServiceImpl; @Service("bulletinService") public class BulletinServiceImpl<Bulletin> extends BaseServiceImpl<Bulletin> implements BulletinService<Bulletin>{ } <file_sep>package com.lj.app.core.common.audit; public final class AuditCode { /** * 系统配置部分 * */ public static final class SysCfg { public static final String createRole = "1-AIUAP-20016";// 增加角色 public static final String updateRole = "1-AIUAP-20017";// 修改角色 public static final String deleteRole = "1-AIUAP-20018";// 删除角色 public static final String queryRole = "1-AIUAP-20019";// 查询角色 /** UapDictionaryNoteadd: 数据字典 增加 */ public static final String UAP_DICTIONARY_NOTE_ADD = "1-AIUAP-20413"; /** UapDictionaryNoteadd: 数据字典 修改 */ public static final String UAP_DICTIONARY_NOTE_MODIFY = "1-AIUAP-20414"; /** UapDictionaryNoteadd: 数据字典 删除 */ public static final String UAP_DICTIONARY_NOTE_DEL = "1-AIUAP-20415"; /** UapDictionaryNoteadd: 数据字典数据 增加 */ public static final String UAP_DICTIONARY_ADD = "1-AIUAP-20416"; /** UapDictionaryNoteadd: 数据字典数据 修改 */ public static final String UAP_DICTIONARY_MODIFY = "1-AIUAP-20417"; /** UapDictionaryNoteadd: 数据字典数据 删除 */ public static final String UAP_DICTIONARY_DEL = "1-AIUAP-20418"; /** UAP_PERMISSION_ADD: 权限菜单 增加 */ public static final String UAP_PERMISSION_ADD = "1-AIUAP-20419"; /** UAP_PERMISSION_MODIFY: 权限菜单 修改 */ public static final String UAP_PERMISSION_MODIFY = "1-AIUAP-20420"; /** UAP_PERMISSION_DEL: 权限菜单 删除 */ public static final String UAP_PERMISSION_DEL = "1-AIUAP-20421"; /** UAP_PERMISSION_CANCEL: 权限菜单 停用 */ public static final String UAP_PERMISSION_CANCEL = "1-AIUAP-20422"; /** UAP_PERMISSION_STAR: 权限菜单 启用 */ public static final String UAP_PERMISSION_STAR = "1-AIUAP-20423"; //弱密码新增 public static final String UAP_WEAK_PWD_ADD = "<PASSWORD>"; //弱密码删除 public static final String UAP_WEAK_PWD_DEL = "<PASSWORD>"; //弱密码批量增加 public static final String UAP_WEAK_PWD_BATCHADD = "<PASSWORD>"; //应急系统禁止登陆组织配置操作 public static final String UAP_EMERGENCY_ORG_CFG = "1-AIUAP-20427"; /** 权限互斥菜单保存 */ } public static final String tokenCreate = "1-<PASSWORD>"; // 认证枢纽token申请 public static final String tokenCheck = "1-<PASSWORD>"; // 认证枢纽token验证 }<file_sep>package com.lj.app.cardmanage.plan.service; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.apache.poi.hssf.record.formula.functions.T; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.lj.app.cardmanage.creditcard.model.CreditCard; import com.lj.app.cardmanage.creditcard.service.CreditCardService; import com.lj.app.core.common.pagination.Page; import com.lj.app.core.common.util.AbstractAcceptanceTestBaseTestCase; public class PlanServiceAcceptanceTest<Plan> extends AbstractAcceptanceTestBaseTestCase{ private String batchNo;//批次编号 private String currentDate;//当前日期 private String currentDateOfDD;//当天日期 private int billDate;//账单日期 private String nextMonthToday;//下个月今天 private String preMonthToday;//上个月今天 private CreditCard creditCard; private int creditCardSize; @Autowired private PlanService planService; @Autowired private CreditCardService creditCardService; protected Page<T> page = new Page<T>(PAGESIZE); public static int PAGESIZE = 500; /** * 用户U10001拥有一张信用卡、一个POST机,并且当天是账单日 */ @Test public void userHasOneCreditCardAndOnePostCardAndCurrentDayIsBillDayTest() { currentDateOfDD = planService.getCurrentDateOfDD(); billDate = planService.getBillDay(currentDateOfDD); creditCard = new CreditCard(); creditCard.setCreateBy(1); creditCardSize = creditCardService.getUserCreditBillDateCount(creditCard); currentDate = planService.getCurrentDate(); nextMonthToday =planService.getNextMonthToday(); if(creditCardSize>0){//检验生成的账单 Map<String,String> condition = new HashMap<String,String>(); condition.put("loginNo", "U10001"); condition.put("userName", "U10001"); condition.put("cardNo", ""); condition.put("currentDate", currentDate); condition.put("nextMonthToday", nextMonthToday); planService.findPageList(page, condition); assertTrue(page.getTotalCount()>=28 && page.getTotalCount()<=31); } } /** * 用户U10001拥有一张信用卡、一个POST机,并且当天不是账单日 */ @Test public void userHasOneCreditCardAndOnePostCardAndCurrentDayIsNotBillDayTest() { currentDateOfDD = planService.getCurrentDateOfDD(); billDate = planService.getBillDay(currentDateOfDD); creditCard = new CreditCard(); creditCard.setCreateBy(1); creditCardSize = creditCardService.getUserCreditBillDateCount(creditCard); currentDate = planService.getCurrentDate(); nextMonthToday =planService.getNextMonthToday(); if(creditCardSize==0){//用户当天没呀账单,检验当天没有生成U10001的计划 Map<String,String> condition = new HashMap<String,String>(); condition.put("loginNo", "U10001"); condition.put("userName", "U10001"); condition.put("cardNo", ""); condition.put("currentDate", currentDate); condition.put("nextMonthToday", nextMonthToday); planService.findPageList(page, condition); assertTrue(page.getTotalCount()==0); } } }
ed17ce176951ca277c4826ad62cfc7af30be0a83
[ "SQL", "JavaScript", "Markdown", "Maven POM", "INI", "Java", "Text" ]
48
Java
975545486/cardmanage
163ed00052fe39331f24a294d97f140be3719064
68946c9dd2bbcbcbd9ad643b3372dc01522d0b38
refs/heads/master
<repo_name>C-Vane/name-generator<file_sep>/src/services/generateRandomNames.ts function generateRandomNames(names: Array<String>): Array<String> { let lengthOfAllNames:number=names.length if (lengthOfAllNames<=0) return [] if(lengthOfAllNames<=5)return names let LIST_LENGTH:number=5 let result:String[] = new Array(LIST_LENGTH); let taken = new Array(lengthOfAllNames); while (LIST_LENGTH--) { let current = Math.floor(Math.random() * names.length); result[LIST_LENGTH] = names[(current in taken ? taken[current] : current)]; taken[current] = --lengthOfAllNames in taken ? taken[lengthOfAllNames] : lengthOfAllNames; } return result; } export const namesService = { generateRandomNames, }; export interface RandomNamesApi { randomNames: typeof namesService; } <file_sep>/tests/sagas/randomNames.saga.test.ts import { apiName } from "../../src/services"; import { randomNamesSaga } from "../../src/sagas/randomNames.saga"; import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; import * as chai from "chai"; import * as sinon from "sinon"; import { expect } from "chai"; import { recordSaga } from "../utils/recordSaga"; import { NamesActionIds, namesUpdateAction, } from "../../src/actions/names.actions"; import names from "../../src/assets/data/names.json"; chai.use(require("chai-json-schema")); chai.use(require("chai-match")); let sandbox: sinon.SinonSandbox; let store: any; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const initialAction = { type: NamesActionIds.TOGGLE_NAMES, payload: { names: [] } }; describe("toggleRandomNamesSaga", () => { before(() => { sandbox = sinon.createSandbox(); store = mockStore(); }); afterEach(() => { sandbox.restore(); }); it("puts namesUpdateAction", async () => { const listNames: String[] = Array.from(names); const randomNamesGeneratorSpy = sandbox .stub(apiName.randomNames) .generateRandomNames.callsFake((listNames: String[]) => { return listNames; }); const dispatchedActions = await recordSaga( randomNamesSaga, apiName, store.dispatch, initialAction ); expect(randomNamesGeneratorSpy.calledOnceWith()).to.be.true; expect(dispatchedActions).to.deep.include( namesUpdateAction(listNames) ); }); }); <file_sep>/src/actions/names.actions.ts import { BaseAction } from "."; export const NamesActionIds = { UPDATE_NAMES: "UPDATE_RANDOM_NAMES", TOGGLE_NAMES: "TOGGLE_NAMES", }; export const namesUpdateAction: ( names: Array<String> ) => BaseAction = (names) => ({ type: NamesActionIds.UPDATE_NAMES, payload: { names }, }); export const namesToggleAction: ( ) => BaseAction = () => ({ type: NamesActionIds.TOGGLE_NAMES, payload: { }, }); <file_sep>/tests/reducers/names.reducer.test.ts import * as chai from "chai"; import { expect } from "chai"; import { namesUpdateAction } from "../../src/actions/names.actions"; import { namesReducer } from "../../src/reducers/names.reducer"; chai.use(require("chai-json-schema")); chai.use(require("chai-match")); describe("namesReducer", () => { it("returns the initial state on undefined action", () => { expect(namesReducer(undefined, { type: null })).to.eql({ names: [], }); }); describe("UPDATE_RANDOM_NAMES", () => { it("returns array of max five names on array payload", () => { const listNames: String[] = ["Hanna","Luisa","Mac"]; expect( namesReducer( undefined, namesUpdateAction(listNames) ) ).to.eql({ names: listNames, }); }); }); }); <file_sep>/src/sagas/randomNames.saga.ts import { call, put, takeEvery } from "redux-saga/effects"; import { BaseAction } from "../actions"; import { Dispatch } from "redux"; import { RandomNamesApi } from "../services/generateRandomNames"; import { NamesActionIds, namesUpdateAction, } from "../actions/names.actions"; import names from "../assets/data/names.json"; const listOfNames:String[]=names export function* randomNamesSaga( api: RandomNamesApi, dispatch: Dispatch<BaseAction> ) { //@ts-ignore return yield takeEvery(NamesActionIds.TOGGLE_NAMES, (action) => randomNames(api, dispatch, action) ); } function* randomNames( api:RandomNamesApi, dispatch: Dispatch<BaseAction>, action: BaseAction ) { const names: Array<String> = yield call(() => api.randomNames.generateRandomNames( Array.from(listOfNames) as String[]) ); yield put(namesUpdateAction(names)); } <file_sep>/src/sagas/index.ts import { Dispatch } from "redux"; import { all, fork } from "redux-saga/effects"; import {apiAnimation,apiName} from "../services"; import { BaseAction } from "../actions/index"; import { toggleRotationSaga } from "./toggleRotation.saga"; import { randomNamesSaga } from "./randomNames.saga"; // Register all your watchers export const rootSaga = function* root(dispatch: Dispatch<BaseAction>) { yield all([fork(randomNamesSaga,apiName,dispatch),fork(toggleRotationSaga, apiAnimation, dispatch)]); }; <file_sep>/src/reducers/index.ts import { combineReducers } from "redux"; import { AnimationsState, animationsReducer } from "./animations.reducer"; import { NamesState, namesReducer } from "./names.reducer"; export interface AppState { animationsState: AnimationsState; randomNames: NamesState; } export const reducers = combineReducers<AppState>({ animationsState: animationsReducer, randomNames: namesReducer, }); <file_sep>/src/reducers/names.reducer.ts import { BaseAction } from "../actions"; import { NamesActionIds } from "../actions/names.actions"; export interface NamesState { names: Array<String>; } const initialState: NamesState = { names: [], }; export const namesReducer = ( state: NamesState = initialState, action: BaseAction ): NamesState => { switch (action.type) { case NamesActionIds.UPDATE_NAMES: return { ...state, names: action.payload.names }; default: return state; } }; <file_sep>/src/services/index.ts import { AnimationsApi, animationsService } from "./animations"; import { RandomNamesApi ,namesService } from "./generateRandomNames"; export const apiAnimation: AnimationsApi = { animations: animationsService, }; export type ApiAnimation = typeof apiAnimation; export const apiName: RandomNamesApi = { randomNames: namesService, }; export type ApiNames = typeof apiName; <file_sep>/tests/services/generateRandomNames.test.ts import { namesService} from "../../src/services/generateRandomNames"; import * as chai from "chai"; import { expect } from "chai"; chai.use(require("chai-json-schema")); chai.use(require("chai-match")); describe("Random Names Service", () => { it("on given empty array returns empty array", async () => { const expectedFlag = 0; const mockList=[] const resultFlag: String[] = namesService.generateRandomNames(mockList); expect(resultFlag).to.be.length(expectedFlag); }); it("on given array of names less then 5 returns given array", async () => { const expectedFlag = 3; const mockList=["Ringruth","Bridheaks","Scaal"] const resultFlag: String[] = namesService.generateRandomNames(mockList) expect(resultFlag).to.be.length(expectedFlag); }); it("on given array of names returns an array of max 5 random names", async () => { const expectedFlag = 5; const mockList=[ "Ringruth", "Bridheaks", "Scaal", "Ghaels", "Ghov'eds", "Xarkriex", "Ielphi", "Bhun'id", "Eil'e", "Dhengex", "Throqaids", "Bax'oi"] const resultFlag: String[] = namesService.generateRandomNames(mockList); expect(resultFlag).to.be.length(expectedFlag).lessThanOrEqual; }); }); <file_sep>/README.md # React Developer Skill Challenge We have a small web application that mirrors the architecture of our life page that you can view at (https://synergyofserra.com). - Fix this React project so it is building without errors using `npm start`. - When the project is running again, implement the following User Story. - Your new Services, Sagas and Reducers should be covered with sufficient test cases. ## As a user, I want to generate random names in the application that are presented to me. ### DODs: - I can see a "Generate Names"-Button in a new block next to the "Logo Rotation"-Block. - When I click the "Generate Names"-Button I'm presented with 5 random names (that come from the file `src/assets/data/names.json`). Complexity: 6h
a54c7168f91fbe93ad4617e3ec4b5398361dd899
[ "Markdown", "TypeScript" ]
11
TypeScript
C-Vane/name-generator
bb4bca716a2feca7a93c3a15bf1ba22cc6a1ef9c
7447c3e21cc27a824be2762dea14f4e89618598d
refs/heads/main
<file_sep>package com.hscastro.consumers; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.eclipse.microprofile.rest.client.inject.RestClient; @Path("mp-restclient") @ApplicationScoped public class MPRestClientResource { @Inject @RestClient private MunicipioService service; @GET public String adicinarComGet() { Integer idUF = 38; return service.adicionar(idUF, new MunicipioDTO(null, "Mossoro", 180025)).toString(); } } <file_sep>package com.hscastro.resources; import java.util.Optional; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.config.spi.ConfigSource; @Path("/mp-config") @ApplicationScoped public class MPConfigResource { @Inject private Config config; @Inject @ConfigProperty(name="quantidade.elementos.pagina", defaultValue = "38") Integer quantidadeElementosPagina; @Inject @ConfigProperty(name="quantidade.elementos.pagina") Optional<Integer> quantidadeElementosPaginaOp; @GET @Path("quantidades") @Produces(MediaType.TEXT_PLAIN) public String quantidade() { return quantidadeElementosPagina.toString(); } @GET @Path("/config-sources") @Produces(MediaType.TEXT_PLAIN) public String methodName() { config = ConfigProvider.getConfig(); Iterable<ConfigSource> configSources = config.getConfigSources(); StringBuilder sb = new StringBuilder(); for (ConfigSource configSource : configSources) { sb.append("\nNome").append(configSource.getName()) .append("\nOdinal").append(configSource.getOrdinal()) .append("\nPropertyName").append(configSource.getProperties()); } return sb.toString(); } } <file_sep>package com.hscastro.consumers; import java.net.http.HttpHeaders; import java.util.concurrent.atomic.AtomicInteger; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; @Path("/municipios") @ApplicationScoped @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class MunicipioResource { private AtomicInteger geradorID = new AtomicInteger(); @POST public MunicipioDTO adicionar(@Context HttpHeaders headers, @QueryParam("idUF")Integer idUF, MunicipioDTO municipio) { System.out.println("------------------------------------"); System.out.println("Adicionando municipio"); municipio.setId(geradorID.getAndIncrement()); return municipio; } } // curl -d '{"nome":"Fortaleza", "populacao":"8700874"}' -H "Content-Type: application/json" -H "Accept: application/json" http://192.168.40.179:9080/microprofile-demo/municipios -v <file_sep>quantidade.elementos.pagina=320 correios/mp-rest/uri=http://192.168.40.179:9080/microprofile-demo/
40f7730107f554ca537b3b979c2565a4bc81699a
[ "Java", "INI" ]
4
Java
hscastro/microprofile-demo
4c489ac42dec78c013ebdbaf260e1597e1a666bf
b1d0023577f5b3b86edf4f4a93ac660986b8aabd
refs/heads/master
<repo_name>yrogovich/lordprint<file_sep>/build/libs/send.php <? $to = ''; //Почта получателя, через запятую можно указать сколько угодно адресов $subject = 'Заявка с сайта '.$_SERVER['SERVER_NAME'];; //Заголовок сообщения $message = ' <html> <head> <title>'.$subject.'</title> </head> <body>'; if(isset($_POST['user_name']) && $_POST['user_name'] !== '') $message .= '<p>Имя: '.$_POST['user_name'].'</p>'; if(isset($_POST['user_phone']) && $_POST['user_phone'] !== '') $message .= '<p>Телефон: '.$_POST['user_phone'].'</p>'; if(isset($_POST['checkbox']) && $_POST['checkbox'] !== '') { $checkboxArr = $_POST['checkbox']; foreach ($checkboxArr as $value) { $message .= '<p>Checkbox: '.$value.'</p>'; } } if(isset($_POST['textarea']) && $_POST['textarea'] !== '') { $textareaArr = $_POST['textarea']; foreach ($textareaArr as $value) { $message .= '<p>Checkbox: '.$value.'</p>'; } } $message .= ' </body> </html>'; //Текст нащего сообщения можно использовать HTML теги $headers = "Content-type: text/html; charset=utf-8 \r\n"; //Кодировка письма $headers .= "From: form@".$_SERVER['SERVER_NAME']."\r\n"; //Наименование и почта отправителя mail($to, $subject, $message, $headers); //Отправка письма с помощью функции mail <file_sep>/README.md # Landing page with quiz Build - https://yrogovich.github.io/lordprint/build <file_sep>/build/js/main.js $(document).ready(function() { $('.lazy').Lazy(); $('.left-side').css("background-image", "url(img/quiz/img-1.jpg)"); $('#checkbox-6').on('input', textareaFocus); $('#checkbox-9').on('input', textareaFocus); function textareaFocus() { if($(this).prop('checked')){ $("textarea").prop('disabled', false).focus(); console.log(2); return false; } console.log(1); $("textarea").prop('disabled', true); }; var i = 1; $( ".fieldset input:checkbox" ).on('input', function () { if($( ".fieldset:eq("+(i-1)+") input:checkbox:checked" ).length) { $('.next').prop('disabled', false); return false; } $('.next').prop('disabled', true); }); $('.next').click(function () { i++; $(this).parent('.fieldset').hide(); $(this).parent('.fieldset').next('.fieldset').css({opacity: 0, display: 'flex'}).animate({ opacity: 1 }, 300); $('.left-side').css("background-image", "url(img/quiz/img-" + i +".jpg"); $('.left-side').children('img').attr("src","img/quiz/steps/step-" + i + ".png"); $('.quiz-progress').children('.step.active').toggleClass("active").next('.step').toggleClass("active"); $('.next').prop('disabled', true); $("textarea").prop('disabled', true); }); $('.modal-1').click(function () { $('#modal-1').modal({ fadeDuration: 300 }); }); //Social parallax var parallax = $('#parallax'); $(window).scroll(function() { var x = $(this).scrollTop(); parallax.css('background-position', '0% ' + parseInt(-x / 50) + 'px'); }); //Script for burger const menuToggle = document.querySelector('.menuToggle'); function addClassFunSix() { this.classList.toggle("clickmenuToggle"); } menuToggle.addEventListener('click', addClassFunSix); $('.menuToggle').click(function () { $(".menu").slideToggle(); }); //Group big listst var $tdm = $('.services-row'); var $max = 5; // Перебераем все .tdm var $i = 0; $tdm.each(function () { $i++; // Получаем все пункты li в .tdm var $item = $(this).find('li'), // С помощью фильтра выбираем все пункты, которые идут после пятого $item_target = $item.filter(function () { return $(this).index() > $max-1; }); // Создаём ссылку, по нажатию на которую будут показываться все пункты var $link = []; $link[$i] = $('<a class="all-list">Развернуть весь список</a>').click(function () { // Показываем скрытые пункты $item_target.slideToggle(); // Переименовываем кнопку if($(this).text() == "Свернуть весь список") { $(this).text("Развернуть весь список"); } else { $(this).text("Свернуть весь список"); $(this).toggleClass("active"); } // Блокируем все последущие действия ссылки return false; }); // Скрываем пункты, которые идут после пятого и добавляем перед шестым пунктом ссылку, с помощью которой покажем скрытые пункты $item_target.hide().eq(0).parent().after($link[$i]); }); $('#to-top').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); // Smooth to top action $(window).scroll(function() { if ($(this).scrollTop() > 100) { $('#to-top').fadeIn('slow'); } else { $('#to-top').fadeOut('slow'); }}); // Smooth the scroll action smoothScroll(); function smoothScroll() { $('a[href*="#"]:not([href="#"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1500); return false; } } }); } });
f04ae747fa56ec8c33aa55851ef4a009b876f5f6
[ "Markdown", "JavaScript", "PHP" ]
3
PHP
yrogovich/lordprint
ba6d73766465d5468dccb124d5b35487b1e8bfc0
22d8c3d8816c50f39247e4fe1f671c41566d2cbe
refs/heads/master
<repo_name>bigcachemoney/aA-Classwork<file_sep>/week9/w9d4/ajax_twitter/frontend/twitter.js const FollowToggle = require("./following_toggle.js"); $(function () { const $buttons = $('.follow-toggle') // debugger; for (let i = 0; i < $buttons.length; i++){ const $button = $($buttons[i]); //need to convert $button[i] from object into an jquery array new FollowToggle($button); } }); // //js goes here :) // var ChatMachine = require("./ChatMachine.js"); // $(function () { // new ChatMachine($('.chat')); // }); <file_sep>/week5/w5d1/W5D1/skeleton/lib/p04_linked_list.rb # Phase 4: Linked List # A linked list is a data structure that consists of a series of nodes. Each node holds # a value and a pointer to the next node (or nil). Given a pointer to the first (or head) # node, you can access any arbitrary node by traversing the nodes in order. # We will be implementing a special type of linked list called a "doubly linked list" - # this means that each node should also hold a pointer to the previous node. Given a # pointer to the last (or tail) node, we can traverse the list in reverse order. # Our LinkedLists will ultimately be used in lieu of arrays for our HashMap buckets. # In order to make the HashMap work, each node in your linked list will need to store # both a key and a value. # The Node class is provided for you. It's up to you to implement the LinkedList. # Making Heads and Tails of LinkedList # There are a few ways to implement LinkedList. You can either start with the head and # tail of your list as nil, or start them off as sentinel nodes. For this project, we # will be using sentinel nodes to avoid unnecessary type checking for nil. # A sentinel node is merely a "dummy" node that does not hold a value. Your LinkedList # should keep track of pointers (read: instance variables) to sentinel nodes for its head # and tail. The head and tail should never be reassigned. # Given these properties of our LinkedList, how might we check if our list is empty? # How might we check if we are at the end of our list? Think about how your linked list # will function as you implement the methods below. # Methods to Implement # Go forth and implement the following methods: # first # empty? # #append(key, val) - Append a new node to the end of the list. # #update(key, val) - Find an existing node by key and update its value. # #get(key) # #include?(key) # #remove(key) # If you are surprised by any spec failures along the way, remember to read both the # RSpec messages and the spec file itself. Does the setup for this test rely on any # methods that you haven’t yet implemented? Be sure not to put on “spec blinders” - # try out the methods you’re writing for yourself to test their behavior, and don’t # let passed or failed specs be your only metric for whether you’ve written the code # you need. # Once you're done with those methods, we're also going to make your linked lists # enumerable. We want them to be just as flexible as arrays. Remember back to when # you wrote Array#my_each, and let's get this thing enumerating. The block passed to # #each will yield to a node. # Once you have #each defined, you can include the Enumerable module into your class. # As long as you have each defined, the Enumerable module gives you map, each_with_index, # select, any? and all of the other enumeration methods for free! (Note: you may wish # to refactor your #update, #get, and #include methods to use your #each method for # cleaner code!) class Node attr_reader :key attr_accessor :val, :next, :prev def initialize(key = nil, val = nil) @key = key @val = val @next = nil @prev = nil end def to_s "#{@key}: #{@val}" end def remove # optional but useful, connects previous link to next link # and removes self from list. end end class LinkedList def initialize end def [](i) each_with_index { |link, j| return link if i == j } nil end def first end def last end def empty? end def get(key) end def include?(key) end def append(key, val) end def update(key, val) end def remove(key) end def each end # uncomment when you have `each` working and `Enumerable` included # def to_s # inject([]) { |acc, link| acc << "[#{link.key}, #{link.val}]" }.join(", ") # end end <file_sep>/week11/w11d2/pokedex2/app/controllers/api/pokemon_controller.rb class Api::PokemonController < ApplicationController def index @pokemon = Pokemon.all render :index end def show @pokemon = Pokemon.find(params[:id]) render :show end private def poke_params params.require(:pokemon).permit(:attack, :defense, :image_url, :name, :poke_type) end end <file_sep>/week3/w3d2/edwin_ray_memory_puzzle/board.rb require_relative "./card.rb" require "byebug" class Board attr_reader :grid, :size def initialize(size=4) @size = size if size.even? @grid = Array.new(size) {Array.new(size, " ")} else raise 'size cannot be an odd number' end @populate_num = (size*size) / 2 end def [](pos) # x, y = pos @grid[x][y] end def []=(pos, ele) x, y = pos @grid[x][y] = ele end def populate card_array = [] @populate_num.times do card_array << Card.create_pair end # debugger card_array.flatten! card_array.shuffle! #array.shuffle. iterate through array, add ele #pop(ele) and add pop(ele) into @grid @grid.each_with_index do |sub_arr, idx1| sub_arr.each_with_index do |ele, idx2| @grid[idx1][idx2] = card_array.pop #popping #<Card:0x00007ffb4451cab0 @face_up=false, @name="E"> #grid[x][y] = #<Card:0x00007ffb4451cab0 @face_up=false, @name="E"> end end #get elements into a random position [x][y] #check if position is nil before assigning end def render render_arr = [] @grid.each do |sub_arr| render_arr << sub_arr.map { |card| card.to_s } end top_arr = [" "] top_arr << (0...size).to_a top_arr.flatten! puts "#{top_arr.join(" ")}" (0...@grid.length).each do |i| puts "#{i} #{render_arr[i].join(" ")}" end # 0 1 2 3 # 0 N N N N # 1 N N N N # 2 N N N N # 3 N N N N end def won? #should return true if all cards have been revealed. win_arr = [] @grid.each do |sub_arr| win_arr << sub_arr.map { |card| card.to_s } end win_arr.each do |row| row.any? {|ele| return false if ele == " "} end true end ###reveal #should reveal a Card at guessed_pos (unless it's already face-up, in which case the method should do nothing). It should also return the value of the card it revealed. def reveal(pos) #pos = [2,3] @grid[pos[0]][pos[1]].reveal self.render card_letter = @grid[pos[0]][pos[1]].name return card_letter #"U" end end <file_sep>/week3/w3d1/Ghost/ghost/game.rb require_relative "./player.rb" class Game @@dictionary = File.new("dictionary.txt").readlines.map(&:chomp).to_set def initialize(player1, player2) @fragment = "" @player1 = Player.new(player1) @player2 = Player.new(player2) @current_player = @player1 @previous_player = @player2 end def play_round round_is_over = false until round_is_over do round_is_over = !(take_turn(@current_player)) || round_over?(@fragment) next_player! end puts "#{@current_player.name} wins!" @previous_player end def next_player! @current_player, @previous_player = @previous_player, @current_player end def take_turn(player) guess = player.guess if valid_play?(guess) @fragment << guess true else false end end def valid_play?(guess) ("a".."z").include?(guess) && @@dictionary.any? {|word| word[0..@fragment.length] == @fragment + guess} end def round_over?(word) @@dictionary.include?(word) end def run until game_over? loser = play_round loser.loses! @fragment = "" puts "#{loser.name} loses the round!" puts "#{@player1.name}'s score is #{"GHOST"[0...@player1.losses]}, #{@player2.name}'s score is #{"GHOST"[0...@player2.losses]}" end loser = @player1.losses == 5 ? @player1 : @player2 puts "#{loser.name} loses the game!" end def game_over? @player1.losses == 5 || @player2.losses == 5 end end<file_sep>/week6/w6d4/ray_lynn_artshare_project/db/migrate/20201008193037_create_artworks.rb class CreateArtworks < ActiveRecord::Migration[5.2] def change create_table :artworks do |t| t.string :title, null: false t.string :image_url, null: false t.integer :artist_id, null: false end # add_index :user_views, [:article_id, :user_id] add_index :artworks, [:artist_id, :title] #which comes first? end end <file_sep>/week3/w3d1/Ghost/ghost/player.rb class Player attr_reader :name, :losses def initialize(name) @name = name @losses = 0 end def guess puts "#{name} please enter a letter:" gets.chomp end def loses! @losses += 1 end end<file_sep>/week8/w8d4/js_reversi/lib/board.js let Piece = require("./piece"); /** * Returns a 2D array (8 by 8) with two black pieces at [3, 4] and [4, 3] * and two white pieces at [3, 3] and [4, 4] */ function _makeGrid () { let grid = Array(8).fill().map(() => Array(8)); // Output: [ [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ], , [ <5 empty items> ] ] // grid = [ // [1, 2, 3, 4, 5, 6, 7, 8], // [1, 2, 3, 4, 5, 6, 7, 8], // [1, 2, W, W, 5, 6, 7, 8], // [1, 2, 3, 4, 5, 6, 7, 8], // [1, 2, B, B, 5, 6, 7, 8], // [1, 2, 3, 4, 5, 6, 7, 8], // [1, 2, 3, 4, 5, 6, 7, 8], // [1, 2, 3, 4, 5, 6, 7, 8], // ] grid[3][4] = new Piece("black"); grid[4][3] = new Piece("black"); grid[3][3] = new Piece("white"); grid[4][4] = new Piece("white"); return grid; } /** * Constructs a Board with a starting grid set up. */ function Board () { this.grid = _makeGrid(); } Board.DIRS = [ [ 0, 1], [ 1, 1], [ 1, 0], [ 1, -1], [ 0, -1], [-1, -1], [-1, 0], [-1, 1] ]; /** * Checks if a given position is on the Board. */ Board.prototype.isValidPos = function (pos) { // 1) should return false when x or y is less than 0 // 2) should return false when x or y is greater than 7 // 3) should return true otherwise let x = pos[0]; let y = pos[1]; return (x >= 0 && x < 8) && (y >= 0 && y < 8); // { // return true; // } // return false; }; /** * Returns the piece at a given [x, y] position, * throwing an Error if the position is invalid. */ Board.prototype.getPiece = function (pos) { // 1) should return a piece for an occupied position // ✓ should return undefined for an empty position // 2) should throw an error for an invalid position let valid = this.isValidPos(pos); //get the item at pos... //if it's a piece return piece //if empty return undefined let x = pos[0]; let y = pos[1]; if (valid === false) { throw new Error('Not valid pos!'); } // if (this.grid[x][y] === undefined) { // return undefined; // } else { return this.grid[x][y]; } }; /** * Checks if the piece at a given position * matches a given color. */ Board.prototype.isMine = function (pos, color) { // 1) should return true when the retrieved piece matches the color // 2) should return false when retrieved piece does not match // ✓ should return falsey when retrieved piece is undefined debugger //i'm asking my circle TA about this rn SAme! lol if (this.getPiece(pos) === undefined){ return false; } if (this.getPiece(pos).color === color){ return true; } else { return false; } }; /** * Checks if a given position has a piece on it. */ Board.prototype.isOccupied = function (pos) { // 1) should return true if there is a piece on a position // 2) should return false if there isn't a piece on a position if (this.getPiece(pos) === undefined){ return false; } else { return true; } }; /** * Recursively follows a direction away from a starting position, adding each * piece of the opposite color until hitting another piece of the current color. * It then returns an array of all pieces between the starting position and * ending position. * * Returns an empty array if it reaches the end of the board before finding another piece * of the same color. * * Returns empty array if it hits an empty position. * * Returns empty array if no pieces of the opposite color are found. */ // 1) returns empty array when pos is not on the board // 2) returns empty array when there is a blank space one position away from the current position // 3) returns empty array if no pieces of the opposite color are found // 4) returns positions for longer horizontal and vertical cases // 5) returns positions for longer diagonal cases Board.prototype._positionsToFlip = function(pos, color, dir, piecesToFlip){ let newPos = [pos[0] + dir[0], pos[1] + dir[1]]; //base case 1 = hit a piece of the same color // debugger if (this.isMine(newPos, color)){ return []; } //base case 2 = hit the edge of the board try { this.isValidPos(newPos); } catch(err){ return []; } // if (!this.isValidPos(newPos)){ // // debugger // return []; // } //spec 2 if (!this.isOccupied(newPos)){ // debugger return []; } if (!this.isMine(newPos, color)){ //if opponent's color // piecesToFlip.push(this.getPiece(newPos)); // debugger let arr = piecesToFlip.concat(this._positionsToFlip(newPos, color, dir, piecesToFlip)); return arr; } }; /** * Checks that a position is not already occupied and that the color * taking the position will result in some pieces of the opposite * color being flipped. */ Board.prototype.validMove = function (pos, color) { }; /** * Adds a new piece of the given color to the given position, flipping the * color of any pieces that are eligible for flipping. * * Throws an error if the position represents an invalid move. */ Board.prototype.placePiece = function (pos, color) { }; /** * Produces an array of all valid positions on * the Board for a given color. */ Board.prototype.validMoves = function (color) { }; /** * Checks if there are any valid moves for the given color. */ Board.prototype.hasMove = function (color) { }; /** * Checks if both the white player and * the black player are out of moves. */ Board.prototype.isOver = function () { }; /** * Prints a string representation of the Board to the console. */ Board.prototype.print = function () { }; module.exports = Board; <file_sep>/week9/w9d1/project_exercise/prototype_inheritance.js Function.prototype.inherits = function(Parent) { function Surrogate() {}; Surrogate.prototype = Parent.prototype; this.prototype = new Surrogate(); //this = child this.prototype.constructor = this; }; Function.prototype.inherits = function(Parent) { this.prototype = Object.create(Parent.prototype); this.prototype.constructor = this; }; function MovingObject() { } MovingObject.prototype.moves = function (){ console.log("i am moving"); } function Ship() { } Ship.inherits(MovingObject); Ship.prototype.steer = function (){ console.log("steering"); } function Asteroid() { } Asteroid.inherits(MovingObject); const ship1 = new Ship(); ship1.moves(); ship1.steer(); const movingObject1 = new MovingObject(); movingObject1.moves(); movingObject1.steer();<file_sep>/week2/w2d4/chris_lopez_ray_todo_board/todo_board_phase_1/todo_board.rb require './list.rb' class TodoBoard end <file_sep>/week6/w6d3/first_routes_controllers/app/controllers/users_controller.rb class UsersController < ApplicationController #Note that controllers are always plural def index render plain: "I'm in the index action!" end def create user = User.new(user_params) #params.require(:user).permit(:name, :email) # replace the `user_attributes_here` with the actual attribute keys if user.save render json: user else render json: user.errors.full_message, status: :unprocessable_entity end end #save! will raise an error if not successful. #save will return boolean value like true or false. #example from class # def create # user = User.new(params.require(:user).permit(:user_attributes_here)) # # replace the `user_attributes_here` with the actual attribute keys # user.save! # render json: user # end def show render json: params end def update end # protected # def toy_params # self.params[:toy].permit(:cat_id, :name, :ttype) # end protected def user_params params.require(:user).permit(:name, :email) end end # class DropsController < ApplicationController # def index # # index should get all of a resource and send it to user # drops = Drop.all # render json: drops # end # def show # # debugger # drop = Drop.find(params[:id]) # render json: drop # end # def create # # debugger # drop = Drop.new(drop_params) # # we dont' want to use .save! or .create! because it would throw an error # # we want to decide what happens if the save is successful or not # if drop.save # render json: drop # else # render json: drop.errors.full_messages, status: 422 # end # end # def update # # debugger # drop = Drop.find(params[:id]) # if drop.update(drop_params) # this is using the ActiveRecord update method # redirect_to drop_url(drop) # else # render json: drop.errors.full_messages, status: :unprocessable_entity # end # end # def destroy # # debugger # drop = Drop.find(params[:id]) # drop.destroy # redirect_to drops_url # end # # private # def drop_params # params.require(:drop).permit(:body, :author_id) # # require looks for top level key of `drop` within params # # then only grabs (permits) the keys within drop of body and author_id # end # end<file_sep>/week6/w6d5/ninenine_cats/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Cat.destroy_all garfield = Cat.create!(name: 'Garfield', birth_date: Date.new(2000,1,1), color: "orange", sex: "M", description: "lasagna lover") lomein = Cat.create!(name: 'LoMein', birth_date: Date.new(2010,1,1), color: "black", sex: "F", description: "noodle lover") <file_sep>/week5/w5d3/aa_questions/reply.rb class Reply def self.find_by_id end def initialize @id @question_id @parent_id @user_id @Reply end end<file_sep>/week2/w2d3/ray_battleship_project/lib/board.rb class Board attr_reader :size def initialize(n) @grid = Array.new(n) { Array.new(n, :N) } @size = n * n end def [](position) row, col = position @grid[row][col] end def []=(position, val) row, col = position @grid[row][col] = val end def num_ships count = 0 (0...@grid.length).each do |row| (0...@grid.length).each do |col| count += 1 if @grid[row][col] == :S end end count end def attack(position) if self[position] == :S self[position] = :H puts 'you sunk my battleship!' #DO NOT USE PRINT, we made a custom print method return true else self[position] = :X return false end end def place_random_ships quarter_ships = (@grid.length * @grid.length)/4 while self.num_ships < quarter_ships temp1 = rand(0...@grid.length) temp2 = rand(0...@grid.length) position = [temp1, temp2] self[position] = :S end end def hidden_ships_grid @grid.map do |row| row.map do |ele| if ele == :S :N else ele end end end end def self.print_grid(grid_arr) grid_arr.each do |row| puts row.join(" ") end end def cheat Board.print_grid(@grid) end def print Board.print_grid(self.hidden_ships_grid) end end <file_sep>/week2/w2d3/ray_mastermind_project/lib/code.rb require "byebug" class Code attr_reader :pegs POSSIBLE_PEGS = { "R" => :red, "G" => :green, "B" => :blue, "Y" => :yellow } def self.valid_pegs?(arr) arr.each {|ch| return false if !POSSIBLE_PEGS.has_key?(ch.upcase)} return true end def initialize(arr) @pegs = [] if Code.valid_pegs?(arr) @pegs = arr.map {|ch| ch.upcase} else raise "entered invalid pegs" end end def self.random(num) new_arr = [] num.times {new_arr << POSSIBLE_PEGS.keys.sample} Code.new(new_arr) end def self.from_string(str) Code.new(str.split("")) end def [](idx) return @pegs[idx] end def length return @pegs.length end def num_exact_matches(code) new_pegs = code.pegs count = 0 new_pegs.each_with_index do |peg1, index1| if @pegs[index1] == new_pegs[index1] count += 1 end end return count end def num_near_matches(another_code) #original = RGRB #"B", "R", "Y", "Y" <<<<<<<< #"R", "G", "R", "B" new_pegs = another_code.pegs count = 0 (0...@pegs.length).each do |index1| if @pegs.include?(new_pegs[index1]) && @pegs[index1] != new_pegs[index1] count += 1 end end return count end def ==(another_code) self.pegs == another_code.pegs end end <file_sep>/week2/w2d4/chris_lopez_ray_todo_board/todo_board_phase_2/todo_board.rb require './list.rb' class TodoBoard end TodoBoard.new.run <file_sep>/week2/w2d3/tic_tac_toe/AJ_Ray_tic_tac_toe/game.rb # Game # The Game class will be the main class that houses the instances of Board and HumanPlayer required for gameplay. It will be responsible for passing data between the board and players. It will also serve to contain the main game loop. # Be sure to require your board.rb and human_player.rb files into game.rb. require './board.rb' require './human_player.rb' class Game # Game#initialize(player_1_mark, player_2_mark) # An instance of Game should have instance variables for player one, player two, and the board. Design the #initialize method to accept the mark values to be used for the players. # You should also initialize an instance variable to contain the current player. By default, player one should begin as the current player. # Game#switch_turn # This method should set the current player to the other player. Calling this method repeatedly should switch the current player back and forth between the two players. # Game#play # This method will contain the main game loop. Here is some psuedocode for the loop: # while there exists empty positions on the board # print the board # get a position from the current player # place their mark at that position of the board # check if that user has won # if they win, print out a 'victory' message saying who won and return to end the game # otherwise they did not win, so switch turns # if we finish the while loop without returning, that means there are no more empty positions on the board and noone has won, so print a 'draw' message # Test your game in pry. Play a few games by creating an instance of Game and invoking #play on it. After a game is over, be sure to create a new instance of Game to play again, this is the only way to get a fresh board. Some scenarios to test are: player one winning, player two winning, and a draw. # If any errors are raised during gameplay, your game loop and #play method will end immediately, so you'll have to start a new game and retry! end <file_sep>/week11/w11d1/jbuilder/app/views/api/parties/show.json.jbuilder json.extract! @party, :name, :location, :guests json.array! @guests do |guest| @guest.gift end<file_sep>/week5/w5d1/W5D1/skeleton/lib/p01_int_set.rb # Learning Goals # Be able to describe the characteristics of a good hashing function # Be able to explain how a linked list works and know how to traverse it # Be able to explain how a hash map works # Know how to implement an LRU cache using hash maps and linked lists # Phase 1: IntSet # A Set is a data type that can store unordered, unique items. Sets don't make any promises # regarding insertion order, and they won't store duplicates. In exchange for those constraints, # sets have remarkably fast retrieval time and can quickly look up the presence of values. # Many mathematicians claim that sets are the foundation of mathematics, so basically # we're going to build all of mathematics today. No big deal. # A set is an abstract data type (ADT). An ADT can be thought of as a high-level description # of a structure and an API (i.e., a specific set of methods). Examples of ADTs are things # like sets, maps, or queues. But any given data type or API can be realized through many # different implementations. Those implementations are known as data structures. # Different data structures can implement the same abstract data type, but some data # structures are worse than others. We're going to show you the best implementations, # or close to them. (In reality, there's usually no single best implementation of an ADT; # there are always tradeoffs.) # Sound cool yet? Now let's go build a Set. # MaxIntSet # We'll start with the first stage. In this version of a set, we can only store integers # that live in a predefined range. So I tell you the maximum integer I'll ever want to # store, and you give me a set that can store it and any smaller non-negative number. # Initialize your MaxIntSet with an integer called max to define the range of integers # that we're keeping track of. # Internal structure: # An array called @store, of length max # Each index in the @store will correspond to an item, and the value at that index # will correspond to its presence (either true or false) # e.g., the set { 0, 2, 3 } will be stored as: [true, false, true, true] # The size of the array will remain constant! # The MaxIntSet should raise an error if someone tries to insert, remove, or check # inclusion of a number that is out of bounds. # Methods: # #insert # #remove # #include? # Once you've built this and it works, we'll move on to the next iteration. class MaxIntSet attr_reader :store def initialize(max) @store = Array.new(max, false) end def insert(num) validate!(num) return false if @store[num] @store[num] = true end def remove(num) validate!(num) @store[num] = false if include?(num) end def include?(num) validate!(num) @store[num] end private def is_valid?(num) num.between?(0, @store.length - 1) end def validate!(num) raise "Out of bounds" unless is_valid?(num) end end # IntSet # Now let's see if we can keep track of an arbitrary range of integers. Here's where # it gets interesting. Create a brand new class for this one. We'll still initialize # an array of a fixed length--say, 20. But now, instead of each element being true or # false, they'll each be sub-arrays. # Imagine the set as consisting of 20 buckets (the sub-arrays). When we insert an integer # into this set, we'll pick one of the 20 buckets where that integer will live. That can # be done easily with the modulo operator: i = n % 20. # Using this mapping, which wraps around once every 20 integers, every integer will be # deterministically assigned to a bucket. Using this concept, create your new and improved set. # Initialize an array of size 20, with each containing item being an empty array. # To look up a number in the set, modulo (%) the number by the set's length, and add it to # the array at that index. If the integer is present in that bucket, that's how we know it's # included in the set. # You should fill out the #[] method to easily look up a bucket in the store - calling self[num] # will be more DRY than @store[num % num_buckets] at every step of the way! # Your new set should be able to keep track of an arbitrary range of integers, including # negative integers. Test it out. class IntSet def initialize(num_buckets = 20) @store = Array.new(num_buckets) { Array.new} end def insert(num) self[num] << num unless include?(num) #add if number is not there end def remove(num) self[num].delete(num) if include?(num) #delete if number is present end def include?(num) self[num].include?(num) #the left side would give us the bucket number, #include method is checking to see if num is inside #that bucket end private def [](num) # optional but useful; return the bucket corresponding to `num` @store[num % num_buckets] #bucket number end def num_buckets @store.length end end class ResizingIntSet attr_reader :count def initialize(num_buckets = 20) @store = Array.new(num_buckets) { Array.new } @count = 0 end def insert(num) # store.length > N unless include?(num) self[num] << num @count += 1 end resize! if @count > num_buckets end def remove(num) if include?(num) #delete if number is present self[num].delete(num) @count -= 1 end end def include?(num) self[num].include?(num) end private def [](num) # optional but useful; return the bucket corresponding to `num` @store[num % num_buckets] end def num_buckets @store.length end def resize! #resize -> make a new array #run insert again to move elements into buckets? # have to iterate through every element in our original store (2D array) and re-insert # them into our resized store # insert method increments our count by 1, but since we're reintroducing the same # elements, reset count to 0, the insert method will reincrement our count back to # original count # First step: save elements of our original store into an array elements = @store.flatten # second step: reset count to 0 @count = 0 # Third step: make new resized store @store = Array.new(num_buckets * 2) {Array.new} # fourth step: re insert each element into resized array elements.each {|ele| insert(ele) } end end # ResizingIntSet # The IntSet is okay for small sample sizes. But if the number of elements grows pretty big, # our set's retrieval time depends more and more on an array scan, which is what we're trying # to get away from. It's slow. # Scanning for an item in an array (when you don't know the index) takes O(n) time, because # you potentially have to look at every item. So if we're having to do an array scan on one # of the 20 buckets, that bucket will have on average 1/20th of the overall items. That # gives us an overall time complexity proportional to 0.05n. When you strip out the 0.05 # constant factor, that's still O(n). Meh. # Let's see if we can do better. # Make a new class. This time, let's increase the number of buckets as the size of the set # increases. The goal is to have store.length > N at all times. # You may want to implement an inspect method to make debugging easier. # What are the time complexities of the operations of your set implementation?<file_sep>/week2/w2d3/tic_tac_toe/AJ_Ray_tic_tac_toe/board.rb #The Board class is responsible for adding a player's marks, checking for winners, and printing the game board. A board instance must have an attribute to represent the grid. For simplicity, give the grid the dimensions of classic tic-tac-toe, 3x3. require 'byebug' class Board # Board#initialize # A Board instance must have an instance variable to represent the game grid. For now, Board#initialize does not need to accept any arguments. Initialize the grid so that all positions are empty; this means that every position should contain an underscore ('_'). def initialize @board = Array.new(3) {Array.new(3, "_")} end # Board#valid?(position) # This method should return a boolean indicating whether or not the specified position is valid for the board, meaning the position is not "out of bounds." def valid?(position) #[][] row, col = position if ((row < 4) && (col < 4)) && ((row >= 0) && (col >= 0)) return true end false end # Board#empty?(position) # This method should return a boolean indicating whether or not the specified position does not contain a player's mark. def empty?(position) row, col = position return @board[row][col] == "_" end # Board#place_mark(position, mark) # This method should assign the given mark to the specified position of the grid. It should raise an error when the position is not #valid? or not #empty?. def place_mark(position, mark) row, col = position if self.valid?(position) && self.empty?(position) @board[row][col] = mark else raise "position not valid" end end # Board#print # This method should simply print out the board and all of the marks that have been placed on it. Feel free to style the printing as much as you'd like, but be sure to print out each row of the board on a new line. This will help us visualize the board better as we debug or even play the game! def print @board.each do |row| puts row.join(" ") end end # Board#win_row?(mark) # This method should return a boolean indicating whether or not the given mark has completely filled up any row of the grid. def win_row?(mark) @board.any? do |row| row.all? {|ele| mark == ele} end end # Board#win_col?(mark) # This method should return a boolean indicating whether or not the given mark has completely filled up any column of the grid. def win_col?(mark) @board.transpose.any? do |col| col.all? {|ele| mark == ele} end end # Board#win_diagonal?(mark) # This method should return a boolean indicating whether or not the given mark has completely filled up either diagonal of the grid. #0,0 #1,1 #2,2 #0,2š #2,0 def win_diagonal?(mark) debugger left_to_right = (0...@board.length).all? do |i| pos = i, i @board[pos] == mark end right_to_left = (0...@board.length).all? do |i| row = i col = @board.length - 1 - i pos = row, col #[row, col] @board[pos] == mark end left_to_right || right_to_left end # Board#win?(mark) # This method should return a boolean indicating whether or not the given mark has filled any full row, column, or diagonal. def win?(mark) self.win_diagonal?(mark) || self.win_row?(mark) || self.win_col?(mark) end # Board#empty_positions? # This method should return a boolean indicating whether or not there is at least one empty position on the grid. def empty_positions? @board.any? do |row| row.any? {|ele| ele == "_"} end end end <file_sep>/week9/w9d4/ajax_twitter/frontend/following_toggle.js FollowToggle = function ($button) { //$button -> searches through entire _form.html.erb for $button this.userId = $button.data("user-id"); this.followState = $button.data("initial-follow-state"); this.$button = $button; this.render(); this.$button.click(this.handleClick.bind(this)); } FollowToggle.prototype.render = function (){ // debugger if (this.followState === "Following") { debugger this.$button.text("Unfollow"); // this.$button.prop("disabled", true); } if (this.followState === "Unfollowing") { debugger this.$button.text("Follow"); // this.$button.prop("disabled", true); } // if (this.followState === "Followed") { // // debugger // this.$button.text("Unfollow"); // // this.$button.prop("disabled", false); // } // if (this.followState === "Unfollowed") { // // debugger // this.$button.text("Follow"); // // this.$button.prop("disabled", false); // } } FollowToggle.prototype.handleClick = function(e){ const verb = this.followState === "Following" ? "delete" : "post"; that = this; debugger e.preventDefault(); $.ajax({ method: verb, url: `/users/${this.userId}/follow`, dataType: "json", success : function(){ debugger if (that.followState === "Following"){ debugger that.followState = "Unfollowing"; debugger that.render(); } if (that.followState === "Unfollowing"){ that.followState = "Following"; that.render(); } }, error() { // debugger console.error("An error occurred."); } }); } module.exports = FollowToggle;<file_sep>/week2/w2d4/chris_lopez_ray_todo_board/todo_board_phase_1/list.rb require './item.rb' class List end <file_sep>/week4/w4d5/execution_time_difference.rb require "byebug" #n^2 quadratic #nesting two loops. If our array has n items, our outer loop runs n times and our inner loop runs n times for each iteration of the outer loop, giving us n^2 (or "quadratic time"). #constant * n^2 = n^2 def my_min(list) min = list[0] list.each_with_index do |ele1, idx1| #n times list.each_with_index do |ele2, idx2| #n times min = ele2 if min > ele2 && idx2 > idx1 #constant operation end end min end #n? -ray # -tony # O(n^2). # And the reason for that is that with each we are going over all the characters in the string word. That alone would be a linear time algorithm O(n), but inside the block we have the count method. # This method is effectively another loop which goes over all the characters in the string again to count them. #https://www.rubyguides.com/2018/03/time-complexity-for-ruby-developers/ def my_min_b(list) min = list.first list.each {|ele| min = ele if min > ele} min end # list = [ 0, 3, 5, 4, -5, 10, 1, 90 ] # p my_min_b(list) #n^3 -tony (cubic) #n^3 + n^3 = n^3 #Same as n^2, but time grows in a n^3 relation to input size. Look for a triple nested loop to recognize this one. def largest_contiguous_subsum(array) combinations = [] #n^2 input size (0...array.length - 1).each do |idx1| (idx1...array.length).each do |idx2| combinations << array[idx1..idx2] # O(n) slicing an array requires iteration, creates n^2 amount of subarrays end end max = array.first combinations.each do |combo| #O(n^2) because of input size max = combo.sum if combo.sum > max #summing = O(n) end max end #n????? O(n), O(1) def largest_contiguous_subsum2(array) max = array.first current = array.first i = 1 while i < array.length # current = 0 if current < 0 current += array[i] max = current if current > max i += 1 end max end list = [2, 3, -6, 7, -6, 7] p largest_contiguous_subsum2(list) # => 8 (from [7, -6, 7]) # list = [-5, -1, -3] # p largest_contiguous_subsum2(list) # => -1 (from [-1])<file_sep>/week2/w2d2/jasmine_ray_startup_project/lib/startup.rb require "employee" require 'byebug' class Startup attr_reader :name, :funding, :salaries, :employees def initialize(name, funding, salaries) @name = name @funding = funding @salaries = salaries #'title` => `salary' @employees = [] end def valid_title?(title) @salaries.each {|k, v| return true if title == k } false end def >(startup) self.funding > startup.funding end def hire(employee_n, title) if !valid_title?(title) raise "ERROR" else employee_n = Employee.new(employee_n, title) @employees << employee_n end end def size @employees.length end # def pay_employee(employee) # if self.funding >= @salaries[employee.title] # employee_pay = @salaries[employee.title] # @funding -= employee_pay # else # raise "we broke" # end # end def pay_employee(employee) if @funding >= @salaries[employee.title] employee.pay(@salaries[employee.title]) @funding -= @salaries[employee.title] else raise "ERROR" end end def payday @employees.each {|employee| pay_employee(employee)} end def average_salary total = [] @employees.each do |employee| total << @salaries[employee.title] end total.sum / @employees.length end def close @employees = [] @funding = 0 end def acquire(startup) @funding += startup.funding startup.salaries.each do |title2, salary2| if !@salaries.has_key?(title2) @salaries[title2] = salary2 end end @employees += startup.employees startup.close end end <file_sep>/week5/w5d3/aa_questions/question_like.rb class QuestionLike def self.find_by_id end end<file_sep>/week8/w8d3/js_exercise/phase_1_arrays.js // console.log('Hi Ray'); Array.prototype.uniq = function() { let arr = []; let max = this.length; for (let i = 0; i < max; i++){ if (arr.includes(this[i])) { continue; } else { arr.push(this[i]); } } return arr; } // let arr1 = [1, 2, 2, 3, 3, 3]; // console.log(arr1.uniq()); Array.prototype.twoSum = function (){ let arr = []; let max = this.length; for (let i = 0; i < max; i++){ for (let j = 0; j < max; j++){ if (this[i] + this[j] === 0) { arr.push([i,j]); } } } return arr; }; // let arr2 = [1, 2, 2, 3, -1, -2]; // console.log(arr2.twoSum()); // Transpose below let giantArr = [[1,2,3], [4,5,6], [7,8,9]]; // [ // [1, 4, 7] // [2, 5, 8] // [3, 6, 9] // ] //results -> [[1,4,7], [2,5,8], [3,6,9]] Array.prototype.transpose = function() { let row = this[1].length; let col = this.length; let matrix = new Array(row) // [ , ,] // [[ , ,],[, ,] , ,] for (let k = 0; k < matrix.length; k++){ matrix[k] = new Array(col); // for (let l = 0; l < col.length; l++){ // debugger; // matrix[k].push(); // } } // console.log(matrix[0].length); for (let i = 0; i < row; i++){ for (let j = 0; j < col; j++){ matrix[j][i] = this[i][j]; //console.log(matrix[j][i]); } } return matrix; }; // console.log(giantArr.transpose()); <file_sep>/week5/w5d3/aa_questions/user.rb class User attr_accessor :fname, :lname def self.find_by_id(id) ids = QuestionsDatabase.instance.execute( "SELECT * FROM users WHERE users.id = id") ids.map {|id| User.new(id)} end def initialize(hash) @id = hash[id] @fname = hash[fname] @lname = hash[lname] end end<file_sep>/week3/w3d2/edwin_ray_memory_puzzle/card.rb require "byebug" class Card attr_reader :name, :card CARD_LETTERS = ("A".."Z").to_a @@card_letters_pos = 0 def self.create_pair # debugger arr = [] arr << Card.new(CARD_LETTERS[@@card_letters_pos % 26]) arr << Card.new(CARD_LETTERS[@@card_letters_pos % 26]) @@card_letters_pos += 1 return arr end def initialize(name) @name = name @face_up = false end def hide @face_up = false end def reveal @face_up = true end def to_s #representation of the card object, print name of value of the card, useful for #Board.render #hide or reveal here if @face_up return self.name else return " " end end def ==(other_card) self.name == other_card.name end end # card = Card.new("test") # arr = [] # arr << Card.create_pair # p arr<file_sep>/week5/w5d3/aa_questions/import_db.sql PRAGMA foreign_keys = ON; --DROP tables here, order matters, reverse order DROP TABLE IF EXISTS question_likes; DROP TABLE IF EXISTS replies; DROP TABLE IF EXISTS question_follows; DROP TABLE IF EXISTS questions; DROP TABLE IF EXISTS users; CREATE TABLE users ( id INTEGER PRIMARY KEY, fname VARCHAR(255) NOT NULL, lname VARCHAR(255) NOT NULL ); CREATE TABLE questions ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, author_id INTEGER NOT NULL, FOREIGN KEY(author_id) REFERENCES users(id) ); CREATE TABLE question_follows ( id INTEGER PRIMARY KEY, question_id INTEGER NOT NULL, user_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (question_id) REFERENCES questions(id) ); CREATE TABLE replies ( id INTEGER PRIMARY KEY, question_id INTEGER NOT NULL, parent_id INTEGER NOT NULL, user_id INTEGER NOT NULL, reply TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (question_id) REFERENCES questions(id), FOREIGN KEY (parent_id) REFERENCES replies(id) ); CREATE TABLE question_likes ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, question_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (question_id) REFERENCES questions(id) ); INSERT INTO users (fname, lname) VALUES ('Chris', 'Lee'), ('Ray', 'Liang'), ('Bob', 'Ross'); INSERT INTO questions (title, body, author_id) VALUES ('reddit','first_post', (SELECT id FROM users WHERE fname = 'Chris')); INSERT INTO questions (title, body, author_id) VALUES ('title test', 'body test', 2); INSERT INTO question_follows (question_id, user_id) VALUES ((SELECT id FROM questions WHERE title = 'reddit'), (SELECT id FROM users WHERE fname = 'Chris'));<file_sep>/week5/w5d3/aa_questions/question_follow.rb class QuestionFollow def self.find_by_id(id) var = Questions end end <file_sep>/week1/w1d3/Christine_Ray_rspec_exercise_2/lib/part_1.rb require 'byebug' def partition(arr, num) new_arr = [[], []] (0..arr.length - 1).each do |i| if arr[i] < num new_arr[0] << arr[i] else new_arr[1] << arr[i] end end new_arr end def merge(hash1, hash2) #hash1.merge(hash2) new_hash = {} hash1.each do |k, v| if !new_hash[k] new_hash[k] = hash1[k] end end hash2.each do |k, v| if !new_hash[k] new_hash[k] = hash2[k] elsif new_hash[k] new_hash[k] = hash2[k] end end new_hash end def censor(sentence, curse_words) new_sentence = sentence.split(" ") vowels = "aeiouAEIOU" censored = [] new_sentence.each do |word| if curse_words.include?(word.downcase) new_word = "" word.each_char do |char| if vowels.include?(char) new_word += "*" else new_word += char end end censored << new_word else censored << word end end censored.join(" ") end def power_of_two?(num) #debugger (0..num).each do |exponent| if 2 ** exponent == num return true end end false end <file_sep>/week6/w6d4/ray_lynn_artshare_project/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # The first step of any seed file should be to destroy all current records Artwork.destroy_all User.destroy_all ArtworkShare.destroy_all # Good practice to destroy data with references first i.e. Drops reference user_ids, # users reference location_ids aw1 = Artwork.create(title: 'screamingman', image_url: 'google', artist_id: u1.id) aw2 = Artwork.create(title: 'monalisa', image_url: 'yahoo', artist_id: u1.id) aw3 = Artwork.create(title: 'meltingclock', image_url: 'msn', artist_id: u2.id) aw4 = Artwork.create(title: 'mountain', image_url: 'baidu', artist_id: u2.id) u1 = User.create(username: 'Apple') u2 = User.create(username: 'Banana') u3 = User.create(username: 'Canteloupe') u4 = User.create(username: 'Durian') u5 = User.create(username: 'Egg') u6 = User.create(username: 'Fruit') ArtworkShare.create!(artwork_id: aw1.id, viewer_id: u2.id) ArtworkShare.create!(artwork_id: aw2.id, viewer_id: u2.id) #--------------------------------------------------------------- # user1 = User.create!(username: 'robert') # user2 = User.create!(username: 'bill') # artwork1 = Artwork.create!(title: 'nighthawks', image_url: 'google.com', artist_id: user1.id) # artwork2 = Artwork.create!(title: '<NAME>', image_url: 'google1.com', artist_id: user2.id, favorite: true) # comment1 = Comment.create!(body: 'great!', user_id: user1.id, artwork_id: artwork1.id) # comment2 = Comment.create!(body: 'another great one', user_id: user2.id, artwork_id: artwork2.id) # Like.create!(user_id: user1.id, likeable_id: comment1.id, likeable_type: 'Comment') # Like.create!(user_id: user2.id, likeable_id: artwork2.id, likeable_type: 'Artwork') # Like.create!(user_id: user1.id, likeable_id: artwork2.id, likeable_type: 'Artwork') # Like.create!(user_id: user2.id, likeable_id: comment1.id, likeable_type: 'Comment')<file_sep>/week3/w3d3/muzammil_ray_recursion_exercises.rb require 'byebug' class Array def range(start, ending) arr = [] (start...ending).each do |ele| arr << ele end arr end def range_rec(start, ending) return [] if start >= ending next_num = start + 1 [start] + range_rec(next_num, ending) end #returns an array of all numbers in that range, exclusive. If end < start, you can return an empty array. # p range_rec(1, 5) #=> [1, 2, 3, 4] #Write both a recursive and iterative version of sum of an array. # range_rec(1, 5) # 1st pass: [1] + range_rec(2, 5) # 2nd pass: [2] + range_rec(3, 5) # 3rd pass: [3] + range_rec(4, 5) # 4th pass: [4] + range_rec(5, 5) # 5th pass: [] def exp1(base, num) #ver 1 decrementing return 1 if num == 0 return base if num == 1 base * exp1(base, num - 1) #ver 2 if even, divide exponent by 2, then square the result end def exp2(base, num) #ver 2 if even, divide exponent by 2, then square the result return 1 if num == 0 return base if num == 1 if num.even? exp2(base, num/2) ** 2 else base * (exp2(base, (num - 1) / 2 ) ** 2) end end def deep_dup new_arr = [] # debugger self.each {|ele| new_arr << (ele.is_a?(Array) ? ele.deep_dup : ele)} new_arr end end # robot_parts = [ # ["nuts", "bolts", "washers"], # ["capacitors", "resistors", "inductors"] # ] # p robot_parts[1].object_id # robot_parts_copy = robot_parts.deep_dup # robot_parts_copy[1] << "LEDs" # p robot_parts[1] # p robot_parts[1].object_id # p robot_parts_copy[1] # p robot_parts_copy[1].object_id def fibonacci(n) return [0] if n == 1 return [0, 1] if n == 2 fib = [0, 1] while fib.length < n next_num = fib[-1] + fib[-2] fib << next_num end fib end def fibonacci_rec(n) return [] if n == 0 return [0] if n == 1 return [0, 1] if n == 2 #fib = [] fib = fibonacci_rec(n - 1) fib << fib[-1] + fib[-2] fib end # p fibonacci_rec(7) def bsearch(arr, target) middle = arr.length / 2 lower = arr[0...middle] higher = arr[middle..-1] return arr.index(target) if arr[middle] == target return nil if arr.empty? return nil if arr.length == 1 && !arr.include?(target) if target < arr[middle] # arr = lower bsearch(lower, target) arr.index(target) else # arr = higher bsearch(higher, target) arr.index(target) end end p bsearch([1, 2, 3], 1) # => 0 p bsearch([2, 3, 4, 5], 3) # => 1 p bsearch([2, 4, 6, 8, 10], 6) # => 2 p bsearch([1, 3, 4, 5, 9], 5) # => 3 p bsearch([1, 2, 3, 4, 5, 6], 6) # => 5 p bsearch([1, 2, 3, 4, 5, 6], 0) # => nil p bsearch([1, 2, 3, 4, 5, 7], 6) # => #puts bsearch([], 6) # => nil<file_sep>/week2/w2d4/chris_lopez_ray_todo_board/todo_board_phase_1/item.rb require 'byebug' class Item attr_reader :title, :deadline,:description def self.valid_date?(string) #YYYY/MM/DD #debugger date = string.split("-") #['####', '##', '##'] #year year_range = (0..9999).to_a year = date[0] if !year_range.include?(year.to_i) return false raise "#{year} range is invalid" end #month month_range = (1..12).to_a #debugger month = date[1] if !month_range.include?(month.to_i) return false raise "#{month} range is invalid" end #day day_range = (1..31).to_a day = date[2] if !day_range.include?(day.to_i) return false raise "#{day} range is invalid" end true end def initialize(title, deadline, description) if Item.valid_date?(deadline) @title = title @deadline = deadline @description = description else raise "#{deadline} is invalid" end end def title=(new_title) @title = new_title end def deadline=(new_deadline) if Item.valid_date?(new_deadline) @deadline = new_deadline else raise "#{new_deadline} is an invalid date" end end def description=(new_description) @description = new_description end end # p my_item = Item.new('Fix login page', '2054-10-42', 'It loads slow.') <file_sep>/week6/w6d5/ninenine_cats/app/models/cat_rental_request.rb # t.integer "cat_id", null: false # t.date "start_date", null: false # t.date "end_date", null: false # t.string "status", default: "PENDING", null: false # t.index ["cat_id"], name: "index_cat_rental_requests_on_cat_id" class CatRentalRequest < ApplicationRecord validates :cat_id, :start_date, :end_date, :status, presence: true validates :status, inclusion: {in: ['PENDING', 'APPROVED', 'DENIED']} belongs_to :cat def overlapping_requests(cat) .find_by(:cat_id) .where('cat_id LIKE ') end end<file_sep>/week1/w1d5/amgaa_ray_rspec_exercise_5/lib/exercise.rb require 'byebug' def zip(*arrs) arrs.transpose #arrs[row][col] = arrs[col][row] end def prizz_proc(arr, p1, p2) arr.select {|ele| p1.call(ele) ^ p2.call(ele) } end def zany_zip(*arrs) longest = 0 new_arr = [] i = 0 while i < arrs.length if longest < arrs[i].length longest = arrs[i].length end i+=1 end arrs.each do |subarr| i = 0 while subarr.length < longest subarr << nil i+=1 end new_arr << subarr end new_arr.transpose end def maximum(arr, &prc) return nil if arr.empty? arr.inject do |acc, ele| if prc.call(acc) > prc.call(ele) acc else ele end end end def my_group_by(arr, &prc) hash = Hash.new {|h,k| h[k] = []} arr.each do |ele| key = prc.call(ele) hash[key] << ele end hash end def max_tie_breaker(arr, prc, &block) return nil if arr.empty? arr.inject do |acc, ele| if block.call(acc) > block.call(ele) #run both acc + ele into the block, take the LARGER original acc #ACC is larger elsif block.call(acc) == block.call(ele) #TIE, use prc.call to see which is bigger if prc.call(acc) < prc.call(ele) ele else acc end else #block.call(acc) < block.call(ele) ele #ELE is larger end end end def silly_syllables(sentence) #debugger words = sentence.split(" ") new_words = words.map do |word| if word.split("").count { |char| 'aeiou'.include?(char)} > 1 first = word.index(/[aeiou]/) #2 last = word.rindex(/[aeiou]/) #4 word[first..last] #word[2..4] else word end end new_words.join(" ") end <file_sep>/week5/w5d1/W5D1/skeleton/lib/p05_hash_map.rb # Phase 5: Hash Map (reprise) # So now let's incorporate our linked list into our hash buckets. Instead of Arrays, # we'll use LinkedLists for our buckets. Each linked list will start out empty. But # whenever we want to insert an item into that bucket, we'll just append it to the end # of that linked list. # So here again is a summary of how you use our hash map: # Hash the key, mod by the number of buckets (implement the #bucket method first for # cleaner code - it should return the correct bucket for a hashed key) # To set, insert a new node with the key and value into the correct bucket. (You can # use your LinkedList#append method.) If the key already exists, you will need to update # the existing node. # To get, check whether the linked list contains the key you're looking up. # To delete, remove the node corresponding to that key from the linked list. # Finally, let's make your hash map properly enumerable. You know the drill. Implement # #each, and then include the Enumerable module. Your method should yield [key, value] # pairs. # Also make sure your hash map resizes when the count exceeds the number of buckets! # In order to resize properly, you have to double the size of the container for your # buckets. Having done so, enumerate over each of your linked lists and re-insert # their contents into your newly-resized hash map. If you don't re-hash them, your # hash map will be completely broken. Can you see why? # Now pass those specs. # Once you're done, you should have a fully functioning hash map that can use numbers, # strings, arrays, or hashes as keys. Show off your understanding by asking a TA for # a Code Review. require_relative 'p04_linked_list' class HashMap attr_accessor :count def initialize(num_buckets = 8) @store = Array.new(num_buckets) { LinkedList.new } @count = 0 end def include?(key) end def set(key, val) end def get(key) end def delete(key) end def each end # uncomment when you have Enumerable included # def to_s # pairs = inject([]) do |strs, (k, v)| # strs << "#{k.to_s} => #{v.to_s}" # end # "{\n" + pairs.join(",\n") + "\n}" # end alias_method :[], :get alias_method :[]=, :set private def num_buckets @store.length end def resize! end def bucket(key) # optional but useful; return the bucket corresponding to `key` end end <file_sep>/week1/w1d1/TRIEU_RAY_W1D1/Trieu_Ray_algorithmic_strategies_exercise/04_peak_finder.rb # Write a method, peak_finder(arr), that accepts an array of numbers as an arg. # The method should return an array containing all of "peaks" of the array. # An element is considered a "peak" if it is greater than both it's left and right neighbor. # The first or last element of the array is considered a "peak" if it is greater than it's one neighbor. def peak_finder(arr) new_arr = [] arr.each_with_index do |num, i| if arr[i] == arr[0] && arr[i] > arr[i+1] #if we're looking at the FIRST number, is it bigger than the number next to it? new_arr << arr[i] elsif arr[i] == arr[-1] && arr[i] > arr[-2] #if we're looking at the LAST number, is it bigger than the number next to it? new_arr << arr[i] elsif arr[i-1] < arr[i] && arr[i] > arr[i+1] #if not the first/last, compare it to the numbers left and right of it new_arr << arr[i] end end new_arr end p peak_finder([1, 3, 5, 4]) # => [5] p peak_finder([4, 2, 3, 6, 10]) # => [4, 10] p peak_finder([4, 2, 11, 6, 10]) # => [4, 11, 10] p peak_finder([1, 3]) # => [3] p peak_finder([3, 1]) # => [3] <file_sep>/week1/w1d3/Christine_Ray_rspec_exercise_2/lib/part_2.rb require 'byebug' def palindrome?(str) reverse_word = "" i = str.length - 1 while i >= 0 reverse_word += str[i] i -= 1 end if str == reverse_word return true end false end def substrings(str) #debugger substring_arr = [] (0..str.length - 1).each do |idx1| (idx1..str.length - 1).each do |idx2| substring_arr << str[idx1..idx2] end end substring_arr end def palindrome_substrings(str) new_arr = [] substring = substrings(str) substring.each do |ele| if ele.length > 1 and palindrome?(ele) new_arr << ele end end new_arr end<file_sep>/week1/w1d5/ray_fa01p/lib/practice_assessment_1.rb # Define your methods here. require 'byebug' def first_letter_vowel_count(sentence) vowels = "aeiouAEIOU" count = 0 words = sentence.split(" ") words.each_with_index do |word, i| count += 1 if vowels.include?(word[0]) end count end def count_true(arr, proc) arr.count {|ele| proc.call(ele)} end def procformation(arr, p1, p2, p3) arr.map do |ele| if p1.call(ele) ele = p2.call(ele) else ele = p3.call(ele) end end end def array_of_array_sum(arr) arr.flatten.sum end def selective_reverse(sentence) vowels = "aeiouAEIOU" words = sentence.split(" ") new_sentence = [] words.each do |word| if vowels.include?(word[0]) or vowels.include?(word[-1]) new_sentence << word else new_sentence << word.reverse end end new_sentence.join(" ") end def hash_missing_keys(hash, *args) return [] if args.length == 0 array = [] args.each do |arg| if !hash.has_key?(arg) array << arg end end array end<file_sep>/week4/w4d5/anagrams.rb # def first_anagram?(str1, str2) # str1.chars.sort.join == str2.chars.sort.join # end require 'byebug' #n! def first_anagram?(str1, str2) anagrams = str1.split("").permutation(str1.length).to_a #permutation = n! anagrams.include?(str2.split("")) #n end # p first_anagram?("gizmo", "sally") #=> false # p first_anagram?("elvis", "lives") #=> true #n^2 + 0(n) def second_anagram?(str1, str2) arr1 = str1.split("") arr2 = str2.split("") arr1.each do |char| index = arr2.index(char) if !str2.include?(char) return false else # debugger arr2.delete_at(index) end end arr2.empty? end p second_anagram?("gizmo", "sally") #=> false p second_anagram?("elvis", "lives") #=> second<file_sep>/week1/w1d3/Christine_Ray_nauseating_numbers/nn_pt2.rb # Phase 2: Nothing you can't handle.--------------------------------------------------------------------- # anti_prime? # Write a method anti_prime? that accepts a number as an argument. # The method should return true if the given number has more divisors than all positive numbers less than the given number. # For example, 24 is an anti-prime because it has more divisors than any positive number less than 24. # Math Fact: Numbers that meet this criteria are also known as highly composite numbers. require 'byebug' def divisor_count(num) count = 1 (2...num).each do |factor| count += 1 if num % factor == 0 end return count end def anti_prime?(num) highest = 0 (1...num).each do |number| if divisor_count(number) > highest highest = divisor_count(number) end end divisor_count(num) > highest end # Examples # p anti_prime?(24) # true # p anti_prime?(36) # true # p anti_prime?(48) # true # p anti_prime?(360) # true # p anti_prime?(1260) # true # p anti_prime?(27) # false # p anti_prime?(5) # false # p anti_prime?(100) # false # p anti_prime?(136) # false # p anti_prime?(1024) # false # matrix_addition --------------------------------------------------------------------- # Let a 2-dimensional array be known as a "matrix". #Write a method matrix_addition that accepts two matrices as arguments. #The two matrices are guaranteed to have the same "height" and "width". #The method should return a new matrix representing the sum of the two arguments. #To add matrices, we simply add the values at the same positions: # # programmatically # [[2, 5], [4, 7]] + [[9, 1], [3, 0]] => [[11, 6], [7, 7]] # # structurally # 2 5 + 9 1 => 11 6 # 4 7 3 0 7 7 def matrix_addition(matrix1, matrix2) sum = [] matrix1.each.with_index do |subarr, idx1| #i = 0 new_sub = [] subarr.each_with_index do |ele, idx2| new_sub << matrix1[idx1][idx2] + matrix2[idx1][idx2] end sum << new_sub end sum end # Examples # matrix_a = [[2,5], [4,7]] # matrix_b = [[9,1], [3,0]] # matrix_c = [[-1,0], [0,-1]] # matrix_d = [[2, -5], [7, 10], [0, 1]] # matrix_e = [[0 , 0], [12, 4], [6, 3]] # p matrix_addition(matrix_a, matrix_b) # [[11, 6], [7, 7]] # p matrix_addition(matrix_a, matrix_c) # [[1, 5], [4, 6]] # p matrix_addition(matrix_b, matrix_c) # [[8, 1], [3, -1]] # p matrix_addition(matrix_d, matrix_e) # [[2, -5], [19, 14], [6, 4]] # # mutual_factors --------------------------------------------------------------------- # # Write a method mutual_factors that accepts any amount of numbers as arguments. # #The method should return an array containing all of the common divisors shared among the arguments. # #For example, the common divisors of 50 and 30 are 1, 2, 5, 10. # #You can assume that all of the arguments are positive integers. def divisors(num) divisors = [] (1..num).each do |factor| if num % factor == 0 divisors << factor end end divisors end def mutual_factors(*num) array = [] final = [] num.each do |number| div_arr = divisors(number) div_arr.each do |factor| array << factor if number % factor == 0 end end count = Hash.new(0) array.each do |baby_num| count[baby_num] += 1 end count.each do |k, v| if v == num.length final << k end end final end ###### #def factors(num) #(1..num).select {|i| num % i ==0} #end # def mutual_factors(*number) # nums # .map {|n| factors(n)} # .inject(:&) #long way # factors = nums.map {|n| factors(n)} # factors.inject do |acc, subarr| # acc & subarr # end # # Examples # p mutual_factors(50, 30) # [1, 2, 5, 10] # p mutual_factors(50, 30, 45, 105) # [1, 5] # p mutual_factors(8, 4) # [1, 2, 4] # p mutual_factors(8, 4, 10) # [1, 2] # p mutual_factors(12, 24) # [1, 2, 3, 4, 6, 12] # p mutual_factors(12, 24, 64) # [1, 2, 4] # p mutual_factors(22, 44) # [1, 2, 11, 22] # p mutual_factors(22, 44, 11) # [1, 11] # p mutual_factors(7) # [1, 7] # p mutual_factors(7, 9) # [1] # # tribonacci_number --------------------------------------------------------------------- # # The tribonacci sequence is similar to that of Fibonacci. # #The first three numbers of the tribonacci sequence are 1, 1, and 2. # #To generate the next number of the sequence, we take the sum of the previous three numbers. # #The first six numbers of tribonacci sequence are: # # 1, 1, 2, 4, 7, 13, ... and so on # # Write a method tribonacci_number that accepts a number argument, n, and returns the n-th number of the tribonacci sequence. def tribonacci_number(num) tribonacci = [1, 1, 2] (0...num).each do |i| arr_slice = tribonacci[-3..-1].sum tribonacci << arr_slice end p tribonacci tribonacci[num-1] end # # Examples p tribonacci_number(1) # 1 p tribonacci_number(2) # 1 p tribonacci_number(3) # 2 p tribonacci_number(4) # 4 p tribonacci_number(5) # 7 p tribonacci_number(6) # 13 p tribonacci_number(7) # 24 p tribonacci_number(11) # 274 <file_sep>/week2/w2d4/ray_practice_assessment_2/lib/board.rb class Board attr_reader :max_height # This Board#print method is given for free and does not need to be modified # It is used to make your game playable. def print @stacks.each { |stack| p stack } end def self.build_stacks(stacks)#num stacks = Array.new(stacks) {Array.new} end def initialize(stacks, height) @max_height = height if stacks < 4 or height < 4 raise 'rows and cols must be >= 4' else @stacks = Board.build_stacks(stacks) end end def add(token, idx) if @stacks[idx].length < @max_height @stacks[idx] << token return true else false end end def vertical_winner?(token) @stacks.each do |row| if row.length == @max_height return true if row.all? {|ele| ele == token } end end false end def horizontal_winner?(token) # minimum = @stacks.map{|stack| stack.length}.min i = 0 while i < @stacks.length #minimum j = 0 count = 0 while j < @stacks.length #minimum if @stacks[j][i] == token count += 1 else break end return true if count == @stacks.length j += 1 end i += 1 end false end def winner?(token) self.horizontal_winner?(token) || self.vertical_winner?(token) end end <file_sep>/week5/w5d3/aa_questions/questions_database.rb require 'sqlite3' require 'singleton' class QuestionsDatabase < SQLite3::Database include Singleton def initialize #E.g., User.new('fname' => 'Ned', 'lname' => 'Ruggeri', 'is_instructor' => true) should return a User object with those attributes. super('questions.db') self.results_as_hash = true self.type_translation = true QuestionsDatabase.execute (<<-SQL SQL) end end<file_sep>/week3/w3d1/dane_ray_enumerables.rb class Array def my_each(&block) i = 0 while i < self.length block.call(self[i]) i += 1 end self end def my_select(&block) new_arr = [] self.my_each {|ele| new_arr << ele if block.call(ele)} new_arr end def my_reject(&block) new_arr = [] self.my_each {|ele| new_arr << ele if !block.call(ele)} new_arr end def my_any?(&block) self.my_each {|ele| return true if block.call(ele)} false end def my_all?(&block) self.my_each {|ele| return false if !block.call(ele)} true end def my_flatten new_arr = [] return new_arr if self.empty? # return [self[0]] if self[0].class != Array new_arr += self[0].class == Array ? self[0].my_flatten : [self[0]] new_arr += self[1..-1].my_flatten new_arr end def my_zip(*arrs) new_arr = Array.new(self.length) {[]} (0...self.length).each do |i| new_arr[i] << self[i] (0...arrs.length).each { |j| new_arr[i] << arrs[j][i] } end new_arr end def my_rotate(n = 1) return self if self.empty? n = n % self.length self[n..-1] + self[0...n] end def my_join(string="") new_str = "" (0...self.length-1).each {|ele| new_str += self[ele] + string} return new_str += self[-1].to_s end def my_reverse new_arr = [] (0...self.length).each {|i| new_arr << self[self.length - 1 - i]} new_arr end def bubble_sort!(&prc) sorted = false prc ||= Proc.new() {|a, b| a <=> b} while !sorted sorted = true (0...self.length - 1).each do |i| self[i], self[i + 1], sorted = self[i + 1], self[i], false if prc.call(self[i], self[i + 1]) == 1 end end end def bubble_sort(&prc) new_arr = self.dup sorted = false prc ||= Proc.new() {|a, b| a <=> b} while !sorted sorted = true (0...new_arr.length - 1).each do |i| new_arr[i], new_arr[i + 1], sorted = new_arr[i + 1], new_arr[i], false if prc.call(new_arr[i], new_arr[i + 1]) == 1 end end new_arr end end def factors(num) new_arr = [] (1...num).each {|ele| new_arr << ele if num % ele == 0} new_arr end def substrings(string) substrings = [] (0...string.length).each do |i| (i...string.length).each do |j| substrings << string[i..j] end end substrings end def subwords(word, dictionary) substrings(word).select {|word| dictionary.include?(word)} end<file_sep>/week5/w5d1/W5D1/skeleton/lib/p03_hash_set.rb # Phase 3: HashSet # Now that we've got our hashing functions, we can store more than just integers. A proper # hashing function also ensures that the elements that we store will be evenly distributed # amongst our buckets, hopefully keeping our buckets to length <= 1. Our freshly cooked # up hashing functions are awesome, but for the rest of this project we'll rely on the # built-in Ruby hashing functions to minimize the clustering of elements that can occur # with our hand-made functions. Let's go ahead and implement a HashSet! # This will be a simple improvement on ResizingIntSet. Just hash every item before # performing any operation on it. This will return an integer, which you can modulo by # the number of buckets. Implement the #[] method to dry up your code. With this simple # construction, your set will be able to handle keys of any data type. # Not too different from what we had before - and we now have a much better set that works # with any data type! Time to request a code review. # Now let's take it one step further. # Up until now, our hash set has only been able to insert and then check for inclusion. # We couldn't create a map of values, as in key-value pairs. Let's change that and create # a hash map. But first, we'll have to build a subordinate, underlying data structure. class HashSet attr_reader :count def initialize(num_buckets = 8) @store = Array.new(num_buckets) { Array.new } @count = 0 end def insert(key) end def include?(key) end def remove(key) end private def [](num) # optional but useful; return the bucket corresponding to `num` end def num_buckets @store.length end def resize! end end <file_sep>/week5/w5d3/aa_questions/question.rb class Question def self.find_by_id end def initialize() @id, @title, @body, @author_id end end<file_sep>/week3/w3d5/PolyTreeNode/lib/00_tree_node.rb require 'byebug' class PolyTreeNode attr_reader :value, :parent, :children def initialize(value, children = [] ) @value = value @parent = nil @children = children end def inspect @value end def parent=(new_parent_node) old_parent_node = self.parent @parent = new_parent_node @parent.children << self if @parent != nil && !@parent.children.include?(self) old_parent_node.children.delete(self) if old_parent_node != nil && old_parent_node != @parent end def add_child(child) child.parent = self end def remove_child(child) if child.parent == nil raise "node is not a child" else child.parent = nil end end def dfs(value) return self if self.value == value self.children.each do |child| result = child.dfs(value) return result unless result.nil? end nil end def bfs(value) # debugger queue = [self] #[5,4] until queue.empty? ele = queue.shift if value == ele.value return self end ele.children.each {|child| queue << child } #[2,3] end end end <file_sep>/week4/w4d4/TDD Classwork/spec/tdd_spec.rb # --format documentation --color require 'tdd' require 'rspec' describe '#remove_dups' do context "an array gets passed containing duplicates" do it "removes duplicates from an array. It returns the unique elements in the order in which they first appeared" do expect(remove_dups([1,2,2,2,3,4])).to match_array([1,2,3,4]) end end end describe '#two_sum' do context "takes in an array and returns a new array" do it "finds all pairs of positions where the elements at those positions sum to zero" do expect(two_sum([-1, 0, 2, -2, 1])).to match_array([[0, 4], [2, 3]]) end end end describe '#my_transpose' do context "takes in a 2D array of with equal lengths for rows and cols" do it "it transposes the 2D array" do expect(my_transpose([[0, 1, 2],[3, 4, 5],[6, 7, 8]])).to match_array(([[0, 1, 2],[3, 4, 5],[6, 7, 8]]).transpose) end end end describe '#stock_picker'do context "find the most profitable stocks from an array" do it "find the indices of the days that gives the most profitable outcome, the first index is the day you purchased the stock" do expect(stock_picker([120, 100, 80, 50, 90, 70])).to match_array([3,4]) end end end describe Tower do let(:tower) { Tower.new } # @board = Array.new(3) {Array.new(3, [])} # @pile1 = @board[0] # pile1 = [1,2,3].shuffle # @pile2 = @board[1] # @pile3 = @board[2] describe "#move" do context "have 3 discs in 3 places" do it "moves one disc to another disc pole" do tower.board[0] = [1] tower.board[1] = [] tower.board[2] = [2,3] tower.move("1","3") expect(tower.board).to match_array([[],[],[1,2,3]]) end end end describe "#won?" do context "discs are arranged correctly on one pole" do it "return a win" do tower.board[0] = [] tower.board[1] = [] tower.board[2] = [1,2,3] state = false state = tower.won? expect(state).to eq(true) end end end end<file_sep>/week4/w4d4/TDD Classwork/lib/tdd.rb require 'byebug' # Remove dups # Array has a uniq method that removes duplicates from an array. It returns the unique elements in the order in which they first appeared: # [1, 2, 1, 3, 3].uniq # => [1, 2, 3] # Write your own version of this method called my_uniq; it should take in an Array and return a new array. def remove_dups(array) new_arr = [] array.each do |ele| new_arr << ele if !new_arr.include?(ele) end new_arr end #p remove_dups([1, 2, 1, 3, 3]).uniq # => [1, 2, 3] # Two sum # Write a new Array#two_sum method that finds all pairs of positions where the elements at those positions sum to zero. # NB: ordering matters. We want each of the pairs to be sorted smaller index before bigger index. We want the array of pairs to be sorted "dictionary-wise": # [-1, 0, 2, -2, 1].two_sum # => [[0, 4], [2, 3]] # [0, 2] before [2, 1] (smaller first elements come first) # [0, 1] before [0, 2] (then smaller second elements come first) def two_sum(array) pairs = [] array.each_with_index do |ele1, idx1| array.each_with_index do |ele2, idx2| if idx2 < idx1 && (ele1 + ele2) == 0 pairs << [idx2, idx1] end end end pairs end def my_transpose(array) array.transpose end # Stock Picker # Write a method that takes an array of stock prices (prices on days 0, 1, ...), and outputs the most profitable pair of days on which to first buy the stock and then sell the stock. Remember, you can't sell stock before you buy it! def stock_picker(array) pairs = [] highest = 0 #highest_idx = 0 array.each_with_index do |ele1, idx1| array.each_with_index do |ele2, idx2| if idx2 < idx1 && (ele1 - ele2) > highest pairs << [idx2, idx1] highest = (ele1 - ele2) end end end pairs.pop end class Tower attr_accessor :pile1, :pile2, :pile3, :board def initialize @board = [[1,2,3],[],[]] # setup_board end def from p "please pick a pile to move the top disc from: ____, e.g. pile1, pile2, or pile3" from = gets.chomp end def start p self.board p "please pick a pile to move the top disc from: ____, e.g. 1, 2, or 3" from = gets.chomp p "please pick a pile to move the top disc to: ____, e.g. 1, 2, 3" to = gets.chomp move(from, to) end def move(from, to) if from == to raise "you can't move the a disc to the same pile" elsif from == "1" && to == "2" #move from pile1 to pile2 board[1].unshift(board[0].shift) elsif from == "1" && to == "3" #move from pile1 to pile3 board[2].unshift(board[0].shift) elsif from == "2" && to == "3" #move from pile2 to pile3 board[2].unshift(board[1].shift) elsif from == "2" && to == "1" #move from pile2 to pile1 board[0].unshift(board[1].shift) elsif from == "3" && to == "1" #move from pile3 to pile1 board[0].unshift(board[2].shift) elsif from == "3" && to == "2" #move from pile3 to pile2 board[1].unshift(board[2].shift) end if !won? self.start else p "congrats!" p self.board end #shift to remove top disc #unshift to put disc on top of a different pile end def won? if @board.any? {|pile| pile == [1,2,3] && pile != board[0]} return true else return false end end end <file_sep>/week9/w9d3/TTT_skeleton/src/index.js const View = require('./ttt-view.js')// require appropriate file // const Game = // require appropriate file $(() => { // Your code here }); <file_sep>/week10/w10d1/jquery_lite/src/index.js function core () { window.$1 = function (selector){ const nodelist = document.querySelectorAll(selector); const arr = Array.from(nodelist); } }
a8c45c257a61c5339e48f014e5a64eed726b9cb8
[ "JavaScript", "SQL", "Ruby" ]
52
JavaScript
bigcachemoney/aA-Classwork
23c0e55eb8d1265519ca63cad9eee6a9a6d059a2
bd9f61ef417cf3871d09f0abda2fe485db92b4f2
refs/heads/master
<file_sep>import React from 'react'; import './Home.css'; import Banner from './Banner' import Card from './Card' function Home(){ return( <div className='home'> <Banner/> <div className='home__section'> <Card src="https://www.deluxora.com/images/products/retro_wooden_home_key_holder_with_four_hooks-1530943964-1_crop.jpg" title="Online Experiences" description="Unique activities we can do together, led by a world of hosts." /> <Card src="https://wheretoflynextcom.files.wordpress.com/2019/03/sahara-desert-luxury-camp-merzouga-booking.com-tent.jpg?w=1000&h=667" title="Unique stays" description="Spaces that are more than just a place to sleep." /> <Card src="https://i.pinimg.com/originals/a1/15/7c/a1157c46018066b8517c798467ceda06.jpg" title="Entire Homes" description="Comfortable private places, with room for friends or family." /> </div> <div className='home__section'> <Card src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExIVFRUVFRcVFxcVGBUWFxUYFRUXFxcWFRcYHSggGBolGxYVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGi0lHR0tLS0tLS0tLS0rLS0tLSstLS0tKy0tLS0rLS0tLS0tLS0tLS0tLS0rLS0tLS0rLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAcAAAABwEBAAAAAAAAAAAAAAAAAQIDBAUGBwj/xABLE<KEY> title="3 Bedroom Flat in Bournemouth" description="Superhost with a stunning view of the beachside in Sunny Bournemouth" price="£350/night" /> <Card src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExIVFRUVFRcVFxcVGBUWFxUYFRUXFxcWFRcYHSggGBolGxYVITEhJSkrLi4uFx8zODMtNygt<KEY>0lHR0tLS0tLS0tLS0rLS0tLSstLS0tKy0tLS0rLS0tLS0tLS0tLS0tLS0rLS0tLS0rLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAcAAAABwEBAAAAAAAAAAAAAAAA<KEY>Mp<KEY>Ph<KEY>PxFlNzgq<KEY>AgMEBf/EACYRAAICAgICAQMFAAAAAAAAAAABAhEDIRIxBEFRIjJCBRNhkfH/2gAMAwEAAhEDEQA/AOz4n2TKtjLPFeyfCU9R9ZDexjytFhpFV5JooW3RpiFh4sNGG0hB5diJQaKDSMHiw8dgSA0UGkcNFhogH7xQaMBooNAY+DBeNhod4CHLwXiM0F4ALvBeIvBeAC7wrx<KEY> title="3 Bedroom Flat in Bournemouth" description="Superhost with a stunning view of the beachside in Sunny Bournemouth" price="£350/night" /> <Card src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExIVFRUVFRc<KEY> title="3 Bedroom Flat in Bournemouth" description="Superhost with a stunning view of the beachside in Sunny Bournemouth" price="£350/night" /> </div> </div> ) } export default Home<file_sep>import React from 'react'; import './App.css'; import Home from './Home'; import Header from './Header'; import Footer from './Footer'; import Data from './data.json'; function App() { return ( <div className="App"> <div className="posts"> { Data.map(post =>{ return ( <div key={post.name}> <h4>{ post.hotelName}</h4> <p>{post.rating}</p> </div> ) })} </div> <Header /> <Home /> <Footer/> </div> ); } export default App;
8d27340a9a0274b823832abc2bd36cad7ac5155c
[ "JavaScript" ]
2
JavaScript
bergoulan/AirBnb-clone
dc8c02235388670b4d5158a67c154c5e77e3eeb7
b0a151d64cfc72be7f6573a5fe031b2096a9a495
refs/heads/master
<file_sep># tousize [![Maintenance](https://img.shields.io/badge/maintenance-actively%20maintained-brightgreen.svg)](https://github.com/SirWindfield/tousize) [![crates.io](https://img.shields.io/crates/v/tousize.svg)](https://crates.io/crates/tousize) [![crates.io](https://img.shields.io/crates/d/tousize)](https://crates.io/crates/tousize) [![Documentation](https://docs.rs/tousize/badge.svg)](https://docs.rs/tousize) [![docs_master_badge]][docs_master_url] > A Rust library providing a trait for `usize` conversion. ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [docs_master_badge]: https://img.shields.io/badge/docs.rs-master-green [docs_master_url]: https://tousize.zerotask.net <file_sep>[package] name = "tousize" description = "A helper trait to convert values into usize." version = "1.0.0" license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/SirWindfield/tousize" authors = ["<NAME> <<EMAIL>>"] edition = "2018" <file_sep>//! A helper trait to convert values to `usize`. //! //! This is most useful for code that works with array indices. The trait allows //! to pass anything into the function that can be resolved to a `usize`. /// A trait used to convert a type into a `usize`. pub trait ToUsize { /// Converts self into `usize`. fn to_usize(&self) -> usize; } impl ToUsize for u8 { #[inline] fn to_usize(&self) -> usize { *self as usize } } impl ToUsize for u16 { #[inline] fn to_usize(&self) -> usize { *self as usize } } // 16bit platforms use a `usize` of 16bit. Converting using a cast would fail on // those systems. #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] impl ToUsize for u32 { #[inline] fn to_usize(&self) -> usize { *self as usize } } // 32bit platforms use a `usize` of 32bit. Converting using a cast would fail on // those systems. #[cfg(target_pointer_width = "64")] impl ToUsize for u64 { #[inline] fn to_usize(&self) -> usize { *self as usize } } impl ToUsize for usize { #[inline] fn to_usize(&self) -> usize { *self } }
ef6a97f37787c89734993c35c28633f7cee90503
[ "Markdown", "TOML", "Rust" ]
3
Markdown
SirWindfield/tousize
a3d496fc73ebae0f2117075a12892f6642e66ecf
06dee89847be700f01456832a8ce13f38b021d6c
refs/heads/master
<file_sep>package com.hs.persistence; import org.springframework.data.repository.CrudRepository; import com.hs.domain.Attach_file; public interface Attach_fileRepository extends CrudRepository<Attach_file, Long>{ } <file_sep>/** * */ /** * @author DoYoung * 한신메디피아 예약/결과조회 */ package com.hs.questionnaire.controller;<file_sep>package com.hs.young; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Commit; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import com.hs.domain.Attach_file; import com.hs.domain.Qna; import com.hs.domain.Qna_comment; import com.hs.persistence.QnaRepository; import com.hs.persistence.Qna_commentRepository; import lombok.extern.java.Log; @RunWith(SpringRunner.class) @SpringBootTest @Log @Commit // test 내용들은 default 로 rollback이되기 떄문에 적용시킬려면 @Commit 어노테이션이 필요. public class QnaTest { @Autowired QnaRepository qnaRepository; @Autowired Qna_commentRepository qnaCommRepo; @Test public void testInsertQna() { Qna qna = new Qna(); qna.setTitle("QnaTitle"); Attach_file file1 = new Attach_file(); file1.setAttach_name("file1.doc"); Attach_file file2 = new Attach_file(); file2.setAttach_name("file2.doc"); qna.setFiles(Arrays.asList(file1,file2)); log.info("try to save qna"); qnaRepository.save(qna); } @Test //optional 을 사용하지 않은 방식 public void testUpdateQna() { if(qnaRepository.existsById(1L)) { Optional<Qna> qna = qnaRepository.findById(1L); log.info(" orizinal title : "+ qna.get().getTitle()); qna.get().setTitle("update 한 title3"); log.info(" update : "+ qna.get().getTitle()); qnaRepository.save(qna.get()); //save 바뀐내용만 update 시켜줌 } } //optional 을 사용한 예 @Transactional @Test public void testUpdateQna3() { String newName = "updateFile2.doc"; Optional<Qna> result = qnaRepository.findById(1L); result.ifPresent(qna ->{ //해당 결과가 존재한다면 log.info("데이터가 존재하므로 update 시도 !"); Attach_file target = new Attach_file(); target.setAttach_key(2L); target.setAttach_name(newName); int idx = qna.getFiles().indexOf(target); //2번 첨부파일이 있는지 확인 if(idx > -1) { //2번 첨부파일이 있으면 새로운 파일로 교체 List<Attach_file> list = qna.getFiles(); list.remove(idx); list.add(target); qna.setFiles(list); } qnaRepository.save(qna); }); } @Transactional @Test public void deleteFile() { //첨부파일 번호 Long attach_key = 1L; qnaRepository.deleteById(attach_key); } @Transactional @Test public void insertDummies() { List<Qna> list = new ArrayList<>(); IntStream.range(103, 150).forEach(i -> { Qna qna = new Qna(); qna.setTitle("자료 "+ i); qna.setWriter("user"+i); qna.setPswd("1234"); qna.setContent("<p>테스트입니다.</p>"); //파일 첨부 확인 Attach_file file1 = new Attach_file(); file1.setAttach_name("file1.doc"); file1.setAttach_attr("qna"); Attach_file file2 = new Attach_file(); file2.setAttach_attr("qna"); file2.setAttach_name("file2.doc"); qna.setFiles(Arrays.asList(file1,file2)); log.info("try to save qna"); list.add(qna); }); qnaRepository.saveAll(list); } @Transactional @Test public void insertDummies2() { IntStream.range(1, 100).forEach(i -> { Qna qna = new Qna(); qna.setQno((long) i); IntStream.range(1, 3).forEach(i2 -> { //뎃글 Qna_comment comm = new Qna_comment(); comm.setBoard_comment("<p>테스트입니다.</p>"); comm.setCommenter("user"+i2); comm.setQna(qna); qnaCommRepo.save(comm); }); }); } } <file_sep>/** * 아코디언 js */ $(function(){ var accordianContent jQuery(".accordianContent").hide(); //content 클래스를 가진 div를 표시/숨김(토글) $(".accordian").on("click",function(e) { e.preventDefault(); $('.accordian').removeClass('accordian_rotate'); if($(this).next().css("display") == "none"){ $(this).addClass('accordian_rotate'); } $(".accordianContent").not($(this).next(".accordianContent").slideToggle(200)).slideUp(200); $('.accordian').removeClass('accordian_select'); $(this).addClass('accordian_select'); }); })<file_sep>$(function(){ /* input 에 효과주기 */ $('span.ps_box input').focus(function(){ $(this).parent().addClass("press"); }); $('span.ps_box input').blur(function(){ $('span.ps_box input').parent().removeClass("press"); }); $('span.ps_box.borderNone input').focus(function(){ $(this).addClass("press"); }); $('span.ps_box.borderNone input').blur(function(){ $('span.ps_box.borderNone input.press').removeClass("press"); }); }); $(document).ready(function(){ //onSubmit $("#loginGo").on("click",function(){ loginSubmit(); }) $("#tfId").keydown(function (event) { if (event.keyCode === 13) { loginSubmit(); } }); $("#pwTf").keydown(function (event) { if (event.keyCode === 13) { loginSubmit(); } }); }); function loginSubmit(){ $("#loginForm").submit(); } <file_sep>package com.hs.persistence; import org.springframework.data.repository.CrudRepository; import com.hs.domain.Qna_comment; public interface Qna_commentRepository extends CrudRepository<Qna_comment,Long>{ } <file_sep>package com.hs.daumEditorUtil; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpSession; import org.springframework.ui.Model; import org.springframework.web.multipart.MultipartFile; import lombok.extern.java.Log; @Log public class FileUploadUtil { public HashMap<String, Object> execute(Model model) { Map<String, Object> map = model.asMap(); log.info("FileUploadUtil execute !! "); MultipartFile mf = (MultipartFile) map.get("mf"); HttpSession httpSession = (HttpSession) map.get("httpSession"); HashMap<String, Object> fileInfo = new HashMap<String, Object>(); if(mf != null && !(mf.getOriginalFilename().equals(""))) { String originalName = mf.getOriginalFilename(); //파일이름 String originalNameExtension = originalName.substring(originalName.lastIndexOf(".")+1).toLowerCase(); //확장자 제한 if(((originalNameExtension.equals("html")) || (originalNameExtension.equals("php")) || (originalNameExtension.equals("exe")) || (originalNameExtension.equals("js")) || (originalNameExtension.equals("java")) || (originalNameExtension.equals("class")) )) { fileInfo.put("result", -1); return fileInfo; } //파일 크기 제한(100MB) long fileSize = mf.getSize(); long limitFileSize = 100 * 1024 * 1024; //100MB if(limitFileSize < fileSize) { fileInfo.put("result", -2); return fileInfo; } //파일 저장명 처리 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMDDHHmmss"); SimpleDateFormat dateFormatHH = new SimpleDateFormat("yyyyMM"); String today = dateFormat.format(new Date()); String todayHH = dateFormatHH.format(new Date()); String modifyPath = todayHH; String modifyName = today + "_" + UUID.randomUUID().toString().substring(20) + "." + originalNameExtension; //저장경로 String defaultPath = httpSession.getServletContext().getRealPath("/"); //서버 기본 경로(프로젝트X) String path = defaultPath + File.separator + "upload" + File.separator + "board" + File.separator + "file" + File.separator + modifyPath + File.separator; //저장경로 처리 File file = new File(path); if(!file.exists()) { //디렉토리 존재하지 않을 경우 디렉토리 생성 file.mkdirs(); } //Multipart 처리 try { mf.transferTo(new File(path + modifyName)); log.info("path + modifyName : " + path + modifyName); log.info("path : " + path); log.info("originalName : " + originalName); } catch(Exception e) { e.printStackTrace(); } String attachUrl = httpSession.getServletContext().getContextPath() + "/upload/board/file/" + modifyPath + "/" + modifyName + "/" + originalName; String filePath = "/upload/board/file/" + modifyPath + "/" + modifyName; String filePath2 = "/upload/board/file/" + modifyPath; fileInfo.put("attachurl", filePath); fileInfo.put("filename", originalName); fileInfo.put("modifyname", modifyName); fileInfo.put("path", filePath); fileInfo.put("path2", filePath2); fileInfo.put("filemime", originalNameExtension); fileInfo.put("filesize", fileSize); fileInfo.put("result", 1); } return fileInfo; } } <file_sep>$(function(){ $(".preview-imgWrap .carocelImg").on("click",function(){ var index = $(this).index(); medicaruceling(index); }); $("a.caracelBtn.left").on("click",function(){ var index = $(".preview-imgWrap .carocelImg.active").index(); if(index == 0){ index =$(".preview-imgWrap .carocelImg:last-child()").index()+1; } index = index -1; medicaruceling(index); }); $("a.caracelBtn.right").on("click",function(){ var index = $(".preview-imgWrap .carocelImg.active").index(); if(index == $(".preview-imgWrap .carocelImg:last-child()").index()){ index =$(".preview-imgWrap .carocelImg:first-child()").index() -1; } index = index +1; medicaruceling(index); }); }); function medicaruceling(index){ if($(".carocelImgwrap .carocelImg")){ $(".carocelImgwrap .carocelImg").css("opacity","0"); $(".carocelImgwrap .carocelImg").eq(index).css("opacity","1"); } if($(".preview-imgWrap .carocelImg")){ $(".preview-imgWrap .carocelImg").removeClass("active"); $(".preview-imgWrap .carocelImg").eq(index).addClass("active"); } if($(".caracelTextWrap .caracelTextBox")){ $(".caracelTextWrap .caracelTextBox").removeClass("active"); $(".caracelTextWrap .caracelTextBox").eq(index).addClass("active"); } }<file_sep> $(document).ready(function() { /*이게 더 좋은 소스*/ var adminContextHeight = $('.adminContext').height(); var realSu = parseInt(adminContextHeight) - parseInt($('.adminContext .likeTab ul').height()); console.log(adminContextHeight); console.log(realSu); $('.adminSidebar').css({ "height" : realSu + 'px' }); $(window).resize(function() { /*$('.adminSidebar').css('height',$('.adminContext').css('height')); */ $('.adminSidebar').css({ "height" : realSu + 'px' }); }) }); <file_sep>package com.hs.reserveAct.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/reserveAct") public class reserveActViewC { // 예약신청폼 @GetMapping("/request") public void request() {} // 예약수정폼 @GetMapping("/requestModify") public void requestModify() {} // 예약현황보기 @GetMapping("/requestView") public void requestView() {} // 예약신청 상세보기 @GetMapping("/reserveDetail") public void requestDetail() {} // 예약신청 리스트 @GetMapping("/reserveList") public void requestLisr() {} } <file_sep>$(function(){ $('.joinStatus .rightProcedure .wrapperProcedure .boxProcedure:nth-of-type(1)').addClass('active'); $(".consent.agreeBtn").on("click",function(){ $(this).toggleClass('onBtn'); checkAgree(); }) $(".all-consent.agreeBtn").on("click",function(){ if(!$(".all-consent.agreeBtn").hasClass("onBtn")){ $(".all-consent.agreeBtn").addClass("onBtn"); $(".consent.agreeBtn").addClass("onBtn"); $(".followBtn").addClass("active"); var offset = $("#submitBtn").offset(); $("html body").animate({scrollTop:offset.top},400); }else{ $(".all-consent.agreeBtn").remove("onBtn"); $(".followBtn").removeClass("active"); $(".consent.agreeBtn").removeClass("onBtn"); } checkAgree(); }) $("#submitBtn").on("click",function(){ var check = true $(".consent.agreeBtn").each(function(){ if(!$(this).hasClass("onBtn")){ check = false; } }); if(check){ localStorage.setItem('joinWrite','checked'); location.href='/join/writeInfo'; }else{ alert("이용약관동의를 하셔야 회원가입을 하실 수 있습니다.") } }) }) function checkAgree(){ var check = true $(".consent.agreeBtn").each(function(){ if(!$(this).hasClass("onBtn")){ check = false; } }) if(check){ if(!$(".all-consent.agreeBtn").hasClass("onBtn")){ $(".all-consent.agreeBtn").addClass("onBtn"); } if(!$(".followBtn").hasClass("active")){ $(".followBtn").addClass("active"); } }else{ $(".all-consent.agreeBtn").removeClass("onBtn"); $(".followBtn").removeClass("active"); } } <file_sep>package com.hs.security; import java.util.ArrayList; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import com.hs.domain.Member; import com.hs.domain.MemberRole; import lombok.Getter; import lombok.Setter; @Getter @Setter public class HSSecurityUser extends User { private static final String ROLE_PREFIX = "ROLE_"; private Member member; private String memberStr; public HSSecurityUser(Member member) { super(member.getMember_id(), member.getMember_pw(), makeGrantedAuthority(member.getRoles())); this.member = member; this.memberStr = member.getMember_id(); } private static List<GrantedAuthority> makeGrantedAuthority(List<MemberRole> roles) { List<GrantedAuthority> list = new ArrayList<>(); roles.forEach(role -> list.add(new SimpleGrantedAuthority(ROLE_PREFIX + role.getRoleName()))); return list; } } <file_sep>package com.hs.domain; import java.sql.Timestamp; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @Entity @Table(name = "qna") @EqualsAndHashCode(of = "qno") //callSuper = 부모의 키값과 맞는지 비교한다. @ToString(exclude= {"files","comments"}) //callSuper = true 부모에 맴버까지 toString 한다. public class Qna { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="q_key") private Long qno; @Column(name ="q_title") private String title; @Column(name ="q_writer") private String writer; @Column(name ="q_content") private String content; //게시글 비밀번호 @Column(name ="q_pswd") private String pswd; @Column(name ="q_email") private String email; private Long views =0L; @CreationTimestamp @Column(name ="q_date") private Timestamp date; @UpdateTimestamp private Timestamp updatedate; @OneToMany(fetch =FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name ="attach_ref") //attach_file 과 join 을 시켜줄 joinColumn 생성 private List<Attach_file> files; @JsonIgnore @OneToMany(mappedBy="qna", cascade = CascadeType.ALL, fetch=FetchType.LAZY) private List<Qna_comment> comments; } <file_sep>/** * */ /** * @author DoYoung * 한신메디피아 프로그램안내 */ package com.hs.guide.controller;<file_sep>package com.hs.domain; import static com.querydsl.core.types.PathMetadataFactory.*; import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.PathMetadata; import javax.annotation.Generated; import com.querydsl.core.types.Path; /** * QAttach_file is a Querydsl query type for Attach_file */ @Generated("com.querydsl.codegen.EntitySerializer") public class QAttach_file extends EntityPathBase<Attach_file> { private static final long serialVersionUID = -643813886L; public static final QAttach_file attach_file = new QAttach_file("attach_file"); public final StringPath attach_attr = createString("attach_attr"); public final NumberPath<Long> attach_key = createNumber("attach_key", Long.class); public final StringPath attach_name = createString("attach_name"); public final StringPath attach_path = createString("attach_path"); public final NumberPath<Long> attach_ref = createNumber("attach_ref", Long.class); public final NumberPath<Long> attach_size = createNumber("attach_size", Long.class); public final DateTimePath<java.sql.Timestamp> attach_time = createDateTime("attach_time", java.sql.Timestamp.class); public final DateTimePath<java.sql.Timestamp> updatedate = createDateTime("updatedate", java.sql.Timestamp.class); public QAttach_file(String variable) { super(Attach_file.class, forVariable(variable)); } public QAttach_file(Path<? extends Attach_file> path) { super(path.getType(), path.getMetadata()); } public QAttach_file(PathMetadata metadata) { super(Attach_file.class, metadata); } } <file_sep>package com.hs.daumEditorUtil; import java.util.HashMap; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; 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.multipart.MultipartFile; import lombok.extern.java.Log; @RestController @Log public class UploadController2 { @PostMapping("/FileUpload") public @ResponseBody HashMap<String, Object> FileUpload(@RequestParam("Filedata") MultipartFile mf, Model model, HttpSession httpSession) { log.info("FileUploadUtil FileUpload !! "); model.addAttribute("mf", mf); model.addAttribute("httpSession", httpSession); FileUploadUtil fileUploadUtil = new FileUploadUtil(); return fileUploadUtil.execute(model); } @PostMapping(value = "/ImageUpload") public @ResponseBody HashMap<String, Object> ImageUpload(@RequestParam("Filedata") MultipartFile mf, Model model, HttpSession httpSession) { log.info("ImageUpload ImageUpload !! "); model.addAttribute("mf", mf); model.addAttribute("httpSession", httpSession); ImageUploadUtil imageUploadUtil = new ImageUploadUtil(); return imageUploadUtil.execute(model); } } <file_sep>/** * */ /** * @author DoYoung * 한신메디피아 센터소개 */ package com.hs.info.controller;<file_sep> // 위에 처음없는 높이를 제외시켜야하기 때문에 변수선언 var headerHeight = 0; var naviHeight = 0; var fakeHeight = 0; var banner = 0; //네비게이션에 맞는 section var sectionOffsetArray = []; /*문진표 속성들*/ /* 체크박스의 넓이 */ var checkWidth; /* wrapper 넓이 값 */ var checkWrapper; /* wrapper 넓이 값 */ var checkWrapperMinimum; /* wrapper의 margin 값 */ var smallWrapperMargin; /* 체크박스 레이블의 left 값 */ var centerLocater; var centerLocaterMinimum ; var centerInputWrapper; /* wrap width 값 구하기 IE에서 firt-content가 안되기에 */ var itemSetSpan; /* 레이블 칸(병명) - 왼쪽*/ var itemSetSpanMinimun; /* 레이블 칸(병명) - 왼쪽*/ var articleWrapper; /* 진단여부 치료여부 - 오른쪽 */ var articleWrapperMininum; /* 진단여부 치료여부 - 오른쪽 [1개의 로우] */ var paddingLeft; var paddingRight; var choiceItemPadding; /* 질환박스 총넓이 병명(왼쪽) + 치료여부(오른쪽) + 패딩 */ var wrapBigWidth; var wrapMiniWidth; //doyoung 1 $(window).on('load', function() { //세션 offset 좌표값 배열로 너놓기 $('.question-block').each(function(idx, el) { sectionOffsetArray.push($(el).offset().top); }); headerHeight = $('header').outerHeight(); naviHeight = $('nav').height(); banner = $('.questionnaireBanner').height(); fakeHeight = 100; moveScroll(''); layoutQuestion(); }); //doyoung 2 $(window).on('scroll', function() { scrolling($(window).scrollTop()); }); $(function(){ $('.itemSet .articleChoice').hover(function() { $(this).parents('.itemSet').addClass('hoverEffect'); },function(){ $(this).parents('.itemSet').removeClass('hoverEffect'); }); /* 셀렉트 박스 변경시(노멀) */ $('.makeInput').on('select2:select', function (e) { /* 셀렉트박스를 처음 선택할 시 */ if(($(this).parent().next().css('display') == 'none')){ $(this).parent().next().css('display','block'); $(this).parent().removeClass('attention'); } $(this).parents('.articleChoice').find('.createInput').focus(); $(this).parents('.articleChoice').find('.createInput').val(''); }); $('.lastNone').on('select2:select', function (e) { var index = $("option", this).index($("option:selected", this)); $(this).parents('.articleChoice').find('.detail').css('display','none'); if(($(this).parents('.articleChoice').find('.detail').css('display') == 'none') && index!=this.length-1){ $(this).parents('.articleChoice').find('.detail').css('display','block'); $(this).parents('.select-group').removeClass('attention'); } $(this).parents('.articleChoice').find('.createInput').focus(); $(this).parents('.articleChoice').find('.createInput').val(''); }); }); /*doyoung 3*/ $(".researchSelect").on("blur"," .createInput",function(){ var inputValue = $(this).val(); if(inputValue){ var $etc = $(this).parents('.articleChoice').find(".etc"); if($etc){ $etc.val(inputValue); } } }) /* 체크박스 클릭시 셀렉트박스 생성 */ $('.viewSelect').on('click' , function(){ /* 체크박스 클릭 시 */ if($(this).is(":checked")) { if($(this).hasClass('inner')) { $(this).parents('.articleChoice').find('.innerInput').css('display','block'); } if($(this).parents('.articleChoice').find('.select-group').length > 0) { $(this).parents('.articleChoice').find('.select-group').css('display','block'); } }else { if($(this).hasClass('inner')) { $(this).parents('.articleChoice').find('.innerInput').css('display','none'); $(this).parents('.articleChoice').find('.innerInput').val(''); } /* 셀렉트박스 감추기 */ $(this).parents('.articleChoice').find('.select-group').css('display','none'); $(this).parents('.articleChoice').find('.detail').css('display','none'); /* 셀렉트박스 초기화*/ $(this).parents('.articleChoice').find('select.next').val(0); $(this).parents('.articleChoice').find('.createInput').val(''); $('.js-example-basic-single').select2(); } }); /* 버튼마다 해당 문제 보여주기 checkShow */ $(".checkShow").on("click"," .checkUI" ,function(){ var thisClass =$(this).attr("class"); //해당 문제들 hide로 초기화 var target = $(this).attr("class") + "target"; //숨겨진 문제들 감싸고 있는 div id 값 var targetClass =$(this).find("input").attr("class"); $("#"+targetClass + ">div").each(function(){ if(!$(this).hasClass("hide")){ $(this).addClass("hide") } }) //보여줄 문제에 class 값 var targetId = $(this).attr("id"); if($("."+targetId).hasClass("hide")){ $("."+targetId).removeClass("hide"); } }); $('.makeInputOther').on('select2:select', function (e) { /* 셀렉트박스 선택값 index */ var index = $("option", this).index($("option:selected", this)); $(this).parents('.articleChoice').find('.detail').css('display','none'); if(($(this).parents('.articleChoice').find('.detail').css('display') == 'none') && index==this.length-1){ console.log("진입"); console.log(index); console.log(this.length-1); $(this).parents('.articleChoice').find('.detail').css('display','block'); $(this).parents('.select-group').removeClass('attention'); } $(this).parents('.articleChoice').find('.createInput').focus(); $(this).parents('.articleChoice').find('.createInput').val(''); }); /* 기타버튼 클릭시 상세 인풋박스 나타내기 */ $('.checkUI > input.otherInput').on('click' , function() { if ($(this).is(":checked")) { $(this).parents('.checkUI').append('<input type="text" value="" id="" class="write">'); }else { $('.checkUI > input.write').remove(); } }); $('.articleChoice input').on('click' , function(){ /* 라디오 선택문항을 만드는 버튼*/ if($(this).hasClass('nextmakeRadio') && $(this).is(":checked")) { $(this).parents('.questionWrap').next().removeClass('hide'); /* 셀렉트박스 선택문항을 만드는 버튼*/ }else if($(this).hasClass('nextmakeSelect') && $(this).is(":checked")){ $(this).parents('.questionWrap').next().removeClass('hide'); /* 셀렉트박스 초기화*/ $(this).parents('.questionWrap').next().find('.makeInput').find('option:eq(0)').prop("selected", true); $(this).parents('.questionWrap').next().find('.createInput').val(''); $('.js-example-basic-single').select2(); $(this).parents('.questionWrap').next().find('.detail').css('display','none'); if(!$(this).parents('.questionWrap').next().find('.select-group').hasClass('attention')) $(this).parents('.questionWrap').next().find('.select-group').addClass('attention'); /* 항목(라디오)선택시 상세 인풋박스 나타내기 */ }else if($(this).hasClass('nearmakeInput') && $(this).is(":checked")){ $(this).parents('.articleChoice').find('.detailComplex').css('display','block'); $(this).parents('.articleChoice').find('.detail').css('display','block'); if($(this).parents('.articleChoice').next().length > 0) { $(this).parents('.articleChoice').find('.detail input').css('margin','0 10px'); }else { $(this).parents('.articleChoice').find('.detail input').css('margin','0 10px'); } }else{ /* 생성한 선택문항 숨기기 */ if($(this).parents('.questionWrap').hasClass('linked')) { /* 라디오 문항 초기화*/ $(this).parents('.questionWrap').next().find('.checkUI input:radio').prop( "checked", false ); $(this).parents('.questionWrap').next().addClass('hide'); } /* 생성한 상세인풋박스 숨기기 */ if($(this).parents('.questionWrap').find('.nearmakeInput').length > 0){ if($(this).parents('.articleChoice').prev().length > 0) { $(this).parents('.articleChoice').prev().find('.detail input').val(''); $(this).parents('.articleChoice').prev().find('.detail').css('display','none'); $(this).parents('.articleChoice').prev().find('.detailComplex').css('display','none'); } else { $(this).parents('.articleChoice').next().find('.detail input').val(''); $(this).parents('.articleChoice').next().find('.detail').css('display','none'); $(this).parents('.articleChoice').next().find('.detailComplex').css('display','none'); } } } }); /* 병명체크리스트 - 기타 선택시 기타입력(인풋박스) 나타내기 */ $('.others').on('click' , function(){ var $choiceItem = $(this).parents('.choiceItem'); var $choiceItemInput = $choiceItem.find('input'); /* 기타입력 누르면 나오는 메뉴의 넓이값을 부모의 넓이값과 동일시 하기) */ var wrapperWidth = $choiceItem.outerWidth(); /* 체크박스가 중앙정렬되어있으므로 인풋박스도 마진값을 주어 동일한 정렬을 한다. */ var inputMgl = $(this).parents('.choiceItem').find('.checkUI.center').css('left').replace("px",""); /* 인풋박스의 넓이구하기 */ var inputWrapperWidth = $(this).parents('.articleWrapper').outerWidth(); var inputWidth = $(this).parents('.articleChoice').outerWidth(); /* 기타 체크가 하나라도 되어있으면 보여주기*/ if($(this).parents('.articleChoice').next().find('input').is(":checked")||$(this).parents('.articleChoice').prev().find('input').is(":checked")||$(this).is(":checked")) { if($(this).parents('.choiceItem').find('.otherInput').hasClass('hide')) { $choiceItem.find('.otherInput').removeClass('hide'); $choiceItem.find('.otherInput input').focus(); } if($(this).hasClass('center')){ $choiceItem.find('.inputWrapper').css('width',articleWrapper); $choiceItemInput.css('margin-left',centerInputWrapper); }else{ $choiceItem.css('max-width',wrapperWidth); /* 인풋박스 */ if($choiceItem.hasClass('wide')){ var inputWidthWide = inputWrapperWidth - inputMgl; $choiceItemInput.css('max-width',inputWidthWide); }else { $choiceItemInput.css('max-width',inputWidth); } } }else { $choiceItemInput.val(''); $choiceItem.find('.otherInput').addClass('hide'); } }); /* 체크박스 클릭시 셀렉트박스 생성 */ $('.viewSelect').on('click' , function(){ /* 체크박스 클릭 시 */ if($(this).is(":checked")) { /* 인풋박스를 나타내는 클래스 inner 가 있으면*/ if($(this).hasClass('hasInput')) { /* 인풋박스 생성 */ $(this).parents('.articleChoice').find('.innerInput').css('display','block'); } /* 셀렉트 박스가 존재하면 */ if($(this).parents('.articleChoice').find('.select-group').length > 0) { $(this).parents('.articleChoice').find('.select-group').css('display','block'); } }else { /* 인풋박스 감추기 */ if($(this).hasClass('hasInput')) { $(this).parents('.articleChoice').find('.innerInput').css('display','none'); $(this).parents('.articleChoice').find('.innerInput').val(''); } /* 셀렉트박스 감추기 */ $(this).parents('.articleChoice').find('.select-group').css('display','none'); $(this).parents('.articleChoice').find('.detail').css('display','none'); /* 셀렉트박스 초기화*/ $(this).parents('.articleChoice').find('select.makeInput').find('option:eq(0)').prop("selected", true); $(this).parents('.articleChoice').find('.createInput').val(''); $('.js-example-basic-single').select2(); } }); /* 버튼마다 해당 문제 보여주기 checkShow doyoung */ $(".checkShow").on("click"," .checkUI" ,function(){ var thisClass =$(this).attr("class"); //해당 문제들 hide로 초기화 var target = $(this).attr("class") + "target"; //숨겨진 문제들 감싸고 있는 div id 값 var targetClass =$(this).find("input").attr("class"); $("#"+targetClass + ">div").each(function(){ if(!$(this).hasClass("hide")){ $(this).addClass("hide") } //숨길때 값 초기화 $("#"+targetClass + " input[type=radio]").prop("checked",false); }); //보여줄 문제에 class 값 var targetId = $(this).attr("id"); if($("."+targetId).hasClass("hide")){ $("."+targetId).removeClass("hide"); } }); /* error 풀기 doyoung 4*/ $(".articleChoice input").on("change",function(){ var inspectionVal = $(this).val(); if(inspectionVal){ var $questionWrap = $(this).parents(".questionWrap"); if($questionWrap.hasClass('hasError')){ $questionWrap.removeClass("hasError"); } } }); /* error 풀기 doyoung 5*/ $(".articleChoice select").on("change",function(){ var inspectionVal = $(this).val(); if(inspectionVal){ var $questionWrap = $(this).parents(".questionWrap"); if($questionWrap.hasClass('hasError')){ $questionWrap.removeClass("hasError"); } } }); /* error 풀기 doyoung 6*/ $(".questionWrap textarea").on("blur",function(){ var inspectionVal = $(this).val(); var $questionWrap = $(this).parents(".questionWrap"); if(inspectionVal){ if($questionWrap.hasClass('hasError')){ $questionWrap.removeClass("hasError"); } }else{ if(!$questionWrap.hasClass('hasError')){ $questionWrap.addClass("hasError"); } } }); /* 체크할 값의 태그객체 , 채크한 값 doyoung 6*/ function questionValidation(obj,inspectionVal){ var $questionWrap = obj.closest(".questionWrap"); if(inspectionVal){ if($questionWrap.hasClass('hasError')){ $questionWrap.removeClass("hasError"); } return true; }else{ if(!$questionWrap.hasClass('hasError')){ $questionWrap.addClass("hasError"); } var offSetTop = $questionWrap.offset().top; TweenMax.to($("html, body"),0.3, {scrollTop:offSetTop - 300, ease:"slow"}); return false; } } //문진표 레이아웃 function layoutQuestion(){ /* 체크박스 가운데 정렬하기 */ if($('.choiceItem').length > 0) { /* 체크박스의 넓이 */ checkWidth = $('.checkUI span.checkmark').outerWidth(); /* wrapper 넓이 값 */ checkWrapper =$('.itemSet .articleChoice').width(); /* wrapper 넓이 값 */ checkWrapperMinimum =$('.mini .itemSet .articleChoice').width(); /* wrapper의 margin 값 */ smallWrapperMargin = parseInt($('.checkUI.center').css('margin-right')); /* 체크박스 레이블의 left 값 */ centerLocater = parseInt((checkWrapper - checkWidth)/2)-smallWrapperMargin; centerLocaterMinimum = parseInt((checkWrapperMinimum - checkWidth)/2) -smallWrapperMargin; $('.checkUI.center').css('left',centerLocater); $('.mini .checkUI.center').css('left',centerLocaterMinimum); centerInputWrapper = parseInt((checkWrapper - checkWidth)/2); /* wrap width 값 구하기 IE에서 firt-content가 안되기에 */ itemSetSpan = $('.itemSet p.material').outerWidth(); /* 레이블 칸(병명) - 왼쪽*/ itemSetSpanMinimun = $('.mini .itemSet p.material').outerWidth(); /* 레이블 칸(병명) - 왼쪽*/ articleWrapper = $('.itemSet .articleWrapper').outerWidth(); /* 진단여부 치료여부 - 오른쪽 */ articleWrapperMininum = $('.mini .itemSet .articleWrapper').outerWidth(); /* 진단여부 치료여부 - 오른쪽 [1개의 로우] */ paddingLeft =Math.ceil($('.choiceItem .itemSet').css('padding-left').replace("px","")); paddingRight =Math.ceil($('.choiceItem .itemSet').css('padding-right').replace("px","")); choiceItemPadding =parseInt(paddingLeft + paddingRight); /* 패딩값 */ /* 질환박스 총넓이 병명(왼쪽) + 치료여부(오른쪽) + 패딩 */ wrapBigWidth = parseInt(itemSetSpan + articleWrapper + choiceItemPadding); wrapMiniWidth = parseInt(itemSetSpanMinimun + articleWrapperMininum + choiceItemPadding); $('.choiceItem.wide').css('max-width',wrapBigWidth); $('.choiceItem.mini').css('max-width',wrapMiniWidth); } $('.js-example-basic-single').select2(); $('.questionnaireViewFormCard').css('opacity','1'); } // 스크롤 함수 - 네비 doyoung 7 function scrolling(currentScroll, transitionFlag) { //target var animTriggerPoint = currentScroll + $(window).height() / 2; // var animTriggerPoint = currentScroll + $(window).height(); if (transitionFlag) { var transition = 'background 0.46s ease-out'; } else { var transition = ''; } //해당 좌표값 아래로 내려가면 NAV 바 전환 if (currentScroll >= ($('.Presession').height() + 220)) { $('.questionnaireNavWrap').addClass('is-sticky'); } else { $('.questionnaireNavWrap').removeClass('is-sticky'); } //NAV바에 active 주기 if(currentScroll <= sectionOffsetArray[0] - (banner +headerHeight + naviHeight -fakeHeight)) { var activeTap = ""; $('.questionnaireNav .tap').removeClass('is-active'); return; } else if (currentScroll > (sectionOffsetArray[0] - (banner +headerHeight + naviHeight -fakeHeight)) && currentScroll < sectionOffsetArray[1] - (banner +headerHeight + naviHeight -fakeHeight)) { // 현재 섹션 1번 var activeTap = "cal1"; } else if (currentScroll > (sectionOffsetArray[1] - (banner +headerHeight + naviHeight -fakeHeight)) && currentScroll < sectionOffsetArray[2] - (banner +headerHeight + naviHeight -fakeHeight)) { // 현재 섹션 2번 var activeTap = "cal2"; } else if (currentScroll > (sectionOffsetArray[2] - (banner +headerHeight + naviHeight -fakeHeight))) { // 현재 섹션 3번 var activeTap = "cal3"; } $('.questionnaireNav .tap').removeClass('is-active'); $('.questionnaireNav .tap.' + activeTap).addClass('is-active'); } //해당 NAV바와 연결된 section 으로 이동시키기 doyoung 8 function moveScroll(param) { switch (param) { case "cal1": $('body').animate({ scrollTop: sectionOffsetArray[0] -60 }, 500); break; case "cal2": $('html, body').animate({ scrollTop: sectionOffsetArray[1] - 60 }, 500); break; case "cal3": $('html, body').animate({ scrollTop: sectionOffsetArray[2] - 60 }, 500); break; } } <file_sep> /* 전역변수 선언 flag */ var pwFlag = false; var emailFlag = false; var dateFlag = false; var idFlag = false; var phoneFlag = false; var nameFlag = false; function submitBtnSwitch(){ console.log("pwFlag :"+pwFlag); console.log("emailFlag :"+emailFlag); console.log("dateFlag :"+dateFlag); console.log("idFlag :"+idFlag); console.log("phoneFlag :"+phoneFlag); console.log("nameFlag :"+nameFlag); /* var dateStr= $("#birthDate").val(); checkPswd1(); checkName(); checkDate(dateStr); checkPhone(); checkEmail(); checkId("first");*/ if(pwFlag && emailFlag && dateFlag && idFlag && phoneFlag && nameFlag){ console.log("addClass :: active"); $("#submitBtn").addClass("active"); }else{ console.log("removeClass ::active"); $("#submitBtn").removeClass("active"); } } $(function(){ var dateStr= $("#birthDate").val(); checkPswd1(); checkName(); checkDate(dateStr); checkPhone(); checkEmail(); checkId("first"); $("#pswd2").addClass("errorBorder"); $("#pswd2Msg").text("*비밀번호 확인을 반드시 입력해주세요.") $("#pswd2Msg").css("display","inline"); /* validation */ /* 비밀번호 유효성 체크*/ $("#pswd1").blur(function() { $(".passwordFocusWrap").hide(); pwFlag = false; checkPswd1(); /*pswd1 띠었을 때 pswd2 랑 맞는지 안맞는지*/ var pswd2 = $("#pswd2").val(); var pswd1 = $("#pswd1").val(); if($("#pswd2").val().length > 1){ if(pswd2 == pswd1){ $("#pswd2").parent().addClass("int_pass_check2"); $("#pswd2").removeClass("errorBorder"); $("#pswd2Msg").css("display","none"); }else{ $("#pswd2").addClass("errorBorder"); $("#pswd2").removeClass("int_pass_check2"); $("#pswd2Msg").text("*비밀번호가 일치하지 않습니다.") $("#pswd2Msg").css("display","inline"); } } submitBtnSwitch(); }).keypress(function(event) { checkCapslock(event); }) /*id 확인*/ $("#id").blur(function() { idFlag =false; checkId("first"); if($("#pswd1Img").hasClass("int_pass_step4")){ pwFlag =false; checkPswd1(); checkingPw($("#pswd1").val()); } submitBtnSwitch() }); /*이름 한글체크*/ $("#name").blur(function() { nameFlag = false; checkName(); submitBtnSwitch() }); /*생년월일 유효성 체크*/ $("#birthDate").blur(function() { dateFlag = false; var dateStr= $("#birthDate").val(); checkDate(dateStr); submitBtnSwitch() }); /* 휴대폰 번호 유효성 체크 */ $("#phone").blur(function(){ phoneFlag = false; checkPhone(); submitBtnSwitch() }) /* 이메일 유효성 체크*/ $("#email").blur(function(){ emailFlag = false; checkEmail(); submitBtnSwitch(); }) /* 비밀번호 유동적 유효성 체크*/ $( "#pswd1" ).focus(function() { $(".passwordFocusWrap").show(); }); /*password2 확인*/ $('#pswd2').blur(function(){ var pswd2 = $("#pswd2").val(); var pswd1 = $("#pswd1").val(); if($("#pswd2").val().length > 1){ if(pswd2 == pswd1){ $("#pswd2").addClass("int_pass_check2"); $("#pswd2").removeClass("errorBorder"); $("#pswd2Msg").css("display","none"); }else{ $("#pswd2").addClass("errorBorder"); $("#pswd2").removeClass("int_pass_check2"); $("#pswd2Msg").text("*비밀번호가 일치하지 않습니다.") $("#pswd2Msg").css("display","inline"); } }else{ $("#pswd2").addClass("errorBorder"); $("#pswd2Msg").text("*비밀번호 확인을 반드시 입력해주세요.") $("#pswd2Msg").css("display","inline"); } }) $('#phone').on('keyup', function(event){ var phone = this.value.trim(); this.value = autoDashPhoneNumber(phone) ; }); $('#birthDate').on('keyup', function(event){ var birthday = this.value.trim(); this.value = autoDashDate(birthday) ; }); $('.js-example-basic-single').select2(); $('.joinStatus .rightProcedure .wrapperProcedure .boxProcedure:nth-of-type(2)').addClass('active'); $('.js-example-basic-single').on('change', function () { var emailSelect = $('.js-example-basic-single').val(); $('.memberJoin .article.email span.ps_box.borderNone input#email2').val(emailSelect); }); $('span.ps_box input').focus(function(){ $(this).parent().addClass("press"); }); $('span.ps_box input').blur(function(){ $('span.ps_box input').parent().removeClass("press"); }); $('span.ps_box.borderNone input').focus(function(){ $(this).addClass("press"); }); $('span.ps_box.borderNone input').blur(function(){ $('span.ps_box.borderNone input.press').removeClass("press"); }); }); function checkPswd1() { if(pwFlag) return true; var id = $("#id").val(); var pw = $("#pswd1").val(); var oImg = $("#pswd1Img"); var oSpan = $("#pswd1Span"); var oMsg = $("#pswd1Msg"); if (pw == "") { showPasswd1ImgByStep(oImg, oSpan, 1); showErrorMsg(oMsg,"*필수 정보입니다."); return false; } if (isValidPasswd(pw) != true) { showPasswd1ImgByStep(oImg, oSpan, 1); showErrorMsg(oMsg,"*8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요."); return false; } if (id == pw) { console.log("id == pw") showPasswd1ImgByStep(oImg, oSpan, 1); showErrorMsg(oMsg,"*아이디와 다른 비밀번호를 사용하세요."); return false; } pwFlag = true; showPasswd1ImgByStep(oImg, oSpan, 4); hideMsg(oMsg); return true; } /* * 유동적 패스워드 확인 */ function checkingPw(str){ $(".passwordFocusWrap").show(); var oImg = $("#pswd1Img"); var oSpan = $("#pswd1Span"); var checkingPw = true; var passLevel = 1; var cnt = 0; if (str == "") { checkingPw = false; } /* check whether input value is included space or not */ var retVal = checkSpace(str); if (retVal) { checkingPw = false; } /* 8문자 이상 */ var checkLength = $("#checkLength"); if (str.length < 8) { checkingPw = false; var obj = $("#checkLength") fail(checkLength); }else{ success(checkLength); passLevel++; } for (var i = 0; i < str.length; ++i) { if (str.charAt(0) == str.substring(i, i + 1)) ++cnt; } if (cnt == str.length) { checkingPw = false; } /* 패턴검사 */ var checkPattern = $("#checkPattern"); var isPW = /^[A-Za-z0-9`\-=\\\[\];',\./~!@#\$%\^&\*\(\)_\+|\{\}:"<>\?]{8,16}$/; if (!isPW.test(str)) { checkingPw = false; fail(checkPattern); }else{ success(checkPattern); passLevel++; } var checkId = $("#checkId"); /*console.log("checkId :: id <- " + id +" pswd1 "+ str);*/ if($("#id").val() == str){ checkingPw = false; fail(checkId); }else{ success(checkId); passLevel++; } showPasswd1ImgByStep(oImg, oSpan, passLevel); if(checkingPw){ $(".passwordFocusWrap").hide(); } } function showPasswd1ImgByStep(oImg, oSpan, step) { if("IE8" == "") { return false; } if(step == 1) { oImg.attr("class", "ps_box int_pass_step1"); } else if(step == 2) { oImg.attr("class", "ps_box int_pass_step2"); } else if(step == 3) { oImg.attr("class", "ps_box int_pass_step3"); } else if(step == 4) { oImg.attr("class", "ps_box int_pass_step4"); } else { oImg.attr("class", "ps_box int_pass"); } } function checkCapslock(e) { var myKeyCode = 0; var myShiftKey = false; if (window.event) { // IE myKeyCode = e.keyCode; myShiftKey = e.shiftKey; } else if (e.which) { // netscape ff opera myKeyCode = e.which; myShiftKey = isShift; } var oMsg = $("#pswd1Msg"); if ((myKeyCode >= 65 && myKeyCode <= 90) && !myShiftKey) { showErrorMsg(oMsg,"Caps Lock이 켜져 있습니다."); } else if ((myKeyCode >= 97 && myKeyCode <= 122) && myShiftKey) { showErrorMsg(oMsg,"Caps Lock이 켜져 있습니다."); } else { hideMsg(oMsg); } } function checkSpace(str) { /*console.log("checkSpace :: "+str);*/ /* str= str.toString(); */ if (str.search(/\s/) != -1) { return true; } else { return false; } } function checkEmail() { if(emailFlag) return true; var email = $("#email").val(); var oMsg = $("#emailMsg"); if (email == "") { showErrorMsg(oMsg,"*이메일을 반드시 입력해주세요."); return true; } var isEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var isHan = /[ㄱ-ㅎ가-힣]/g; if (!isEmail.test(email) || isHan.test(email)) { showErrorMsg(oMsg,"*이메일 주소를 다시 확인해주세요."); return false; } hideMsg(oMsg); emailFlag = true; return true; } function checkDate(dateStr) { if(dateFlag) return true; var year = Number(dateStr.substr(0,4)); var month = Number(dateStr.substr(5,2)); var day = Number(dateStr.substr(8,2)); var today = new Date(); // 날자 변수 선언 var yearNow = today.getFullYear(); var adultYear = yearNow-150; var oMsg = $("#dateMsg"); if ( dateStr == "") { showErrorMsg(oMsg,"*생년월일을 반드시 입력해주세요."); return false; } if (adultYear > year){ showErrorMsg(oMsg,"*년도를 확인하세요. "+adultYear+"년생 이전 출생자만 등록 가능합니다."); return false; } if (month < 1 || month > 12) { showErrorMsg(oMsg,"*달은 1월부터 12월까지 입력 가능합니다."); return false; } if (day < 1 || day > 31) { showErrorMsg(oMsg,"*일은 1일부터 31일까지 입력가능합니다."); return false; } if ((month==4 || month==6 || month==9 || month==11) && day==31) { showErrorMsg(month+"*월은 31일이 존재하지 않습니다."); return false; } if (month == 2) { var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day==29 && !isleap)) { showErrorMsg("* "+year + "년 2월은 " + day + "일이 없습니다."); return false; } } hideMsg(oMsg); dateFlag = true; return true; } /*checkId*/ function checkId(event) { if(idFlag) return true; var id = $("#id").val(); var oMsg = $("#idMsg"); if ( id == "") { showErrorMsg(oMsg,"*아이디 값을 반드시 입력해주세요."); return false; } var isID = /^[a-z0-9][a-z0-9_\-]{4,19}$/; if (!isID.test(id)) { showErrorMsg(oMsg,"*5~20자의 영문 소문자, 숫자와 특수기호(_),(-)만 사용 가능합니다."); return false; } //아이디 중복 검사. var params = { "member_id" : id, }; $.ajax({ type : "post", url : "/check/idRepu", data : params, dataType : "json", success : function(data) { var check = data.check; if(check != "checked"){ showErrorMsg(oMsg,"*이미 사용중인 아이디입니다."); }else{ hideMsg(oMsg); idFlag = true; } }, error : function(args) { alert("에러 발생" + args); } }); hideMsg(oMsg) idFlag = true; } /* 전역변수 선언 flag */ function checkPhone() { if(phoneFlag) return true; var oMsg = $("#phoneMsg"); var phone = $("#phone").val(); if (phone == "") { showErrorMsg(oMsg,"*휴대폰 번호를 정확하게 입력해주세요."); return false; } hideMsg(oMsg); phoneFlag = true; return true; } // 한글 이름 체크 function checkName() { if(nameFlag) return true; var oMsg = $("#nameMsg"); var nonchar = /[^가-힣a-zA-Z0-9]/gi; var name = $("#name").val(); if (name == "") { showErrorMsg(oMsg,"*이름을 정확하게 입력해주세요."); return false; } /* if (name != "" && nonchar.test(name)) { showErrorMsg(oMsg,"*이름을 정확하게 입력해주세요. (특수기호, 공백 사용 불가)"); return false; } */ var isHan = /[ㄱ-ㅎ가-힣]/g; if(!name != "" || !isHan.test(name)){ showErrorMsg(oMsg,"* 한글만 입력이 가능합니다."); return false; } nameFlag = true; hideMsg(oMsg); return true; } // 영어 이름 체크 function checkEngName() { if(nameFlag) return true; var oMsg = $("#nameMsg"); var nonchar = /[^가-힣a-zA-Z0-9]/gi; var name = $("#name").val(); if (name == "") { showErrorMsg(oMsg,"*이름을 정확하게 입력해주세요."); return false; } if (name != "" && nonchar.test(name)) { showErrorMsg(oMsg,"*이름을 정확하게 입력해주세요. (특수기호, 공백 사용 불가)"); return false; } var isEng = /[0-9]|[^\!-z]/gi; if(name != "" && isEng.test(name)){ showErrorMsg(oMsg,"* 영문만 입력이 가능합니다."); return false; } nameFlag = true; hideMsg(oMsg); return true; } function showErrorMsg(obj, msg) { obj.attr("class", "error_next_box"); obj.prev().addClass('errorBorder'); obj.html(msg); obj.show(); } function showErrorMsg2(obj, msg) { obj.attr("class", "error_next_box"); obj.prev().prev().addClass('errorBorder'); obj.html(msg); obj.show(); } function showSuccessMsg(obj, msg) { obj.attr("class", "error_next_box green"); obj.html(msg); obj.show(); } function hideMsg(obj) { obj.prev().removeClass('errorBorder'); obj.hide(); } function hideMsg2(obj) { obj.prev().prev().removeClass('errorBorder'); obj.hide(); } function isValidPasswd(str){ var cnt = 0; if (str == "") { return false; } /* check whether input value is included space or not */ var retVal = checkSpace(str); if (retVal) { return false; } if (str.length < 8) { return false; } for (var i = 0; i < str.length; ++i) { if (str.charAt(0) == str.substring(i, i + 1)) ++cnt; } if (cnt == str.length) { return false; } var isPW = /^[A-Za-z0-9`\-=\\\[\];',\./~!@#\$%\^&\*\(\)_\+|\{\}:"<>\?]{8,16}$/; if (!isPW.test(str)) { return false; } return true; } function success(obj){ obj.removeClass("password-pass1"); obj.addClass("password-pass2"); } function fail(obj){ obj.removeClass("password-pass2"); obj.addClass("password-pass1"); } /** * 숫자만 입력가능하게 하는 함수 */ function fn_onlyNumber(event){ event = event || window.event; var keyID = (event.which) ? event.which : event.keyCode; if ( (keyID >= 48 && keyID <= 57) || (keyID >= 96 && keyID <= 105) || keyID == 8 || keyID == 9 || keyID == 46 || keyID == 37 || keyID == 39 ) return; else return false; } /** * 문자를 제거하는 함수 */ function removeChar(event) { event = event || window.event; var keyID = (event.which) ? event.which : event.keyCode; if ( keyID == 8 || keyID == 46 || keyID == 37 || keyID == 39 ) return; else event.target.value = event.target.value.replace(/[^0-9]/g, ""); } /** * 핸드폰 번호 입력할 때 자동대시 * 11자리 : 000-0000-0000 * 10자리 : 000-000-0000 */ function autoDashPhoneNumber(str){ str = str.replace(/[^0-9]/g, ''); var tmp = ''; if( str.length < 4){ return str; }else if(str.length < 7){ tmp += str.substr(0, 3); tmp += '-'; tmp += str.substr(3); return tmp; }else if(str.length < 11){ tmp += str.substr(0, 3); tmp += '-'; tmp += str.substr(3, 3); tmp += '-'; tmp += str.substr(6); return tmp; }else{ tmp += str.substr(0, 3); tmp += '-'; tmp += str.substr(3, 4); tmp += '-'; tmp += str.substr(7); return tmp; } return str; } /** * 생일 입력할 때 자동대시 */ function autoDashDate(str){ str = str.replace(/[^0-9]/g, ''); var tmp = ''; if( str.length < 5 ){ return str; } else if(str.length < 7){ tmp += str.substr(0, 4); tmp += '-'; tmp += str.substr(4, 5); return tmp; } else { tmp += str.substr(0, 4); tmp += '-'; tmp += str.substr(4, 2); tmp += '-'; tmp += str.substr(6, 2); return tmp; } } function autoDashYYYYMMDate(str){ return autoDashDate(str).substr(0, 7); } <file_sep>package com.hs.screening.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/screening") public class ScreeningViewC { /* 분야별검진*/ //학생검진 //학생검진은? @GetMapping("/student") public void studentView() {} //성장판 검사 @GetMapping("/growthPlate") public void growthPlateView() {} //알레르기 검사 @GetMapping("/allergy") public void allergyView() {} //학생정밀종합검진 @GetMapping("/detailed") public void detailedView() {} //이민/유학검진 @GetMapping("/abroad") public void abroadView() {} //외국인근로자마약검진 @GetMapping("/drug") public void drugView() {} //채용신체검사 @GetMapping("/recruit") public void recruitView() {} //운전면허적성검사 @GetMapping("/drive") public void driveView() {} //직업환경의학 @GetMapping("/work") public void workView() {} } <file_sep>/** * */ /** * @author DoYoung * 한신메디피아 분야별검진 */ package com.hs.screening.controller;<file_sep>/** * */ /** * @author <NAME> * */ package com.hs.young;<file_sep>/*$(function(){ var navNo = $(".pageTitle").attr("id"); var viewName = "<c:out value ='${viewName}' />"; $("#sideContent #"+navNo).next().slideDown( "fast", function() { // Animation complete. alert("viewName :: "+ viewName); $("."+viewName).addClass("active"); }); })*/
f3735fb6937862df247a3ba262ddb65e8d4bfdc9
[ "JavaScript", "Java" ]
23
Java
doyoung0205/HS2
29ad2bc6c4173d9431c80834ef841223ce4ed93d
055174f9d721f60427babda7efca461be17577b3
refs/heads/master
<file_sep>var directive = angular.module('myApp.directive',[]); directive.directive('autoFocusWhen',['$timeout',function($timeout){ return { require: '?ngModel', restrict: 'A', scope: { autoFocusWhen : '=', ngModel: '=' }, link:function(scope,element,attrs,controller){ scope.$watch('autoFocusWhen',function(newValue){ if (newValue) { $timeout(function(){ element[0].focus(); scope.autoFocusWhen = false; }) } }) element.on('blur keyup change', function() { scope.$apply(read); }); function read() { scope.ngModel = element.val(); } } } }]); <file_sep><?php require("class.php"); $sql = "select * from tb_affiche"; $pagesize = 4; // 每页显示几条信息 $nowpage = $_GET['page']; $result = $setpage->ShowData($sql,$conn,$pagesize,$nowpage); $left = $setpage->ShowPage('记录','条',true); $right = $setpage->ShowPage('记录','条',false); $array = array('list'=>$result,'left'=>$left,'right'=>$right); echo json_encode($array); ?><file_sep><?php class ConnDB{ var $dbtype; var $host; var $user; var $pwd; var $dbname; //构造方法 function ConnDB($dbtype,$host,$user,$pwd,$dbname){ $this->dbtype=$dbtype; $this->host=$host; $this->user=$user; $this->pwd=$pwd; $this->dbname=$dbname; } //实现数据库的连接并返回连接对象 function GetConnId(){ if($this->dbtype=="mysql" || $this->dbtype=="mssql"){ $dsn="$this->dbtype:host=$this->host;dbname=$this->dbname"; }else{ $dsn="$this->dbtype:dbname=$this->dbname"; } try { $conn = new PDO($dsn, $this->user, $this->pwd); //初始化一个PDO对象,就是创建了数据库连接对象$pdo $conn->query("set names utf8"); return $conn; } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } } } //数据库管理类 class AdminDB{ function ExecSQL($sqlstr,$conn){ $sqltype=strtolower(substr(trim($sqlstr),0,6)); $rs=$conn->prepare($sqlstr); //准备查询语句 $rs->execute(); //执行查询语句,并返回结果集 if($sqltype=="select"){ $array=$rs->fetchAll(PDO::FETCH_ASSOC); //获取结果集中的所有数据 if(count($array)==0 || $rs==false) return false; else return $array; }elseif ($sqltype=="update" || $sqltype=="insert" || $sqltype=="delete"){ if($rs) return true; else return false; } } } class SepPage{ var $pagesize; var $nowpage; var $array; var $conn; var $sqlstr; function ShowData($sqlstr,$conn,$pagesize,$nowpage){ //定义方法 if(!isset($nowpage) || $nowpage=="") //判断变量值是否为空 $this->nowpage=1; //定义每页起始页 else $this->nowpage=$nowpage; $this->pagesize=$pagesize; //定义每页输出的记录数 $this->conn=$conn; //连接数据库返回的标识 $this->sqlstr=$sqlstr; //执行的查询语句 $offset=($this->nowpage-1)*$this->pagesize; $sql=$this->sqlstr." limit $offset, $this->pagesize"; $result=$this->conn->prepare($sql); //准备查询语句 $result->execute(); //执行查询语句,并返回结果集 $this->array=$result->fetchAll(PDO::FETCH_ASSOC); //获取结果集中的所有数据 if(count($this->array)==0 || $this->array==false) return false; else return $this->array; } function ShowPage($contentname,$utits,$class){ $res=$this->conn->prepare($this->sqlstr); //准备查询语句 $res->execute(); //执行查询语句,并返回结果集 $this->array=$res->fetchAll(PDO::FETCH_ASSOC); //获取结果集中的所有数据 $record=count($this->array); //统计记录总数 $pagecount=ceil($record/$this->pagesize); //计算共有几页 $strs= "页次: ".$this->nowpage."/".$pagecount."页 ".$contentname." ".$record." ".$utits; if($this->nowpage!=1) $str="<a href='#/setPage/1'>首页</a>&nbsp;<a href='#/setPage/".($this->nowpage-1)."'>上一页</a>"; else $str="<a href='#/setPage/".($this->nowpage+1)."'>下一页</a>&nbsp;<a href='#/setPage/".$pagecount."'>尾页</a>"; if(count($this->array)==0 || $this->array==false) return "无数据!"; else if($class){ return $strs; }else{ return $str; } } } $connobj=new ConnDB("mysql","localhost","root","","db_database18");//数据库连接类实例化 $conn=$connobj->GetConnId(); //执行连接操作,返回连接标识 $admindb=new AdminDB();//数据库操作类实例化 $setpage = new SepPage(); ?><file_sep>var app = angular.module('myApp',['myApp.service','myApp.directive']); app.config(['$routeProvider',function($routeProvider){ $routeProvider.when('/',{ controller: 'search', templateUrl: 'views/search.html' }).when('/editor',{ controller: 'editor', templateUrl: 'views/editor.html' }).when('/add',{ controller: 'addNote', templateUrl: 'views/add.html' }).when('/modify/:id',{ controller: 'modify', templateUrl: 'views/modify.html' }).when('/delete',{ controller: 'deleteNote', templateUrl: 'views/delete.html' }).when('/intercept',{ controller: 'intercept', templateUrl: 'views/intercept.html' }).when('/setPage/:page',{ controller: 'setPage', templateUrl: 'views/setPage.html' }).otherwise({redirectTo:'/'}) }]) app.controller('search',['$scope','loadAllinfo','searchInfo',function($scope,loadAllinfo,searchInfo){ loadAllinfo().then(function(data){ $scope.allInto = data; }) $scope.search = function(){ if(!$scope.keyword){ alert("请输入关键字"); return } searchInfo($scope.keyword).then(function(info){ $scope.allInto = info }) } }]) app.controller('intercept',['$scope','loadAllinfo',function($scope,loadAllinfo){ loadAllinfo().then(function(data){ $scope.allInto = data; }) }]) app.controller('setPage',['$scope','setPages',function($scope,setPages){ setPages().then(function(data){ $scope.allInto = data.list; $scope.left = data.left; $scope.right = data.right; }) }]) app.controller('deleteNote',['$scope','loadAllinfo','loadinfo','removeNote','$location','searchInfo',function($scope,loadAllinfo,loadinfo,removeNote,$location,searchInfo){ loadAllinfo().then(function(data){ $scope.allInto = data; }) $scope.remove = function(id){ $scope.id = id; if($scope.id){ removeNote($scope.id).then(function(dl){ if(dl){ alert("成功删除"); loadAllinfo().then(function(data){ $scope.allInto = data; }) } }) } } $scope.search = function(){ if(!$scope.keyword){ alert("请输入关键字"); return } searchInfo($scope.keyword).then(function(info){ $scope.allInto = info }) } }]) app.controller('addNote',['$scope','insert','$location',function($scope,insert,$location){ $scope.check = function(){ $scope.focusTitle = false; if($scope.txt_title && $scope.txt_content){ insert($scope.txt_title,$scope.txt_content).then(function(one){ if(one){ $location.path("/"); } }) }else{ alert("不能为空"); $scope.focusTitle = true $scope.txt_title = '' $scope.txt_content = '' return } } }]) app.controller('editor',['$scope','loadAllinfo','searchInfo',function($scope,loadAllinfo,searchInfo){ loadAllinfo().then(function(data){ $scope.allInto = data; }) $scope.search = function(){ if(!$scope.keyword){ alert("请输入关键字"); return } searchInfo($scope.keyword).then(function(info){ $scope.allInto = info }) } }]) app.controller('modify',['$scope','loadinfo','$location','updateNote',function($scope,loadinfo,$location,updateNote){ loadinfo().then(function(data){ $scope.txt_title = data.title $scope.txt_content = data.content $scope.id = data.id }) $scope.check = function(){ $scope.focusTitle = false; if($scope.txt_title && $scope.txt_content){ updateNote($scope.txt_content,$scope.txt_title,$scope.id).then(function(rs){ if(rs){ $location.path("/"); } }) }else{ alert("不能为空"); $scope.focusTitle = true $scope.txt_title = '' $scope.txt_content = '' return } } }])<file_sep><?php require("class.php"); $id = $_POST['id']; $delete = "delete from tb_affiche where id='$id'"; $tb = $admindb->ExecSQL($delete,$conn); echo $tb; ?><file_sep><?php require("class.php"); $content = $_POST['content']; $title = $_POST['title']; $id = $_POST['id']; $update = "update tb_affiche set title='$title',content='$content' where id='$id'"; $tb = $admindb->ExecSQL($update,$conn); echo $tb; ?><file_sep><?php require("class.php"); $sql = "select * from tb_affiche order by id desc limit 5"; $result = $admindb->ExecSQL($sql,$conn); echo json_encode($result); ?><file_sep><?php require("class.php"); $keyword = $_GET['keyword']; $sql = "select * from tb_affiche where title like '%".$keyword."%' or content like '%".$keyword."%'"; $result = $admindb->ExecSQL($sql,$conn); echo json_encode($result); ?><file_sep><?php require("class.php"); $content = $_POST['content']; $title = $_POST['title']; $createtime = date("Y-m-d H:i:s"); $insert = "insert into tb_affiche(title,content,createtime) values('$title','$content','$createtime')"; $tb = $admindb->ExecSQL($insert,$conn); if(!$tb){ return false; } echo $tb; ?><file_sep>-- phpMyAdmin SQL Dump -- version 2.11.6 -- http://www.phpmyadmin.net -- -- 主机: localhost -- 生成日期: 2015 年 12 月 23 日 06:04 -- 服务器版本: 5.0.51 -- PHP 版本: 5.2.6 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 */; -- -- 数据库: `db_database18` -- -- -------------------------------------------------------- -- -- 表的结构 `tb_affiche` -- CREATE TABLE `tb_affiche` ( `id` int(4) NOT NULL auto_increment, `title` varchar(200) character set gb2312 NOT NULL, `content` mediumtext character set gb2312 NOT NULL, `createtime` datetime NOT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ; -- -- 导出表中的数据 `tb_affiche` -- INSERT INTO `tb_affiche` (`id`, `title`, `content`, `createtime`) VALUES (8, '为提高编程者的编程水平,特推出视频讲解!', '互动媒体学习社区网为提高编程者的编程水平,特推出50个项目的视频讲解!对源码程序进行剖析!', '2008-04-01 14:14:38'), (25, '《PHP项目开发全程实录》即将出版啦!', '广大的读者朋友您好,《PHP项目开发全程实录》08年4月中旬即将出版发行!敬请关注!', '2008-04-02 09:37:43'), (2, 'Happy Every Day', 'Every day ! in Every Day! I am getting better and better!ddddddd', '2008-04-02 15:41:45'), (43, '真的好想你', '真的好想你真的好想你真的好想你', '2015-12-16 07:29:39'), (44, '修改主题', '就杀敌发斯蒂芬就杀敌发斯蒂芬就杀敌发斯蒂芬就杀敌发斯蒂芬', '2015-12-16 07:34:01'); <file_sep># 后台管理系统(angularjs + php + mysql) 在此项目中遇到的坑: 在添加页面(add.html)的模板中的 &lt;input name="txt_title" type="text" size="40" auto-focus-when="focusTitle" ng-model="txt_title &gt; 当指令(directive)和ng-model同时使用时,在控制器中无法直接通过 $scope.txt_title 获取页面的值, 而需要在指令中 通过scope.$apply来传播页面输入的数据,代码如下 return { require: '?ngModel', restrict: 'A', scope: { autoFocusWhen : '=', ngModel: '=' }, link:function(scope,element,attrs,controller){ scope.$watch('autoFocusWhen',function(newValue){ if (newValue) { $timeout(function(){ element[0].focus(); scope.autoFocusWhen = false; }) } }) element.on('blur keyup change', function() { scope.$apply(read); }); function read() { scope.ngModel = element.val(); } } } 在使用Angular时需要注意以下几点: 1.ngView只能有一个,不能嵌套多个视图 2.在directive里面操作DOM的代码 3.Angularjs更多的是适合于CRUD的管理系统开发。 <file_sep><?php require("class.php"); $id = $_GET['id']; if(!$id) return false; $sql = "select * from tb_affiche where id=$id "; $result = $admindb->ExecSQL($sql,$conn); echo json_encode($result); ?>
0a538d56d6d12f782620c12ffd490cb8932cc9bc
[ "JavaScript", "SQL", "Markdown", "PHP" ]
12
JavaScript
alwaysrunning/Angularjs-php-mysql
078687097c5e65b5c81fdb679f477a50127010f9
0e63c756bf7cec4352a1f91f9d0c44a2ba8cb6a4
refs/heads/master
<file_sep> int get_one(); <file_sep> int get_one() { return 1; } <file_sep>[package] name = "rvtune" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] build = "build.rs" description = "Rust binding for the Intel FFI SEAPI for profiling" [build-dependencies] bindgen = "0.47.1" [dependencies] libc = "^0.2" <file_sep>extern crate bindgen; use std::env; use std::path::PathBuf; const HEADERS_DIR: &'static str = "intel_headers"; pub fn main() { // Finds the header files let mut header = PathBuf::from(HEADERS_DIR); header.push("wrapper.h"); println!("{} {}", "cargo:rustc-flags= -L", HEADERS_DIR); println!("cargo:rustc-link-lib=static=ittnotify"); let bindings = bindgen::Builder::default() .header(header.to_str().unwrap()) .layout_tests(false) .generate_comments(false) .prepend_enum_name(false) .rustfmt_bindings(true) .rustfmt_configuration_file(None) //.whitelist_function(".*pause.*") //.whitelist_type(".*pause.*") //.whitelist_var(".*pause.*") .generate() .expect("Unable to generate bindings"); // Write the bindings to the $OUT_DIR/bindings.rs file. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); } <file_sep>#include "ittnotify.h" <file_sep># Simple Intel SEAPI bindings for Rust The goal of this library is to have a minimalistic control wrapper for using vtune with rust code to be able to: * Create domains * Pause or resume control * Create tasks * Name * Begin / End **:warning: This is a WIP. Documentation will likely be wrong / not work for you.** ## Usage ### Shared library *To remember but delete later: how to make a shared library.* See [gcc help](https://renenyffenegger.ch/notes/development/languages/C-C-plus-plus/GCC/create-libraries/index) for more infos. Have **separate** header and `.c` files (here `test.h` and `test.c`). Compile the `.c` file with position independent addresses ```bash gcc -c -fPIC test.c -o test.o ``` Create shared library ```bash gcc -shared test.o -o libtest.so ``` Move the library to somewhere the linker can see it by default (or use `LD_LIBRARY_PATH`) ```bash sudo mv libtest.so /usr/lib/ ``` And link the code properly in rust (no `shared`, `dynamic`, etc.) ```rust println!("cargo:rustc-link-lib=test"); ``` ### Static library To create the static library: ```bash gcc -c test.c -o test.o ar rcs libtest.a test.o ``` As show in the code, can add flags in `build.rs` ```rust println!("cargo:rustc-flags= -L intel_headers/test_headers"); println!("cargo:rustc-link-lib=static=test"); // with static ``` :arrow_right: Can include for now the compiled `libittnotify.a` file and later on we can imagine submoduling the official intel repo and building the library in the `build.rs` stage automatically. ## Limitations This is the output of `nm libittnotify.so | grep "pause"`. Not very promising if we want to use the `pause` function (lowercase indicates hidden functions). ``` 0000000000002870 t __itt_pause_init_3_0 0000000000000120 D __itt_pause_ptr__3_0 0000000000000006 T ittnotify_mp_itt_pause_ U __itt_pause_ptr__3_0 ``` I built manually the official IntelSEAPI and after installing it I got the same problems, in detail: ``` nm /opt/intel/lib/libittnotify64.a | grep "pause" 00000000000036d0 t __itt_pause_init_3_0 0000000000000440 D __itt_pause_ptr__3_0 ``` <file_sep>#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![no_std] //include!(concat!(env!("OUT_DIR"), "/bindings.rs")); #[link(name = "ittnotify", kind = "static")] extern "C" { #[link_name = "__itt_pause_init_3_0"] pub fn __itt_pause(); } #[cfg(test)] mod LinkingTests { use super::*; #[test] pub fn linking_is_working() { unsafe { __itt_pause(); } } }
fdcc1c19a60bd8388c62adcf701b572042d0265e
[ "TOML", "C", "Markdown", "Rust" ]
7
C
mfournial/rvtune
74191debbe761ee4d29db16154952e68e7a9f992
374d35f8d308d7980e78bb81565540f754f4ef32
refs/heads/master
<repo_name>atrodo/ld34<file_sep>/fission_engine/js/animation.js function Animation(options) { [% WRAPPER per_second name="New Animations" %] if ($.isFunction(options)) { options = { get_gfx: options }; } $.extend(this, { name: null, img: null, frames: 1, frame_inc: 1/8, can_interrupt: true, loop: true, frame_x: null, frame_y: null, x: 0, y: 0, tile_x: null, tile_y: null, is_tile_sized: false, xw: 1, yh: 1, flip_xw: false, center: null, trim_s: 0, trim_b: 0, }, options); var self = this; var fix_center = this.center == null if (this.is_tile_sized) { this.xw *= runtime.tiles.tiles_xw this.yh *= runtime.tiles.tiles_yh delete this.is_tile_sized } if (this.gfx instanceof Gfx && this.get_gfx == undefined) { this.get_gfx = function() { return this.gfx } this.xw = this.gfx.xw() this.yh = this.gfx.yh() } if (this.gfx == undefined) this.gfx = new Gfx(this.xw, this.yh) if (fix_center) self.center = self.xw if (this.get_gfx == undefined) { if ($.type(this.img) != "string") throw "Must provide img or get_gfx for an Animation"; var img = new Gfx(1, 1); img .preload(this.img) .then(function(img) { self.img = img; self.xw = img.xw() self.yh = img.yh() self.gfx = new Gfx(self.xw, self.yh) if (fix_center) self.center = self.xw } ) this.get_gfx = function() { return self.img } } var did_last_frame = false var frame = 0 this.reset = function() { frame = 0 did_last_frame = false } this.was_last_frame = function() { return did_last_frame } this.frame = function() { frame += this.frame_inc || 1 did_last_frame = false if (frame >= this.frames) { frame -= this.frames did_last_frame = true } return did_last_frame } [% END %] } <file_sep>/fission_engine/js/input.js function Action(options, kb_trigger) { var action_name = ""; if (typeof options == "string") { action_name = options; kb_trigger = arguments[2] options = arguments[1] } if ($.isFunction(options)) { options = { handler: options, } } var _id = guid() $.extend(true, this, { action_name: action_name, handler: $.noop, triggers: { kb: kb_trigger, click: null, action: new action_check(_id), }, data: {} }, options); var self = this; self.id = function() { return _id; }; self.action_id = self.id if (!($.isFunction(self.handler))) die("handler for Action must be a function", self.handler); self.set_trigger = function(trigger, trigger_class) { var found_type = false var new_trigger var new_trigger_class $.each(triggers, function(trigger_name, trigger_type) { if (trigger instanceof trigger_type) { new_trigger = trigger new_trigger_class = trigger_name return false; } }) // We also accept arrays that will contain Actions for checking if ( new_trigger == undefined && trigger_class != undefined && trigger instanceof Array ) { $.each(triggers, function(trigger_name, trigger_type) { if (trigger_type == trigger_class) { new_trigger = trigger new_trigger_class = trigger_name return false; } }) } if (new_trigger == undefined) { $.each(triggers, function(trigger_name, trigger_type) { var result try { result = new trigger_type(trigger); } catch(e){}; if (result != undefined) { new_trigger = result new_trigger_class = trigger_name return false; } }) } if (new_trigger == undefined) { die("Could not find trigger type for " + trigger) } if (new_trigger._action != undefined && new_trigger._action != self) die("Trigger can only be assigned to one Action") new_trigger._action = self self.triggers[new_trigger_class] = new_trigger } $.each(self.triggers, function(trigger_name) { if (this == undefined) return if (trigger_name == "action") return self.set_trigger(this) }) self.check_trigger = function(trigger_type, trigger_name) { if (self.triggers[trigger_type] == undefined) return if (self.triggers[trigger_type] instanceof Array) { var trigger_actions = [] $.each(self.triggers[trigger_type], function(i, action) { if ( !( action instanceof Action) ) return var new_actions = action.check_trigger(trigger_type, trigger_name) trigger_actions.push(new_actions) }) return combine_arrays(trigger_actions) } return self.triggers[trigger_type].check(trigger_name) } self.trigger = function() { return self.handler() } self.toString = function() { if (self.action_name != undefined) return self.action_name; return self.id() } } var triggers = { kb: function(key) { if ($.type(key) != "string") die("Must pass a key string to triggers.kb") var self = this; $.extend(true, this, { toString: function() { return key } }) self.check = function(trigger_name) { if (trigger_name == key) return self._action } }, click: function(pos) { $.extend(true, this, pos); var self = this; $.each(["x", "y", "xw", "yh"], function(i, k) { if (! $.isNumeric(self[k])) { die("Must pass a number in " + k + " to new clickAction") } }); self.check = function(trigger_name) { // Click events are in the form of x,y var points = trigger_name.split(',') var x = points[0] var y = points[1] if ( x >= self.x && x <= self.x + self.xw && y >= self.y && y <= self.y + self.yh ) { return self._action } } }, } var action_check = function(id) { this.check = function(trigger_name) { if (trigger_name == id) return this._action } } function Input(options) { $.extend(true, this, { layer: null, default_actions: false, default_adv_actions: false, active: true, }, options); var self = this; var my_actions = [] var active_actions = {} var indv_action_name = "-" // kb specific { var special_keys = { 8: "backspace", 9: "tab", 13: "enter", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 192: '`', 224: "meta", } var nice_name = function(e) { var key = special_keys[e.which] || String.fromCharCode(e.which) key = key.toLowerCase() var keys = [ key ]; if (e.altKey && key != "alt") keys.unshift("alt") if (e.ctrlKey && key != "ctrl") keys.unshift("ctrl") if (e.shiftKey && key != "shift") keys.unshift("shift") //console.log(e.type, e.which, keys.join('+')) return keys.join('+'); } } this.trigger_on_key = function(action, key) { if ($.type(action) != "string") die("Must pass String to trigger_on_key"); self.add_action(new Action({ action_name: "", handler: function() { self.trigger(action, triggers.kb) }, input: self, triggers: { kb: key, } })); } this.add_action = function(action_name, action) { // Passing a plain object will do a mass add if ($.isPlainObject(action_name)) { $.each(action_name, this.add_action) return } if (action == undefined) { action = action_name action_name = "" } if ($.type(action_name) == "string" && $.isFunction(action)) { action = new Action(action_name, action) } if ($.type(action) != "string" && !(action instanceof Action)) { die("Must pass Action or String to add_action"); } if ($.inArray(action, my_actions) < 0) my_actions.push(action) } var get_trigger_type = function(trigger_type) { if ($.type(trigger_type) == "string") trigger_type = triggers[trigger_type] var tc_name = "" $.each(triggers, function(k, tc) { if (tc == trigger_type) { tc_name = k; return false; } }); return tc_name } this.activate = function() { this.active = true } this.deactivate = function() { this.active = false } this.activate_action = function(trigger_name, trigger_type) { if ($.type(trigger_name) != "string" && !(trigger_name instanceof Action)) return trigger_type = get_trigger_type(trigger_type) if (trigger_name instanceof Action) { trigger_type = "actions" trigger_name = trigger_name.id() } var trigger_actions = [] $.each(my_actions, function(i, action) { if (action.triggers[trigger_type] == undefined) return var new_actions = action.check_trigger(trigger_type, trigger_name) trigger_actions.push(new_actions) }) if (active_actions[trigger_type] == undefined) active_actions[trigger_type] = {} var cur_actions = combine_arrays(trigger_actions) active_actions[trigger_type][trigger_name] = cur_actions } this.deactivate_action = function(trigger_name, trigger_type) { if ($.type(trigger_name) != "string" && !(trigger_name instanceof Action)) return trigger_type = get_trigger_type(trigger_type) if (trigger_name instanceof Action) { trigger_type = "actions" trigger_name = trigger_name.id() } if (trigger_type in active_actions) delete active_actions[trigger_type][trigger_name] } this.trigger = function(trigger_name, trigger_type) { if ($.type(trigger_name) != "string" && !(trigger_name instanceof Action)) return trigger_type = get_trigger_type(trigger_type) if (trigger_name instanceof Action) { trigger_type = "actions" trigger_name = trigger_name.id() } var trigger_actions = [] $.each(my_actions, function(i, action) { if (action.triggers[trigger_type] == undefined) return var new_actions = action.check_trigger(trigger_type, trigger_name) trigger_actions.push(new_actions) }) process_actions(combine_arrays(trigger_actions)) } var done_actions = null; var process_actions = function(actions) { $.each(actions, function(i, action) { if (action == undefined) return var is_done_actions = done_actions != null var action_id if ($.isFunction(action.action_id)) { action_id = action.action_id() } if (action_id == undefined) return if (is_done_actions && action_id in done_actions) { actions[i] = done_actions[action_id] if (done_actions[action_id] === false) { delete actions[i] } return } if (action instanceof Cooldown) { actions[i] = action.frame() if (is_done_actions) done_actions[action_id] = actions[i] return; } if (!self.active || !self.layer.active_input) return; if (!(action instanceof Action)) return var result try { result = action.trigger() } catch (e) { if (e instanceof Cooldown) { result = e } else { warn(e); throw e } } if (result instanceof Cooldown) { result.result = action actions[i] = result } if (is_done_actions) done_actions[action_id] = result if (result === false) { delete actions[i] } }) } this.frame = function() { if (done_actions != undefined) { done_actions = null die("Input.frame was called inside of Input.frame") } done_actions = {} $.each(active_actions, function(trigger_type_name, triggers) { $.each(triggers, function(trigger_name, actions) { process_actions(actions) }) }) done_actions = null } if (this.default_actions) { this.trigger_on_key("right", "right") this.trigger_on_key("left", "left") this.trigger_on_key("up", "up") this.trigger_on_key("down", "down") } if (this.default_adv_actions) { this.trigger_on_key("jump", "space") this.trigger_on_key("atk_pri", "x") this.trigger_on_key("atk_sec", "z") } this.set_layer = function(new_layer) { if (new_layer == this.layer) return; var old_layer = this.layer this.layer = null if (old_layer instanceof Layer) { old_layer.remove_input(this); } if (new_layer == null) { return; } if (!(new_layer instanceof Layer)) throw new Error("Must pass a Layer to set_layer") this.layer = new_layer; this.layer.add_input({ "frame": function() { self.frame(); }, "keydown": function(e) { var key = nice_name(e) self.activate_action(key, triggers.kb) }, "keyup": function(e) { var key = nice_name(e) self.deactivate_action(key, triggers.kb) }, "click": function(e) { var target_pos = $(e.currentTarget).position() var x = e.pageX - target_pos.left var y = e.pageY - target_pos.top self.trigger(x + "," + y, triggers.click) } }) return; } var init_layer = this.layer; this.layer = null; this.set_layer(init_layer); } function ActionGroup(options) { $.extend(true, this, { layer: null, next: null, prev: null, select: null, on_change: null, }, options); var self = this; if (self.layer == undefined) { die("Must pass layer to ActionGroup") } var input = new Input({layer: self.layer}) self.clear = function() { for (var i = 0; i < self.length; i++) { delete self[i] } self.length = 0; self.current = 0; } self.clear() self.push = function(new_item) { if ($.isFunction(new_item)) new_item = new Action(new_item) if ($.isArray(new_item)) { $.each(new_item, self.push) return } if (!(new_item instanceof Action)) die("Can only add Action or Function to ActionGroup") self[self.length] = new_item self.length++ } self.get = function(i) { return self[i] } self.get_current = function() { return self[self.current] } self.set_current = function(new_current) { if (typeof new_current != "number") { for (var i = 0; i < self.length; i++) { if (self[i] == new_current) { new_current = i; break; } } } new_current = make_between(new_current, 0, self.length - 1); self.current = new_current if ($.isFunction(self.on_change)) self.on_change() } var key_prev = self.prev var key_next = self.next var key_select = self.select self.prev = function() { self.set_current((self.current - 1) % self.length) return new Cooldown() } self.next = function() { self.set_current((self.current + 1) % self.length) return new Cooldown() } self.select = function() { var action = self[self.current] if (action == undefined || !(action instanceof Action) ) return; action.trigger() return new Cooldown() } input.add_action(new Action("prev", self.prev, key_prev)) input.add_action(new Action("next", self.next, key_next)) input.add_action(new Action("select", self.select, key_select)) var action_catch = new Action() $.each(triggers, function(k, trigger_class) { action_catch.set_trigger(self, trigger_class) }); input.add_action(action_catch) } ActionGroup.prototype = new Array() <file_sep>/lib/state/mt.js var fades = { fadein: null, fadeou: null } var mt = { level: 0, goal: 20, lose: 0, total: 0, hp: 10, ovc: 0, give_soul: function(dir, soul_data) { var result = false; if (dir == 'wall') { mt.ovc += soul_data.good ? 0.5 : -0.5 result = true; } if (dir == 'floor') { if (soul_data.good > 0.6) { mt.ovc -= 0.5 mt.hp--; } else if ( soul_data.good < 0.4 ) { mt.ovc -= 3 mt.hp++; } result = true; } if (dir == 'ceiling') { if (soul_data.good < 0.4) { mt.ovc += 0.5 mt.hp--; } else if ( soul_data.good > 0.6 ) { mt.ovc += 3 mt.hp++; } result = true; } if (result) { mt.total++; } //console.log(mt.hp, mt) if (mt.hp >= mt.goal) { console.log('change level') var mc = require('state/mc').mc; var edges = require('state/land').edges var layer = require('layer/mc').layer layer.deactivate_input() fades.fadeou = new Cooldown('1s', function() { if (edges[mt.level + 1] == null) { console.log('end game'); return result; } fades.fadeou = null layer.activate_input() mt.level++; mt.lose = mt.goal; mt.goal += 10; mc.move_to( require('state/land').center_x, edges[mt.level].y[0] + 5 ) fades.fadein = new Cooldown('1s', function() { fades.fadein = null }); layer.events.once('frame_logic', fades.fadein) }) layer.events.once('frame_logic', fades.fadeou) } if (mt.hp < mt.lose) { var layer = require('layer/mc').layer layer.deactivate_input() fades.fadeou = new Cooldown('1s', function() { console.log('game over'); }) layer.events.once('frame_logic', fades.fadeou) } return result; }, } exports.fades = fades; exports.tree = mt <file_sep>/fission_engine/js/physics.js function Physics(options, extra) { var sub_pixel = 1/8 $.extend(true, this, { x: 100, y: 101, xw: 3, yh: 3, max_jump: 6, min_momentum_x: 0, max_momentum_x: 10, min_momentum_y: -9, max_momentum_y: 10, momentum_y: 0, momentum_x: 0, current_j: 0, layer: null, // The physics that created this object owner: null, relative_x: null, relative_y: null, next_frame: { momentum_y: false, momentum_x: false, min_momentum_x: false, max_momentum_x: false, min_momentum_y: false, max_momentum_y: false, }, animation: null, input: new Input(), ai: null, deferred: $.Deferred(), events: new Events(), flags: { facing_left: false, upside_down: false, solid: true, reduce_momentum: true, gravity: true, destroy_with_owner: true, }, }, options, extra || {}) if ($.isFunction(this.animation)) { this.animation = new Animation({ xw: this.xw * [% tiles_xw %], yh: this.yh * [% tiles_yh %], get_gfx: this.animation, }) } if (!(this.animation instanceof Animation)) { if (this.animation == undefined) throw "Physics Animation must be passed"; if (!$.isFunction(this.animation.get_animation) && !$.isFunction(this.animation.frame)) throw "Invalid Physics Animation, missing get_animation() or frame()"; } if ($.isFunction(this.cb_data)) this.cb_data = this.cb_data() if (this.ai != undefined) { if (!$.isFunction(this.ai)) throw "ai must be a function in Physics"; if (!AI.test(this.ai)) this.ai = new AI(this.ai) } if (this.callback == undefined) this.callback = {} this.callback = $.extend({ start_j: function() {}, end_j: function() {}, start_m: function() {}, end_m: function() {}, frame: function() {}, collide: function() {}, full_collide: null, init: function() {}, removed: function() {}, }, this.callback) $.extend(this, { is_m: function() { return this.momentum_x != 0 }, get_m_dir: function() { var dir = this.momentum_x; if (this.flags.facing_left) dir = -dir; return ( dir < 0 ? 'l' : dir > 0 ? 'r' : null ) }, ultimate_owner: function() { var result = this.owner if (result != undefined) while (result.owner != undefined) result = result.owner; return result }, }); $.extend(this, { add_momentum: function(dir) { if (dir == "l") return this.add_momentum_l() if (dir == "r") return this.add_momentum_r() if (dir == "j") return this.add_momentum_j() }, add_momentum_l: function() { this.momentum_x = floor(this.momentum_x) if (this.momentum_x == 0) this.flags.facing_left = true if (this.flags.facing_left) { this.next_frame.momentum_x = 1 } else { // Converge to zero this.next_frame.momentum_x = (this.momentum_x < 0 ? 1 : -1) } }, add_momentum_r: function() { this.momentum_x = floor(this.momentum_x) if (this.momentum_x == 0) this.flags.facing_left = false if (!this.flags.facing_left) { this.next_frame.momentum_x = 1 } else { // Converge to zero this.next_frame.momentum_x = (this.momentum_x < 0 ? 1 : -1) } return; }, add_momentum_j: function() { this.next_frame.momentum_y = 1 }, }) $.extend(this, { set_momentum: function(dir, speed) { speed = speed || 1; if (dir == "l") return this.set_momentum_l(speed) if (dir == "r") return this.set_momentum_r(speed) if (dir == "u" || dir == "j") return this.set_momentum_u(speed) if (dir == "d") return this.set_momentum_d(speed) }, set_momentum_l: function(speed) { this.flags.facing_left = true this.momentum_x = floor(speed - 1) this.add_momentum_l() }, set_momentum_r: function(speed) { this.flags.facing_left = false this.momentum_x = floor(speed - 1) this.add_momentum_r() }, set_momentum_u: function(speed) { this.momentum_y = floor(speed) }, set_momentum_d: function(speed) { this.momentum_y = -floor(speed) }, }) $.extend(this, { center: function() { return { x: (this.xw/2) + this.x, y: (this.yh/2) + this.y, } }, collidables: function() { var result = []; if (this.layer == null) return result; for (var i = 0; i < this.layer.all_physics.length; i++) { var other = this.layer.all_physics[i] if ( other == this || other == this.owner || !other.flags.solid ) { continue; } result.push(other); } return result; }, is_collide: function(full) { full = !!full var is_solid = this.flags.solid if (full) is_solid = true; if (!is_solid) return false; var all_colide = [] var chunks = runtime.chunks for (var i = floor(this.x); i < this.x + this.xw; i++) for (var j = floor(this.y); j < this.y + this.yh; j++) { var tile = chunks.get_phys(i, j) if (tile.solid) { // Check slope var fail_slope = true; // bl if (tile.angle_bl && i == floor(this.x) && j == floor(this.y)) { var slope = (this.y - j) / (this.x - (i + 1)) if (slope < -1) fail_slope = false } // br if (tile.angle_br && i == floor(this.x + this.xw) && j == floor(this.y)) { var slope = (this.y - j) / ((this.x + this.xw) - i) if (slope > 1) fail_slope = false } if (fail_slope) { if (full) all_colide.push($.extend({x: i, y: j}, chunks.get(i, j))) else return true } } } // Check all physics var xmin = this.x, xmax = this.x + this.xw; var ymin = this.y, ymax = this.y + this.yh; var colid = this.collidables(); for (var i = 0; i < colid.length; i++) { var other = colid[i] if ( ( other.x < xmax && other.x + other.xw > xmin ) && ( other.y < ymax && other.y + other.yh > ymin)) { if (full) all_colide.push(other) else return other; } } if (full) return all_colide else return false }, drop: function() { var old_y = this.y while (old_y > 0 && !this.is_collide()) { old_y = this.y this.y-- } var result = this.is_collide(true) this.y = old_y return result }, set_pos_relative: function(relative_x, relative_y) { var owner = this.owner if (owner == undefined || relative_x == undefined || relative_y == undefined) return false; // Figure out where the corner of the new attack obj is. // If they are facing left, relative_x moved to the other side if (!owner.flags.facing_left) relative_x += owner.xw; else relative_x = -relative_x - this.xw this.x = owner.x + relative_x; this.y = owner.y + relative_y; return true; }, set_pos: function() { var self = this var result = { hit_wall: false, hit_floor: false, hit_ceiling: false, hit_side: false, } var orig_x = this.x var orig_y = this.y var x_dir = this.flags.facing_left ? -1 : 1 var y_dir = this.flags.upside_down ? -1 : 1 x_dir *= this.momentum_x < 0 ? -1 : 1 y_dir *= this.momentum_y < 0 ? -1 : 1 var x_distance = abs(sub_pixel * this.momentum_x) var y_distance = abs(sub_pixel * this.momentum_y) var facing_left = this.flags.facing_left // Check to see if they were on the floor var was_on_floor = false if (y_dir < 0) { this.y -= sub_pixel var collide = self.is_collide() if (self.is_collide()) was_on_floor = true this.y += sub_pixel } // While the x_distance is non-zero, while (x_distance > 0) { // Move them no more than 1 tile = distance var distance = min(x_distance, 1); this.x += x_dir * distance x_distance -= distance // If they started on the floor if (was_on_floor) { var move_y = 0 var move_slope_y_dir = -1 var was_colliding = self.is_collide() if (was_colliding) move_slope_y_dir = 1 // Attempt to move them y no more than distance while (move_y <= distance) { this.y += move_slope_y_dir * sub_pixel if (self.is_collide() != was_colliding) break; move_y += sub_pixel } if (move_y > distance) { // If they don't hit the floor (check +subpixel), undo y movement this.y -= move_slope_y_dir * distance } if (self.is_collide()) { // If they are currently collide, backup 1 subpixel this.y -= move_slope_y_dir * sub_pixel } } // Then check collision. Collision means they've hit a wall var is_collide = self.is_collide(); if (is_collide) { result.hit_side = is_collide if (is_collide === true) { result.hit_wall = true } break; } } while (self.is_collide() && this.x != orig_x) { this.x -= x_dir * sub_pixel } var old_y_pos = this.y // Move them the y_distance stepping at most 1 tile while (y_distance > 0) { // Move them no more than 1 tile = distance var distance = min(y_distance, 1); this.y += y_dir * distance y_distance -= distance // Then check collision. Collision means they've hit the floor if (self.is_collide()) { if (y_dir > 0) result.hit_ceiling = true else result.hit_floor = true break; } } while (self.is_collide() && this.y != orig_y) { this.y -= y_dir * sub_pixel } if (y_dir > 0) this.current_j += this.y - old_y_pos return result }, move_to: function(x, y, keep_momentum) { if (!keep_momentum) { this.momentum_y = 0 this.momentum_x = 0 this.current_j = 0 } this.x = x this.y = y this.set_pos() }, frame: function() { var self = this var pos_info = { hit_floor: false } var m_stats = {} m_stats = $.extend(m_stats, { was_m: this.momentum_x != 0, was_j: this.flags.gravity && this.momentum_y != 0, }) var momentum_bounds = { min_momentum_x: false, max_momentum_x: false, min_momentum_y: false, max_momentum_y: false, } if (self.next_frame.min_momentum_x !== false && self.next_frame.max_momentum_x === false) { self.next_frame.max_momentum_x = self.max_momentum_x + self.next_frame.min_momentum_x } if (self.next_frame.min_momentum_y !== false && self.next_frame.max_momentum_y === false) { self.next_frame.max_momentum_y = self.max_momentum_y + self.next_frame.min_momentum_y } $.each(momentum_bounds, function(k, v) { momentum_bounds[k] = self.next_frame[k] || self[k] }) // Move the object and check collision if ( !this.set_pos_relative(this.relative_x, this.relative_y) ) { pos_info = this.set_pos() } // Do full processing collision if ($.isFunction(this.callback.full_collide)) { this.callback.full_collide.call(this, self.is_collide(true)) } if (this.callback.full_collide instanceof Events) { [% WRAPPER scope %] var buckets = { all_objects: [], all_physics: [], all_tiles: [], unrelated_physics: [] } var full_collide = self.callback.full_collide $.each(buckets, function(bucket) { if (!full_collide.exists(bucket)) delete buckets[bucket] }) if (count_object_keys(buckets) != 0) { var all_objects = self.is_collide(true) var ultimate_owner = self.ultimate_owner() $.each(all_objects, function(i, obj) { if (buckets.all_objects) buckets.all_objects.push(obj) if (buckets.all_physics && (obj instanceof Physics)) buckets.all_physics.push(obj) if (buckets.all_tiles && !(obj instanceof Physics)) buckets.all_tiles.push(obj) if (ultimate_owner && buckets.unrelated_physics && (obj instanceof Physics) && ultimate_owner != obj.ultimate_owner() ) buckets.unrelated_physics.push(obj) }) $.each(buckets, function(bucket, bucket_objs) { if (bucket_objs.length > 0) full_collide.emit(bucket, bucket_objs) }) } [% END %] } // Handle callbacks var was_m = this.is_m(); // Handle all the momentums if (this.flags.reduce_momentum) { // TODO: This all needs reworked to do gravity and everything better if (!this.next_frame.momentum_x) { if (pos_info.hit_floor) this.momentum_x -= 2 else this.momentum_x -= 1 } else { this.momentum_x += this.next_frame.momentum_x } if (pos_info.hit_side) { this.momentum_x = 0 } this.momentum_x = min(this.momentum_x, momentum_bounds.max_momentum_x) this.momentum_x = max(momentum_bounds.min_momentum_x, this.momentum_x) if (pos_info.hit_floor) { this.momentum_y = 0 this.current_j = 0 } if (pos_info.hit_ceiling) { this.momentum_y = 0 this.current_j = this.max_jump } var at_max_jump = this.current_j >= this.max_jump if (this.flags.gravity) { if (!this.next_frame.momentum_y || at_max_jump) { this.current_j = this.max_jump this.momentum_y -= 1 this.momentum_y = min(this.momentum_y, momentum_bounds.max_momentum_y) this.momentum_y = max(momentum_bounds.min_momentum_y, this.momentum_y) } else { this.momentum_y += this.next_frame.momentum_y } } else { var i = this.momentum_y if (!this.next_frame.momentum_y) { this.momentum_y += this.momentum_y > 0 ? -1 : this.momentum_y < 0 ? 1 : 0; } else { this.momentum_y += this.next_frame.momentum_y } } } m_stats = $.extend(m_stats, { is_m: this.momentum_x != 0, is_j: this.flags.graivty && this.momentum_y != 0, }) if (!m_stats.was_m && m_stats.is_m) this.callback.start_m.call(this) if (m_stats.was_m && !m_stats.is_m) this.callback.end_m.call(this) if (!m_stats.was_j && m_stats.is_j) this.callback.start_j.call(this) if (m_stats.was_j && !m_stats.is_j) this.callback.end_j.call(this) this.callback.frame.call(this) // Handle the sprite/frame this.animation.frame() this.next_frame = { momentum_x: false, momentum_y: false, min_momentum_x: false, max_momentum_x: false, min_momentum_y: false, max_momentum_y: false, } $.each(pos_info, function(k, v) { if (v) { self.events.emit(k, self, v); } }); if (this.ai != undefined) { this.ai(); } } }) $.extend(this, { attack: function(attack_obj, relative_x, relative_y) { var deferred = $.Deferred(); relative_x = relative_x || 0 relative_y = relative_y || 0 attack_obj = $.extend({ xw: 2, yh: 3, min_momentum_y: 0, speed: null, fall: null, //animation: "empty", solid: false, reduce_momentum: true, }, attack_obj); if (!$.isFunction(attack_obj.collide)) throw new Error("Must pass a collide test for attack"); attack_obj.relative_x = null attack_obj.relative_y = null if (attack_obj.speed == undefined) { attack_obj.relative_x = relative_x attack_obj.relative_y = relative_y } var frame_number = 0; var new_phys = new Physics({ owner: this, xw: attack_obj.xw, yh: attack_obj.yh, relative_x: attack_obj.relative_x, relative_y: attack_obj.relative_y, min_momentum_y: attack_obj.min_momentum_y, //sprite: attack_obj.sprite, callback: { full_collide: attack_obj.collide, /* sprite_done: function() { if (frame_number >= attack_obj.frames) remove_physics(this); frame_number += attack_obj.frame_inc }, */ removed: function() { deferred.resolve() }, }, flags: { solid: attack_obj.solid, reduce_momentum: attack_obj.reduce_momentum, destroy_with_owner: false, }, }); if (attack_obj.speed != undefined) { new_phys.momentum_x = attack_obj.speed } if (attack_obj.fall != undefined) { new_phys.momentum_y = attack_obj.fall } /* if (attack_obj.frames == undefined) attack_obj.frames = new_phys.sprite.frames if (attack_obj.frame_inc == undefined) attack_obj.frame_inc = new_phys.sprite.frame_inc */ new_phys.set_pos_relative(relative_x, relative_y); add_physics(new_phys); /* attack_obj = new Attack(attack_obj, this); // Create a new Physics object according to the attack object add_physics(attack_obj.make_physics(relative_x, relative_y)); */ return deferred.promise(); }, }); this.get_animation = function() { if (this.animation instanceof Animation) return this.animation return this.animation.get_animation() } this.set_layer = function(new_layer) { if (new_layer == this.layer) return this.deferred.promise(); var old_layer = this.layer this.layer = null if (old_layer instanceof Layer) { old_layer.remove_physics(this); } if (new_layer == null && old_layer != null) { this.callback.removed.call(this); this.deferred.resolve() return; } if (!(new_layer instanceof Layer)) throw new Error("Must pass a Layer to set_layer") this.layer = new_layer; return this.deferred.promise(); } if (this.layer != null) { var new_layer = this.layer this.layer = null this.set_layer(new_layer) } this.callback.init.call(this) } <file_sep>/lib/layer/mt.js var mt = require('state/mt').tree; var layer = runtime.add_layer('game.mt', { }); var edges = require('state/land').edges var perlin = new Gfx() perlin.preload('flame_perlin.png').then(function(img) { perlin = img }) var parts = { 0: 'dirt.jpg', 1: 'forest.jpg', 2: 'canopy.jpg', 3: 'treeline.jpg', 4: 'clouds.jpg', }; _.each(parts, function(v, k) { var result = new Gfx; result.preload(v); parts[k] = result }); //console.log(parts) var anim = new Animation({ frame_x: 0, frame_y: 0, xw: runtime.width, yh: runtime.height, get_gfx: function(cou) { var self = this; var gfx = this.gfx gfx.reset() var c = gfx.context var fades = require('state/mt').fades if (fades.fadeou != null) c.globalAlpha = 1 - fades.fadeou.get_pctdone() if (fades.fadein != null) c.globalAlpha = fades.fadein.get_pctdone() var level_edges = edges[mt.level]; var ovc = make_between((mt.ovc + 50) / 100, 0, 1) /* c.fillStyle = gfx.color_linear( [207, 130, 130], [186, 212, 232], ovc ); c.fillRect(0, 0, gfx.xw(), gfx.yh()); */ if (parts[mt.level]) { c.drawImage( parts[mt.level].canvas, 0, 0, gfx.xw(), gfx.yh() ) } c.globalAlpha = 1 var width = ( mt.hp < 3 ? 3 : mt.hp ) * 3; /* c.drawImage( perlin.canvas, (gfx.xw() / 3) - (width / 2) + (level_edges.x[1] / 1.7 - cou.x), 0, width, gfx.yh(), (gfx.xw() / 3) - (width / 2) + (level_edges.x[1] / 1.7 - cou.x), 0, width, gfx.yh() ) */ c.fillStyle = gfx.color_linear( [97, 61, 32], [191, 121, 64], ovc ); //c.globalCompositeOperation = 'hue'; c.fillRect( (gfx.xw() / 3) - (width / 2) + (level_edges.x[1] / 1.7 - cou.x), 0, width, gfx.yh() ); return gfx; }, }) layer.add_animation(anim); exports.layer = layer; exports.anim = anim; <file_sep>/fission_engine/js/layers.js function Layer(options) { $.extend(this, { name: null, group_name: null, active: true, active_input: true, bg: null, get_animations: function() { return this.all_animations }, all_animations: [], chunks: null, all_physics: [], all_inputs: [], events: new Events(), }, options); if (this.name == undefined) throw "Must name all Layers"; var self = this; self.activate = function() { if (!self.active) { self.active = true self.events.emit('activate') } } self.deactivate = function() { if (self.active) { self.active = false self.events.emit('deactivate') } } self.activate_input = function() { self.active_input = true } self.deactivate_input = function() { self.active_input = false } runtime.events.on('start_runtime', function() { if (self.active) { self.active = false; self.activate(); } else { self.active = true; self.deactivate(); } }) self.repaint = function(stage, cou) { if (!self.active) return if (self.bg instanceof Animation) stage.draw_animation(self.bg, cou) var context = stage.context var tiles = runtime.tiles var animations = self.get_animations(); for (var i in animations) { context.save() try { var anim = animations[i] stage.draw_animation(anim, cou) } catch (e) { console.log("exception:", e) } finally { context.restore() } } for (var phy_obj in self.all_physics) { context.save() try { var phys = self.all_physics[phy_obj] var anim = phys.get_animation() anim.tile_x = phys.x anim.tile_y = phys.y anim.flip_xw = phys.flags.facing_left; stage.draw_animation(anim, cou); [% IF show_phys_box %] var x = (phys.x - cou.x) * tiles.tiles_xw var y = (phys.y - cou.y) * tiles.tiles_yh context.strokeStyle = "rgba(255, 165, 0, 0.5)" context.strokeRect( x, y, phys.xw * tiles.tiles_xw, phys.yh * tiles.tiles_yh ) [% END %] } catch (e) { console.log("exception:", e) } finally { context.restore() } } } self.add_animation = function(new_anim) { if (!(new_anim instanceof Animation)) { new_anim = new Animation($.extend({}, new_anim)); } if ($.inArray(new_anim, self.all_animations) == -1) self.all_animations.push(new_anim) } self.remove_animation = function(old_anim) { var remove_one = function(current_anim) { $.each(self.all_animations, function(i, anim) { if (anim == undefined) return if (anim.flags.destroy_with_owner && anim.owner == current_anim) { remove_one(anim) } if (anim == current_anim) { delete self.all_animations[i] anim.set_layer(null) } }) } remove_one(old_anim) self.all_animations = compact_array(self.all_animations) } self.add_physics = function(new_phys) { if (!(new_phys instanceof Physics)) { new_phys = new Physics($.extend({}, new_phys, { layer: self })); } if ($.inArray(new_phys, self.all_physics) == -1) self.all_physics.push(new_phys) return new_phys.set_layer(self) } self.remove_physics = function(old_phys) { var remove_one = function(current_phys) { $.each(self.all_physics, function(i, phys) { if (phys == undefined) return if (phys.flags.destroy_with_owner && phys.owner == current_phys) { remove_one(phys) } if (phys == current_phys) { delete self.all_physics[i] phys.set_layer(null) } }) } remove_one(old_phys) self.all_physics = compact_array(self.all_physics) } self.add_input = function(new_input) { if (! $.isFunction(new_input.frame)) { throw "New inputs must implement frame"; } if ($.inArray(new_input, self.all_inputs) == -1) self.all_inputs.push(new_input) return self; } self.remove_input = function(old_input) { $.each(self.all_inputs, function(i, input) { if (phys == current_phys) { delete self.all_inputs[i] } }) self.all_inputs = compact_array(self.all_inputs) } self.process_frame = function() { if (!self.active) return for (var input_obj in self.all_inputs) { var input = self.all_inputs[input_obj] if (input == null) continue input.frame() } self.events.emit('frame_logic') for (var anim_obj in self.all_animations) { var anim = self.all_animations[phy_obj] if (anim == null) continue anim.frame() } for (var phy_obj in self.all_physics) { var phys = self.all_physics[phy_obj] if (phys == null) continue phys.frame() } return } self.process_event = function(e) { for (var input_obj in self.all_inputs) { var input = self.all_inputs[input_obj] if (input == null) continue if ($.isFunction(input[e.type])) input[e.type](e) } } } <file_sep>/fission_engine/js/lprng.js //http://jsperf.com/lprng-vs-math-random function lprng(seed) { var mod = Math.pow(2, 32); var magic = 0x80f77deb; var buffer = 16 this.data = new Uint32Array(buffer) this.idx = 0 this.lfsr = 1; this.seed = function(seed) { if (seed.length == undefined) seed = [seed] var lfsr = 0; for (var iseed = 0; iseed < seed.length; iseed++) { if (iseed < seed.length) lfsr ^= seed[iseed]; this.data[iseed] = lfsr; lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & magic); } this.lfsr = lfsr; for (var i = 0; i <= buffer; i++) { this.prng() } return this; } this.prng = function(multi) { multi = multi || 1 var lfsr = this.lfsr var s = this.data[this.idx] ^ lfsr var idx = this.idx ++ this.idx %= buffer s ^= this.data[(idx + lfsr & 0x7) % buffer] lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & magic); this.data[this.idx] = s this.lfsr = lfsr; var result = this.data[this.idx] if (multi) { result = (result * 1/mod) * multi } return result } this.choose = function() { var choices = arguments if (arguments.length == 1 && arguments[0] instanceof Array) choices = arguments[0] return choices[Math.floor(this.random(choices.length))]; } this.random = this.prng if (seed === null) this.seed(Math.floor(Math.random() * Math.pow(2, 32))) else if (seed != undefined) this.seed(seed); } <file_sep>/lib/state/land.js var lvlht = chunk_yh*2; var edges = [ { x: [ 20, 340], y: [20 + lvlht * 0, 40 + lvlht * 0] }, { x: [ 40, 320], y: [20 + lvlht * 1, 40 + lvlht * 1] }, { x: [ 60, 300], y: [20 + lvlht * 2, 40 + lvlht * 2] }, { x: [ 80, 280], y: [20 + lvlht * 3, 40 + lvlht * 3] }, { x: [100, 260], y: [20 + lvlht * 4, 40 + lvlht * 4] }, ] //console.log(edges) exports.edges = edges exports.lvlht = lvlht exports.center_x = edges[0].x[0] + ( edges[0].x[1] - edges[0].x[0] ) / 2 <file_sep>/fission_engine/js/gfx.js var Gfx = function(xw, yh) { [% WRAPPER per_second name="New Gfxs" %] var self = this self.canvas = $("<canvas/>") .attr("width", xw || 0) .attr("height", yh || 0) .get(0) self.context = self.canvas.getContext("2d") self.clear = function() { self.context.clearRect(0, 0, xw, yh) return self } self.reset_transform = function() { self.context.setTransform(1, 0, 0, 1, 0, 0) } self.reset = function() { self.clear() var c = self.context c.beginPath() c.globalAlpha = 1 c.globalCompositeOperation = 'source-over' c.fillStyle = '#000' c.strokeStyle = '#000' c.font = '10px sans-serif' c.shadowColor = 'rgba(0,0,0,0)' c.shadowBlur = 0 self.reset_transform() return self } self.full_reset = function() { self.width = self.width return self } self.draw_animation = function(anim, cou) { if (!(anim instanceof Animation)) throw new Error("Can only draw an Animation") cou = cou || { x: 0, y: 0 } var context = this.context context.save() try { var img = anim.get_gfx(cou) var x = anim.frame_x var y = anim.frame_y if (x == undefined && anim.tile_x != undefined) { x = (anim.tile_x - cou.x) * runtime.tiles.tiles_xw x += runtime.width * (1/2) } if (y == undefined && anim.tile_y != undefined) { y = (anim.tile_y - cou.y) * runtime.tiles.tiles_yh y += runtime.height * (1/4) } if (x == undefined) x = anim.x - cou.x if (y == undefined) y = anim.y - cou.y if (!img) return; if (x == undefined || y == undefined) { warn("Could not determine x/y position") return; } if (!(img instanceof Gfx)) { warn(img, " is not an Gfx, ignoring"); return; } if (anim.flip_xw) { context.scale(-1, 1) context.translate(-anim.center, 0) x = -x } context.drawImage( img.canvas, x - anim.trim_s, y - anim.trim_b, anim.xw, anim.yh ) [% IF show_draw_box %] context.strokeStyle = "rgba(255, 0, 165, 0.5)" context.strokeRect( x - anim.trim_s, y - anim.trim_b, anim.xw, anim.yh ) [% END %] } catch (e) { console.log("exception:", e) } finally { context.restore() } } self.draw_animations = function(anims, cou) { if (!$.isArray(anims)) throw new Error("Must pass an array to 'draw_animations'"); $.each(anims, function(i, anim) { try { self.draw_animation(anim, cou); } catch(e) { console.log(e) }; }) } self.color_linear = function(low, high, percent) { if ($.isArray(low)) { low = { r: low[0], g: low[1], b: low[2] }; } if ($.isArray(high)) { high = { r: high[0], g: high[1], b: high[2] }; } var m = { r: (high.r - low.r), g: (high.g - low.g), b: (high.b - low.b), } var result = [ 'rgb(', (m.r * percent + low.r) | 0, ',', (m.g * percent + low.g) | 0, ',', (m.b * percent + low.b) | 0, ')', ].join('') return result } self.preload = function(url, do_flip) { if (do_flip == undefined) do_flip = true var result = $.Deferred() var promise = engine.events.emit('gfx.add_preload', url); if ($.isArray(promise) && promise.length == 1) promise = promise[0]; promise.then(function(img) { img = $(img); xw = img.width() yh = img.height() $(self.canvas) .attr("height", img.height()) .attr("width", img.width()) var context = self.context if (do_flip) { context.translate(0, img.height()) context.scale(1, -1) } context.drawImage(img.get(0), 0, 0) result.resolve(self) }) return result } self.xw = function() { return xw } self.yh = function() { return yh } [% END %] return self; } [% WRAPPER scope %] var status = $("<div/>") .prependTo("body") .hide() var progress = $("<div/>") .addClass("progress progress-striped active") .append($("<div/>") .addClass("bar") ) .prependTo(content.parent()) var preload_list = []; var preload_div = $("<div/>") .addClass("preload") .appendTo("body") var preload_interval = window.setInterval(function() { $.each(preload_list, function(i, item) { if (item == undefined) return; if (item.go != null) { item.go(); item.go = null; } if (item.promise.state() != 'resolved') { return } preload_list[i] = null; progress.attr("value", i+1); progress.find(".bar").width( round((i+1) / preload_list.length * 100) + "%") if (i == preload_list.length-1) { window.clearInterval(preload_interval) progress.fadeOut(function() { engine.events.emit('preload_done'); }) } return false; }) }, [% preload_interval %]); engine.events.on('gfx.add_preload', function(url) { var result = $.Deferred() var status_line = $("<div/>") .appendTo(status) .text(url) var loaded_img = function() { status_line.append("...loaded") result.resolve(img.get(0)) img.remove() status_line.append("...done") } var img = $("<img/>") preload_list.push({ promise: result.promise(), go: function() { img .load(loaded_img) .attr("src", "r/" + url) .appendTo(preload_div) } }) progress.attr("max", preload_list.length); return result.promise() }); [% END %] <file_sep>/lib/layer/land.js require('layer/mt'); runtime.tiles.add_tile_info( _.mapObject( _.range(80), function(v) { return { solid: true } } ) ); var edges = require('state/land').edges; var lvlht = require('state/land').lvlht; var chunk_generate = function(seed) { var rng = new lprng() rng.seed(seed) var chunks = runtime.chunks for (var level in _.range(5)) { level = parseInt(level); var rng_x = _.range(10 * chunk_xw); for ( var x in rng_x ) { x = rng_x[x]; var rng_y = _.range(level * lvlht, (level+1) * lvlht); for ( var y in rng_y ) { y = rng_y[y]; if ( y <= edges[level].y[0] || y >= edges[level].y[1] || x <= edges[level].x[0] || x >= edges[level].x[1]) { var start = 8 * (level + 1) if (y > edges[level].y[0]) { start += 8; } chunks.set(x, y, rng.choose(_.range(start, start+8))) continue; } } } } //console.log(chunks); chunks.flush(); } $(function() { if (localStorage["seed"] == undefined || localStorage["v"] < 3) { localStorage.clear() chunk_generate(Math.floor(Math.random() * Math.pow(2, 32))); } }) <file_sep>/lib/state/mc.js var layer = require('layer/mc').layer var mc_anim = require('layer/mc').mc_anim var edges = require('state/land').edges var input = new Input({ layer: layer }); var mc = new Physics({ xw: 2, yh: 3, x: ( edges[0].x[1] - edges[0].x[0] ) / 2, y: edges[0].y[0] + 5, input: input, animation: mc_anim, }); var sphere_oi = 15; layer.add_physics(mc); engine.events.on('runtime.cou_source', function () { return mc } ); exports.mc = mc; input.add_action(new Action(function() { mc.add_momentum('j') }, "up")); input.add_action(new Action(function() { mc.add_momentum('r') }, "right")); input.add_action(new Action(function() { mc.add_momentum('l') }, "left")); var find_phys = function() { var result = []; var center = mc.center(); $.each(mc.collidables(), function(i, phys) { var phys_cen = phys.center(); var xd = center.x - phys_cen.x; var yd = center.y - phys_cen.y; var d = Math.sqrt(xd * xd + yd * yd); if (d > abs(exports.radius)) { return; } result.push({ phys: phys, center: phys_cen, xd: xd, yd: yd, d: d }); }); return result; } exports.radius = 0; exports.pulse_cooldown = new Cooldown(0.25 * runtime.fps, function() { //console.log('PULSE') layer.events.off('frame_logic', exports.pulse_cooldown.result); var center = mc.center(); if (exports.radius > 0) { $.each(find_phys(), function(i, info) { info.phys.set_momentum(center.x > info.center.x ? 'l' : 'r', 9 ); info.phys.set_momentum(center.y > info.center.y ? 'd' : 'u', 9 ); }); } else { $.each(find_phys(), function(i, info) { info.phys.set_momentum(center.x < info.center.x ? 'l' : 'r', 9 ); info.phys.set_momentum(center.y < info.center.y ? 'd' : 'u', 9 ); }); } exports.radius = 0; }); input.add_action( new Action( function() { //console.log("PUSH!!", exports.radius) if (exports.radius < 0) return; if (exports.radius == 0) { exports.radius = 3; } if (exports.radius < 15) { exports.radius++ } exports.pulse_cooldown.reset(); layer.events.on('frame_logic', exports.pulse_cooldown); return new Cooldown(0.1 * runtime.fps); }, "x" ) ); input.add_action( new Action( function() { //console.log("PULL!!", exports.radius) if (exports.radius > 0) return; if (exports.radius == 0) { exports.radius = -3; } if (exports.radius > -15) { exports.radius-- } exports.pulse_cooldown.reset(); layer.events.on('frame_logic', exports.pulse_cooldown); return new Cooldown(0.1 * runtime.fps); }, "z" ) ); <file_sep>/fission_engine/js/moo.js /* new BUILDARGS BUILD does extends with has is isa coerce handles trigger default predicate builder clearer lazy required reader writer weak_ref... init_arg before around after ROLE has */ (function(window) { var Moo = function() { }; var isFunction = function(func) { return typeof func === "function"; } var simple_default = function(value) { return function() { return value }; } var die = function(msg) { console.trace(); throw msg }; Moo.extends = function () { die() }; Moo.with = function () { die() }; Moo.has = function (prop_name, attr) { var desc = { configurable: false, enumerable: true, } // * is if (typeof attr.is != 'string') { die( "Moo: 'is' is required and must be a string" ); } attr.is = attr.is.toLowerCase(); if (!(attr.is == 'rw' || attr.is == 'ro')) { die( "Moo: 'is' must be rw or ro: '" + prop_name + "' was '" + attr.is + "'" ); } desc.rw = attr.is == 'rw'; // * lazy desc.lazy = 'lazy' in attr ? !!attr.lazy : false; // * coerce if ('coerce' in attr) { if (typeof attr.coerce != "function") { die("Moo: attribute defaults must be a function or simple type"); } desc.coerce = attr.coerce; } // * default { var default_typeof = typeof attr.default; // We only accept simple, immutable types if ( default_typeof == "boolean" || default_typeof == "number" || default_typeof == "string" || default_typeof == "undefined" || attr.default === null ) { attr.default = simple_default(attr.default); } if (typeof attr.default != "function") { die("Moo: attribute defaults must be a function or simple type"); } desc.default = attr.default; } // /* * isa * handles * trigger * predicate * builder * clearer * required * reader * writer * weak_ref... * init_arg */ this._new.props[prop_name] = desc; }; Moo.method = function (name, body) { if (!isFunction(body)) { die("Method must be a function"); } this._new.methods[name] = body; }; Moo.before = function (name, body) { die() }; Moo.around = function (name, body) { die() }; Moo.after = function (name, body) { die() }; Moo.class = function(class_def) { var meta = Object.create(Moo); var _new = {}; var props = {}; var new_class = function(values) { if (isFunction(this.BUILDARGS)) { values = this.BUILDARGS.apply(this, arguments); } if (values === undefined) { values = {} } if (typeof values != 'object') { die("Moo: constructor requires an object of values"); } var backend = {} for (prop_name in props) { (function() { var prop = prop_name; var desc = props[prop]; var real_getter = function() { return backend[prop] }; var getter = real_getter; var setter; var has_done_lazy = false; if ('coerce' in desc) { setter = function(new_value) { has_done_lazy = true; backend[prop] = desc.coerce.call(this, new_value); } } else { setter = function(new_value) { has_done_lazy = true; backend[prop] = new_value } } if (prop in values) { setter.call(this, values[prop]); } else { if (desc.lazy) { getter = function() { if (!has_done_lazy) { backend[prop] = desc.default.call(this); has_done_lazy = true; } return real_getter() } } else { backend[prop] = desc.default.call(this); } } // Object.defineProperty(this, prop, { configurable: false, enumerable: true, get: getter, set: desc.rw ? setter : undefined, }); }).call(this); }; Object.seal(this); if (isFunction(this.BUILD)) { this.BUILD() } }; _new = { methods: new_class.prototype, props: props, c: new_class, }; meta._new = _new; if (class_def instanceof Function) { class_def.call(meta); } return new_class; } window.Moo = Moo; })(window); <file_sep>/fission_engine/js/sprite.js function Sprite(options) { $.extend(this, { name: null, animations: {}, default: null, current: null, next: null, }, options); if ($.type(this.animations) == "array") { var new_animations = {}; $.each(this.animations, function(i, animation) { if ($.isPlainObject(animation)) animation = new Animation(animation); new_animations[animation.name] = animation; }); this.animations = new_animations } if ($.type(this.default) == "string") this.default = this.animations[this.default]; if (!(this.default instanceof Animation)) throw "Must provide a default Animation"; $.extend(this, { get_animation: function() { return this.current }, set_next: function(next) { if ($.type(next) == "string") next = this.animations[next]; if (next == null) { this.next = null; return; } if (!(next instanceof Animation)) return; if (this.next != null) return; this.next = next }, frame: function() { this.current.frame() if (this.current.was_last_frame()) { var next = this.next if (next == null) { if (this.current.loop) { next = this.current } else { next = this.default } } if (this.current != next) { next.reset() } this.current = next this.next = null } else if (this.current.can_interrupt && this.next != null) { if (this.next != this.current) { this.next.reset() } this.next = null } } }); this.set_next(this.next); if (this.current == undefined) this.current = this.default; } Sprite.empty_sprite = new Sprite({ default: new Animation({ get_gfx: function() { this.gfx.reset(); return this.gfx }, }) }) <file_sep>/lib/layer/souls.js require('layer/mt'); var soul_layer = runtime.add_layer('game.souls', { }); var perlin = new Gfx() perlin.preload('flame_perlin.png').then(function(img) { perlin = img }) var soul_img = new Gfx() soul_img.preload('soul.png').then(function(img) { soul_img = img }) var rng = new lprng(null) exports.layer = soul_layer; exports.anim = function(soul_data) { return new Animation({ xw: 40, yh: 60, get_gfx: function() { var self = this; var gfx = this.gfx gfx.reset() var c = gfx.context var fades = require('state/mt').fades if (fades.fadeou != null) c.globalAlpha = 1 - fades.fadeou.get_pctdone() if (fades.fadein != null) c.globalAlpha = fades.fadein.get_pctdone() c.drawImage( soul_img.canvas, 0, 0, 40, 60 ) /* c.globalCompositeOperation = 'multiply'; c.globalAlpha = 0.4 c.drawImage( perlin.canvas, 0, 0, 30, 45 ) */ c.globalCompositeOperation = 'hue'; var ovc = 2 * (soul_data.good - 0.5) if (ovc >= 0) { c.fillStyle = gfx.color_linear( [191, 191, 191], [120, 184, 232], ovc ); } else { c.fillStyle = gfx.color_linear( [191, 191, 191], [169, 0, 25], abs(ovc) ); } c.fillRect(0, 0, gfx.xw(), gfx.yh()); return gfx; }, }); } <file_sep>/fission_engine/js/ai.js function AI(factory) { if (!$.isFunction(factory)) throw "Must pass a constructor to AI"; var new_this = factory.call(this); if (!$.isFunction(new_this)) throw "Factory must return a function for AI"; new_this.is_ai = true return new_this } AI.test = function(f) { return !!f.is_ai } <file_sep>/lib/state/soul.js var layer = require('layer/mc').layer var anim = require('layer/souls').anim var edges = require('state/land').edges var mc = require('state/mc').mc; var mt = require('state/mt').tree; var all_lvl_souls = {} var create_soul = function(level) { var lvl_souls = all_lvl_souls[level]; var lvl_edges = edges[level]; var x_span = lvl_edges.x[1] - lvl_edges.x[0] - 20; var i = lvl_souls.length var rng = new lprng(null) var soul_data = { good: rng.choose(_.range(0, 1.25, 0.25)), } var soul = new Physics({ x: lvl_edges.x[0] + 20 + rng.choose(_.range(x_span)), y: lvl_edges.y[0] + 3 + rng.choose(_.range(16)), xw: 1, yh: 2, max_momentum_x: 6, min_momentum_y: -6, max_momentum_y: -6, flags: { gravity: false }, animation: anim(soul_data), ai: new AI(function() { return function() { if (mt.level != level) return; var m_dir = this.get_m_dir(); if (this.x <= lvl_edges.x[0] + 4) { this.add_momentum('r'); return } if (this.x >= lvl_edges.x[1] - 4) { this.add_momentum('l'); return } var choice = rng.choose( null, 'l', 'r', m_dir, m_dir, m_dir, m_dir, m_dir, m_dir, null, null, null, null ) if (choice) { this.add_momentum(choice) } } }), }); //console.log(soul.x, soul.y) soul.events.on('hit_side', function(soul, other) { if (other === true) return; if (other == mc) { var ogood = soul_data.good soul_data.good += (0.5 - soul_data.good) / 2 //console.log('hit_mc', ogood, soul_data.good) return new Cooldown('1s') } }); soul.events.on('hit_wall', function(soul) { /* console.log('hit_wall'); if (mt.give_soul('wall', soul_data)) { soul.set_layer(null); delete lvl_souls[i]; } */ }); soul.events.on('hit_floor', function(soul) { //console.log('hit_floor'); if (mt.give_soul('floor', soul_data)) { soul.set_layer(null); delete lvl_souls[i]; } }); soul.events.on('hit_ceiling', function(soul) { //console.log('hit_ceiling'); if (mt.give_soul('ceiling', soul_data)) { soul.set_layer(null); delete lvl_souls[i]; } }); layer.add_physics(soul); lvl_souls.push(soul); } _.each(edges, function(lvl_edges, level) { all_lvl_souls[level] = [] _.each(_.range(50), function(i) { create_soul(level) }) }) var soul_generator = new Cooldown('5s', function() { //create_soul(mt.level); soul_generator.reset() //console.log(soul_generator); layer.events.once('frame_logic', soul_generator) }) layer.events.once('frame_logic', soul_generator) <file_sep>/fission_engine/js/runtime.js function Runtime(options) { $.extend(this, { width: [% width %], height: [% height %], trax_x: [% width / 2 %], trax_y: [% height / 2 %], // chunks: new Chunks(), layer_groups: [], events: engine.events, tiles: new Tiles({ background: "[% tiles_bg %]", foreground: "[% tiles_fg %]", tiles_bd: [% tiles_bd %], tiles_xw: [% tiles_xw %], tiles_yh: [% tiles_yh %], }) }, options); var self = this; var physics_timing = 40 this.fps = floor(1000 / physics_timing) [% IF show_timings %] var fps_span = $("<span/>") var fps = function() { var table = $("<table class='table table-striped table-condensed'/>") fps_span .empty() .append(table) table.append($("<tr/>") .append($("<th/>").text("Metric")) .append($("<th/>").text("Per Second")) .append($("<th/>").text("Total (ms)")) .append($("<th/>").text("Avg (ms)")) ) var timing_names = Object.keys(timings).sort() for (var i = 0; i < timing_names.length; i++) { var name = timing_names[i] var timing = timings[name] || { done: 0, time: 0} table.append($("<tr/>") .append($("<th/>").text(name)) .append($("<th/>").text(timing.done)) .append($("<th/>").text(timing.time)) .append($("<th/>").text(floor(timing.time / timing.done))) ) timings[name] = null } } var fps_interval = setInterval(fps, 1000); [% END %] var frame_logics = []; var run_physics = true var stage = new Gfx(self.width, self.height) content .empty() .append(stage.canvas) [% IF show_timings %] .append(fps_span) [% END %] // Center of universe var get_cou = function() { var cou_source = runtime.events.call("runtime.cou_source") || {} var cou = { x: cou_source.x || 0, y: cou_source.y || 0, } return cou; } var repaint = function() { [% WRAPPER per_second name="Frame" %] var cou = get_cou() var chunks = self.chunks var tiles = self.tiles var chunk_x_mid = chunks.chunk_xw >> 1 var chunk_y_mid = chunks.chunk_yh >> 1 var cou_chunk = chunks.get_chunk_for(cou.x, cou.y) || {} // Check all of the cardinal directions to stop from scrolling into // unseen areas if (cou_chunk.solid_n) { if (cou.y - chunk_y_mid > cou_chunk.meta.chunk_y * chunks.chunk_yh) cou.y = cou_chunk.meta.chunk_y * chunks.chunk_yh + chunk_y_mid } if (cou_chunk.solid_s) { if (cou.y - chunk_y_mid < cou_chunk.meta.chunk_y * chunks.chunk_yh) cou.y = cou_chunk.meta.chunk_y * chunks.chunk_yh + chunk_y_mid } if (cou_chunk.solid_e) { if (cou.x - chunk_x_mid > cou_chunk.meta.chunk_x * chunks.chunk_xw) cou.x = cou_chunk.meta.chunk_x * chunks.chunk_xw + chunk_x_mid } if (cou_chunk.solid_w) { if (cou.x - chunk_x_mid < cou_chunk.meta.chunk_x * chunks.chunk_xw) cou.x = cou_chunk.meta.chunk_x * chunks.chunk_xw + chunk_x_mid } var context = stage.context context.restore() context.clearRect(0, 0, self.width, self.height) context.save() try { context.save() //context.translate(self.width * (1/2), self.height * (1/2)) context.translate(0, self.height); context.scale(1, -1) self.foreach_active_layer(function(layer) { context.save() try { layer.repaint(stage, cou) } catch (e) { console.log("exception:", e) } finally { context.restore() } }) context.save() } catch (e) { console.log("exception:", e) } finally { context.restore() } [% END %] } var bot = Date.now() var last_frame = bot; var frame_number = 0; var physics = function(reset_last_frame) { var now = Date.now(); var frames_done = 0 while (last_frame < now) { [% WRAPPER per_second name="Physics" %] last_frame += physics_timing frame_number++ if (frame_number % (self.fps * 10) == 0) warn("Frame: ", frame_number); runtime.events.emit('input_frame') runtime.events.emit('runtime.frame_logic', last_frame) self.foreach_active_layer(function(layer) { layer.process_frame() }) if (reset_last_frame) last_frame = now; frames_done++ if (frames_done > [% bankrupt_frames %]) last_frame = now; [% END %] } } var maintaince = function() { runtime.events.emit('runtime.maintaince', get_cou()) } var mouseX = 0; var mouseY = 0; var mouse_re = /^mouse/; var get_mouse_pos = function() { return {x: mouseX, y: mouseY} } var current_drag_event var drag_props = [ 'buttons', 'clientX', 'clientY', 'currentTarget', 'movementX', 'movementY', 'revion', 'offsetX', 'offsetY', 'originalTarget', 'pageX', 'pageY', 'screenX', 'screenY', 'target', 'view', 'which' ]; var input_listen = function(e) { e.preventDefault() if (mouse_re.test(e.type)) { var target_pos = $(e.currentTarget).position() mouseX = e.pageX - target_pos.left mouseY = e.pageY - target_pos.top } self.foreach_active_layer(function(layer) { layer.process_event(e) }) var drag_data var do_drag_event = function(event_name) { if (drag_data == null) { drag_data = {} $.each(drag_props, function() { drag_data[this] = e[this] }); } var drag_event = $.Event(event_name, drag_data) self.foreach_active_layer(function(layer) { layer.process_event(drag_event) }) } // Convert a mousemove into a drag if (e.type == 'mousemove' && e.buttons & 1 == 1) { if (!current_drag_event) { do_drag_event('dragstart') current_drag_event = true } do_drag_event('drag') } else if (current_drag_event) { if (e.type == 'mouseup') { do_drag_event('dragend') current_drag_event = false } if (e.type == 'mousemove') { do_drag_event('dragcancel') current_drag_event = false } } } $(document).bind("keydown keyup", input_listen) $(stage.canvas) .bind("click", input_listen) .bind("mouseenter mouseleave", input_listen) .bind("mousedown mouseup mousemove", input_listen) var maintain_interval var phys_interval var process_painting = false var anim_frame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 33); }; var frame_requested = function() { if (process_painting) try { repaint() } catch (e) { warn(e) } anim_frame(frame_requested) } anim_frame(frame_requested) /* */ self.get_frame = function() { return frame_number } self.get_mouse_pos = get_mouse_pos self.on = function(event_name, cb) { if ((typeof event_name) != 'string') { cb = event_name event_name = 'runtime.frame_logic'; } self.events.on(event_name, cb); } self.once = function(event_name, cb) { if ((typeof event_name) != 'string') { cb = event_name event_name = 'runtime.frame_logic'; } self.events.once(event_name, cb); } self.emit = function() { self.events.emit.apply(self.events, arguments); } var name_match = /^(\w*)[.]?(.*)$/ self.find_group = function(name) { var name_split = name.match(name_match) var group_name = name_split[1] var layer_name = name_split[2] var group = null; $.each(self.layer_groups, function(i, layer_group) { if (layer_group.name == group_name) { group = layer_group return false } }) if (group == null) { group = { name: group_name, layers: [], active: true, } self.layer_groups.push(group) } return group } self.find_layer = function(name) { var name_split = name.match(name_match) var group_name = name_split[1] var layer_name = name_split[2] var group = self.find_group(name) var result; $.each(group.layers, function(i, layer) { if (layer.name == layer_name) { result = layer return false; } }) return result } self.add_layer = function(name, layer) { var name_split = name.match(name_match) var group_name = name_split[1] var layer_name = name_split[2] var group = self.find_group(name) if (!(layer instanceof Layer) && $.type(layer) == "object") { $.extend(layer, {name: layer_name, group_name: group.name}) layer = new Layer(layer) } layer.group_name = group.name group.layers.push(layer) return layer } self.deactivate_group = function(name) { var group = self.find_group(name) group.active = false; } self.foreach_active_layer = function(callback) { $.each(self.layer_groups, function(i, group) { if (group.active) { $.each(group.layers, function(i, layer) { if (layer.active) { callback(layer); } }); } }); } self.start_runtime = function() { self.stop_runtime(); console.log("Runtime starting") bot = Date.now() last_frame = bot maintain_interval = setInterval(maintaince, 1000); phys_interval = setInterval(physics, physics_timing); process_painting = true; self.events.emit('start_runtime'); } self.stop_runtime = function() { console.log("Runtime stopping") clearInterval(maintain_interval) clearInterval(phys_interval) process_painting = false; self.events.emit('stop_runtime'); } self.events.on('preload_done', function() { self.start_runtime() }); self.runtime_frame = function() { physics(true); repaint(); } self.suspend_physics = function() { run_physics = false }; self.resume_physics = function() { run_physics = true }; } var runtime = new Runtime() <file_sep>/lib/layer/mc.js require('layer/mt'); var layer = runtime.add_layer('game.mc', { }); var parts = {}; new Gfx().preload('flame_perlin.png').then(function(img) { parts.n = img }) new Gfx().preload('skull.png').then(function(img) { parts.head = img }) new Gfx().preload('wheel_f.png').then(function(img) { parts.w_f = img }) new Gfx().preload('wheel_r.png').then(function(img) { parts.w_r = img }) var mc_anim = new Animation({ xw: 80, yh: 90, get_gfx: function() { var self = this; var gfx = this.gfx gfx.reset() var c = gfx.context var fades = require('state/mt').fades if (fades.fadeou != null) c.globalAlpha = 1 - fades.fadeou.get_pctdone() if (fades.fadein != null) c.globalAlpha = fades.fadein.get_pctdone() c.drawImage( parts.w_r.canvas, 20, 0, 40, 40 ) c.drawImage( parts.head.canvas, 0, 10, 70, 70 ) c.drawImage( parts.w_r.canvas, 0, 0, 40, 40 ) return gfx; }, }) var pulse_anim = new Animation({ xw: 32 * runtime.tiles.tiles_xw, yh: 32 * runtime.tiles.tiles_yh, get_gfx: function() { var self = this; var gfx = this.gfx gfx.reset() self.tile_x = mc_anim.tile_x - 8; self.tile_y = mc_anim.tile_y - 8; var c = gfx.context var fades = require('state/mt').fades if (fades.fadeou != null) c.globalAlpha = 1 - fades.fadeou.get_pctdone() if (fades.fadein != null) c.globalAlpha = fades.fadein.get_pctdone() c.fillStyle = gfx.color_linear( [191, 191, 191], [120, 184, 232], 1 ); var grad = c.createRadialGradient(0, 0, 0, 0, 0, 60) grad.addColorStop(0, '#6cb46c'); grad.addColorStop(1, '#446b44'); c.fillStyle = grad c.beginPath(); var t = require('state/mc').radius * runtime.tiles.tiles_xw || 150; c.arc(t, t, t, 0, 2*pi); //c.fill(); //c.fillRect(0, 0, gfx.xw(), gfx.yh()); return gfx; } }) layer.add_animation(pulse_anim) exports.layer = layer; exports.mc_anim = mc_anim; <file_sep>/fission_engine/js/noise.js //http://jsperf.com/lprng-vs-math-random function Noise(options) { $.extend(this, { width: undefined, height: undefined, depth: undefined, octaves: 1, perlin: false, seed: floor(Math.random() * Math.pow(2, 32)), }, options); var self = this var dims = 3; if (self.depth == undefined) { dims = 2 } if (self.height == undefined) { dims = 1 self.depth = null } if (self.width == undefined) throw "Must provide at least on dimension" var perm; [% WRAPPER scope %] var octave = 0 var dimensions = [self.width, self.height, self.depth] var rng = new lprng([self.seed]) var do_dim = function(dim) { if (dimensions[dim] == undefined) { return rng.prng(); } var result = [] for (var i = 0; i <= ceil(dimensions[dim] / (octave+1)); i++) { result[i] = do_dim(dim+1); } return result } perm = [] for ( ; octave < self.octaves; octave++) { perm[octave] = do_dim(0) } [% END %] var noise2 = function() { var result = [] for (var x = 0; x < self.width; x++) { result[x] = [] for (var y = 0; y < self.height; y++) { result[x][y] = 0; for (var octave = 0; octave < self.octaves; octave++) { var p = perm[octave] var octa_steps = (1 << octave) var base_x = x >> octave var base_y = y >> octave var frac_x = x & (octa_steps - 1) var frac_y = y & (octa_steps - 1) var i = 0 var diff_x = p[base_x][base_y] var diff_y = p[base_x][base_y] if (frac_x != 0) diff_x = p[base_x+1][base_y] - diff_x if (frac_y != 0) diff_y = p[base_x][base_y+1] - diff_y i += diff_x * (frac_x / octa_steps) + p[base_x][base_y] i += diff_y * (frac_y / octa_steps) + p[base_x][base_y] result[x][y] += i / 2 } result[x][y] /= octave } } return result for (var x = 0; x < width; x++) { result[x] = [] for (var y = 0; y < height; y++) { var xl = x - 1; xl = xl < 0 ? width-1 : xl var xr = x + 1; xr %= width var yt = y - 1; yt = yt < 0 ? height-1 : yt var yb = y + 1; yb %= height var m = 0 + perm[xl][yt] + perm[xr][yt] + perm[xl][yb] + perm[xr][yb] m /= 4 result[x][y] = m*m*m*(m*(m*6-15)+10) //result[x][y] = perm[x][y] } } return result } self.noise = function(start_x, start_y, start_z) { start_x = floor(start_x) start_y = floor(start_y) start_z = floor(start_z) if (dims == 2) return noise2(start_x, start_y) } [%# /* coherent noise function over 1, 2 or 3 dimensions */ /* (copyright <NAME>) */ #include <stdlib.h> #include <stdio.h> #include <math.h> #define B 0x100 #define BM 0xff #define N 0x1000 #define NP 12 /* 2^N */ #define NM 0xfff static p[B + B + 2]; static float g3[B + B + 2][3]; static float g2[B + B + 2][2]; static float g1[B + B + 2]; static start = 1; static void init(void); #define s_curve(t) ( t * t * (3. - 2. * t) ) #define lerp(t, a, b) ( a + t * (b - a) ) #define setup(i,b0,b1,r0,r1)\ t = vec[i] + N;\ b0 = ((int)t) & BM;\ b1 = (b0+1) & BM;\ r0 = t - (int)t;\ r1 = r0 - 1.; double noise1(double arg) { int bx0, bx1; float rx0, rx1, sx, t, u, v, vec[1]; vec[0] = arg; if (start) { start = 0; init(); } setup(0, bx0,bx1, rx0,rx1); sx = s_curve(rx0); u = rx0 * g1[ p[ bx0 ] ]; v = rx1 * g1[ p[ bx1 ] ]; return lerp(sx, u, v); } float noise2(float vec[2]) { int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; register i, j; if (start) { start = 0; init(); } setup(0, bx0,bx1, rx0,rx1); setup(1, by0,by1, ry0,ry1); i = p[ bx0 ]; j = p[ bx1 ]; b00 = p[ i + by0 ]; b10 = p[ j + by0 ]; b01 = p[ i + by1 ]; b11 = p[ j + by1 ]; sx = s_curve(rx0); sy = s_curve(ry0); #define at2(rx,ry) ( rx * q[0] + ry * q[1] ) q = g2[ b00 ] ; u = at2(rx0,ry0); q = g2[ b10 ] ; v = at2(rx1,ry0); a = lerp(sx, u, v); q = g2[ b01 ] ; u = at2(rx0,ry1); q = g2[ b11 ] ; v = at2(rx1,ry1); b = lerp(sx, u, v); return lerp(sy, a, b); } float noise3(float vec[3]) { int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; register i, j; if (start) { start = 0; init(); } setup(0, bx0,bx1, rx0,rx1); setup(1, by0,by1, ry0,ry1); setup(2, bz0,bz1, rz0,rz1); i = p[ bx0 ]; j = p[ bx1 ]; b00 = p[ i + by0 ]; b10 = p[ j + by0 ]; b01 = p[ i + by1 ]; b11 = p[ j + by1 ]; t = s_curve(rx0); sy = s_curve(ry0); sz = s_curve(rz0); #define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0); q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0); a = lerp(t, u, v); q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0); q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0); b = lerp(t, u, v); c = lerp(sy, a, b); q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1); q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1); a = lerp(t, u, v); q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1); q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1); b = lerp(t, u, v); d = lerp(sy, a, b); return lerp(sz, c, d); } static void normalize2(float v[2]) { float s; s = sqrt(v[0] * v[0] + v[1] * v[1]); v[0] = v[0] / s; v[1] = v[1] / s; } static void normalize3(float v[3]) { float s; s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] = v[0] / s; v[1] = v[1] / s; v[2] = v[2] / s; } static void init(void) { int i, j, k; for (i = 0 ; i < B ; i++) { p[i] = i; g1[i] = (float)((random() % (B + B)) - B) / B; for (j = 0 ; j < 2 ; j++) g2[i][j] = (float)((random() % (B + B)) - B) / B; normalize2(g2[i]); for (j = 0 ; j < 3 ; j++) g3[i][j] = (float)((random() % (B + B)) - B) / B; normalize3(g3[i]); } while (--i) { k = p[i]; p[i] = p[j = random() % B]; p[j] = k; } for (i = 0 ; i < B + 2 ; i++) { p[B + i] = p[i]; g1[B + i] = g1[i]; for (j = 0 ; j < 2 ; j++) g2[B + i][j] = g2[i][j]; for (j = 0 ; j < 3 ; j++) g3[B + i][j] = g3[i][j]; } } %] } <file_sep>/fission_engine/js/events.js function Events() { var listeners = {} var self = this; $.extend(this, { on: function(type, cb) { if (!$.isArray(listeners[type])) listeners[type] = [] if (listeners[type].indexOf(cb) < 0) listeners[type].push(cb) return this; }, once: function(type, cb) { var cd_observer = function() { var c = cb.frame() if (c != cb) { this.off(type, cd_observer) return c.apply(this, arguments) } } var observer = function() { this.off(type, observer) return cb.apply(this, arguments) } if (cb instanceof Cooldown) { this.on(type, cd_observer) } else { this.on(type, observer) } return this; }, exists: function(type) { if (!$.isArray(listeners[type])) return false; if (listeners[type].length > 0) return true; return false; }, emit: function(type) { var result = [] if (!$.isArray(listeners[type])) listeners[type] = [] var args = Array.prototype.slice.call(arguments, 1) var cbs = listeners[type] for (var i in cbs) { var to_push; try { if (cbs[i] instanceof Cooldown) { // Cooldown returns itself or a function cbs[i] = cbs[i].frame(); } var cb = cbs[i]; if ($.isFunction(cb)) { to_push = cb.apply(self, args) } } catch(e) { if (e instanceof Cooldown) { to_push = e } else { warn(e); } } if (to_push instanceof Cooldown) { to_push.result = cbs[i]; cbs[i] = to_push; } result.push(to_push); } return result }, call: function(type) { var result = this.emit.apply(this, arguments) if (result.length > 1) warn("Too many results, choosing the first one") return result[0] }, off: function(type, cb) { if (cb == undefined) throw new Error("You cannot remove all listeners on an event") //if (!$.isFunction(cb) && !(cb instanceof Cooldown)) // throw new Error("You must pass a listener to Event.off") var index = listeners[type].indexOf(cb) if (index != undefined && index >= 0) { listeners[type].splice(index, 1); } return this; }, }) } <file_sep>/fission_engine/js/cooldown.js var seconds_match = /^(\d)*s$/; function Cooldown(frames, inital_result) { frames = frames || 10 if ($.type(frames) == "string") { var seconds = frames.match(seconds_match) if (seconds) { frames = seconds[1] * runtime.fps } else { frames = parseInt(frames) } } var total = frames var result = false this.set_result = function(new_result) { result = new_result } this.action_id = function() { if (result instanceof Action) return result.id() return } this.set_result(inital_result) this.frame = function() { frames-- if (frames <= 0) return result return this } this.reset = function() { frames = total } this.is_done = function() { return frames >= total } this.get_remaining = function() { return total - frames } this.get_pctdone = function() { return (total - frames) / total } }
f87e42481c8e0d0edcf7450a120e4a45559096ce
[ "JavaScript" ]
21
JavaScript
atrodo/ld34
d8fdc0050cfb58850a34e6bf76253b70daff0e14
1cc5ecf9c52fbfe9c9c111a68c760175e5943bef
refs/heads/master
<file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import logo from './logo.svg'; import './App.css'; class Second extends Component { constructor(){ super(); this.state={} } goToThird() { var data = {}; data.key = "current"; data.val = 'Third'; this.props.changeviewManager(data); } goToFirst() { var data = {}; data.key = "current"; data.val = 'First'; this.props.changeviewManager(data); } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> second view with 2 button </p> <button className="existing-profile" onClick={()=>this.goToFirst()}> <span> go to prev </span> <span className="fontcon-arrow-right"></span> </button> <button className="existing-profile" onClick={()=>this.goToThird()}> <span> go to Next </span> <span className="fontcon-arrow-right"></span> </button> </div> ); } } export default Second; Second.PropTypes = { changeviewManager: PropTypes.func.isRequired }
f661d839d138bc8f8ad5382c361e3d987092807a
[ "JavaScript" ]
1
JavaScript
uiyuvi/react-navigation-without-router
02069826bfa2d1446785807a23ac2be1036d5420
4d9f0415de8e3921484874bf0ca597ddcc0bf7e6
refs/heads/main
<repo_name>jihyuk124/Dazy<file_sep>/premake/Utils.lua function get_platforms() if _ACTION == "android-studio" then return { "armeabi-v7a", "arm64-v8a", "x86", "x86_64" } end if os.ishost( "windows" ) then return { "x64" } end -- Get the ID for the host processor architecture local arch = os.outputof( "uname -m" ) return { arch } end<file_sep>/Dazy/src/Window/Window.h #pragma once #include <Core.h> #include "entt.hpp" struct GLFWwindow; namespace Dazy { struct WindowData { std::string title; uint32_t width; uint32_t height; bool VSync; WindowData(const std::string& title = "Dazy Engine", uint32_t width = 1280, uint32_t height = 720) : title(title), width(width), height(height), VSync(false) { } }; // Interface representing a desktop system based Window class Window { public: template <typename ... Args> using EventCallbackFn = std::function<void(Args...)>; Window(const WindowData& data) : nativeWindow(nullptr), data(data) { } Window(const Window& other) = delete; Window(const Window&& other) = delete; Window& operator=(const Window& other) = delete; Window& operator=(const Window&& other) = delete; ~Window() {}; void Init(); void DeInit(); void OnUpdate(); const bool IsCloseRequested() const; void SetVSync(const bool enabled); const WindowData& GetWindowData() const { return data; } private: GLFWwindow* nativeWindow; union { struct { std::string title; uint32_t width; uint32_t height; bool VSync; }; WindowData data; }; }; } <file_sep>/ThirdParty/glad.lua return function() warnings 'Off' language 'C' includedirs { 'ThirdParty/glad/include' } files { 'ThirdParty/glad/include/glad/glad.h', 'ThirdParty/glad/include/KHR/khrplatform.h', 'ThirdParty/glad/src/glad.c' } filter "system:windows" systemversion "latest" filter "configurations:Debug" runtime "Debug" symbols "on" filter "configurations:Release" runtime "Release" optimize "on" end<file_sep>/ThirdParty/glm.lua return function() warnings 'Off' includedirs { 'ThirdParty/glm' } files { 'ThirdParty/glm/glm/**.h', 'ThirdParty/glm/glm/**.inl', 'ThirdParty/glm/glm/**.hpp', 'ThirdParty/glm/glm/**.cpp' } end <file_sep>/premake/Defaults.lua cppdialect "C++17" flags { "MultiProcessorCompile" } rtti "Off" objdir "../out/obj" --targetdir '../out/%{iif(prj.kind == "StaticLib" or prj.kind == "SharedLib","lib","bin")}/%{cfg.platform}/%{cfg.buildcfg}' targetdir '../out/bin/%{cfg.platform}-%{cfg.buildcfg}' -- warnings 'Extra' warnings 'Default' buildoptions { "/utf-8" } filter "configurations:Debug" optimize "Off" symbols "On" defines { "_DEBUG" } filter "configurations:Release" optimize "Full" symbols "Off" defines { "_RELEASE", "NDEBUG" } filter "system:windows" toolset "msc" defines { "_CRT_SECURE_NO_WARNINGS" } systemversion "latest" staticruntime "On" filter "system:not windows" toolset "gcc" filter "system:linux" debugenvs { "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../%{OUTDIR}" } systemversion "latest" staticruntime "On" filter { } <file_sep>/Dazy/src/Window/Window.cpp #include "Window.h" #include <GLFW/glfw3.h> #include <glad/glad.h> namespace Dazy { static bool GLFWInitialized = false; static void GLFWErrorCallback(int error, const char* description) { LOG_CORE_ERROR("GLFW Error ({0}): {1}", error, description); } void Window::Init() { if (!GLFWInitialized) { // TODO: glfwTerminate on system shutdown int success = glfwInit(); ASSERT_MSG(success, "Could not intialize GLFW!"); glfwSetErrorCallback(GLFWErrorCallback); GLFWInitialized = true; } LOG_CORE_INFO("Creating window {0} ({1}, {2})", title, width, height); nativeWindow = glfwCreateWindow((int)width, (int)height, title.c_str(), nullptr, nullptr); glfwMakeContextCurrent(nativeWindow); int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); ASSERT_MSG(status, "Failed to initialize Glad!"); LOG_CORE_INFO("OpenGL Info:"); LOG_CORE_INFO(" Vendor: {0}", glGetString(GL_VENDOR)); LOG_CORE_INFO(" Renderer: {0}", glGetString(GL_RENDERER)); LOG_CORE_INFO(" Version: {0}", glGetString(GL_VERSION)); glfwSetWindowUserPointer(nativeWindow, &data); SetVSync(true); glfwSetWindowSizeCallback(nativeWindow, [](GLFWwindow* nativeWindow, int width, int height) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); data.width = width; data.height = height; LOG_DEBUG("WindowResize : {0}, {1}", width, height); }); /*glfwSetWindowCloseCallback(nativeWindow, [](GLFWwindow* nativeWindow) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); LOG_DEBUG("WindowClose"); });*/ glfwSetKeyCallback(nativeWindow, [](GLFWwindow* nativeWindow, int key, int scancode, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); switch (action) { case GLFW_PRESS: { LOG_DEBUG("KeyPress : KeyCode({0}), repeat(false)", key); break; } case GLFW_RELEASE: { LOG_DEBUG("KeyRelease : {0}", key); break; } case GLFW_REPEAT: { LOG_DEBUG("KeyPress : KeyCode({0}), repeat(true)", key); break; } } }); glfwSetMouseButtonCallback(nativeWindow, [](GLFWwindow* nativeWindow, int button, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); switch (action) { case GLFW_PRESS: { LOG_DEBUG("MouseButtonPress : Button({0})", button); break; } case GLFW_RELEASE: { LOG_DEBUG("MouseButtonRelease : Button({0})", button); break; } } }); glfwSetScrollCallback(nativeWindow, [](GLFWwindow* nativeWindow, double xOffset, double yOffset) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); LOG_DEBUG("Scroll : XOffset({0}), YOffset{1}", xOffset, yOffset); }); glfwSetCursorPosCallback(nativeWindow, [](GLFWwindow* nativeWindow, double xPos, double yPos) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(nativeWindow); LOG_DEBUG("CursorPos : XPos({0}), YPos{1}", xPos, yPos); }); } void Window::DeInit() { glfwDestroyWindow(nativeWindow); glfwTerminate(); LOG_DEBUG("Window terminated"); } void Window::OnUpdate() { glfwSwapBuffers(nativeWindow); glfwPollEvents(); } const bool Window::IsCloseRequested() const { return glfwWindowShouldClose(nativeWindow); } void Window::SetVSync(const bool enabled) { if (enabled) glfwSwapInterval(1); else glfwSwapInterval(0); data.VSync = enabled; } } <file_sep>/README.md # Dazy Dazy Engine <file_sep>/ThirdParty/glfw.lua return function() warnings 'Off' language 'C' files { 'ThirdParty/glfw/include/GLFW/glfw3.h', 'ThirdParty/glfw/include/GLFW/glfw3native.h', 'ThirdParty/glfw/src/glfw_config.h', 'ThirdParty/glfw/src/context.c', 'ThirdParty/glfw/src/init.c', 'ThirdParty/glfw/src/input.c', 'ThirdParty/glfw/src/monitor.c', 'ThirdParty/glfw/src/vulkan.c', 'ThirdParty/glfw/src/window.c' } filter 'system:linux' pic 'On' systemversion 'latest' staticruntime 'On' files { 'ThirdParty/glfw/src/x11_init.c', 'ThirdParty/glfw/src/x11_monitor.c', 'ThirdParty/glfw/src/x11_window.c', 'ThirdParty/glfw/src/xkb_unicode.c', 'ThirdParty/glfw/src/posix_time.c', 'ThirdParty/glfw/src/posix_thread.c', 'ThirdParty/glfw/src/glx_context.c', 'ThirdParty/glfw/src/egl_context.c', 'ThirdParty/glfw/src/osmesa_context.c', 'ThirdParty/glfw/src/linux_joystick.c' } defines { '_GLFW_X11' } filter 'system:windows' systemversion 'latest' staticruntime 'On' files { 'ThirdParty/glfw/src/win32_init.c', 'ThirdParty/glfw/src/win32_joystick.c', 'ThirdParty/glfw/src/win32_monitor.c', 'ThirdParty/glfw/src/win32_time.c', 'ThirdParty/glfw/src/win32_thread.c', 'ThirdParty/glfw/src/win32_window.c', 'ThirdParty/glfw/src/wgl_context.c', 'ThirdParty/glfw/src/egl_context.c', 'ThirdParty/glfw/src/osmesa_context.c' } defines { '_GLFW_WIN32', '_CRT_SECURE_NO_WARNINGS' } links { 'opengl32.lib' } filter 'configurations:Debug' runtime 'Debug' symbols 'on' filter 'configurations:Release' runtime 'Release' optimize 'on' end<file_sep>/Dazy/src/Events/Event.h #pragma once #include "Core.h" namespace Dazy { #define DECLARE_EVENT_NAME(type) const char* GetName() const { return #type; }\ explicit operator std::string() const { return GetName();} //namespace Event //{ // struct WindowResize // { // unsigned int width, height; // }; // struct WindowClose // { // }; // struct AppTickEvent // { // }; // class AppUpdateEvent : public Event // { // public: // AppUpdateEvent() = default; // EVENT_CLASS_TYPE(AppUpdate) // EVENT_CLASS_CATEGORY(EventCategoryApplication) // }; // class AppRenderEvent : public Event // { // public: // AppRenderEvent() = default; // EVENT_CLASS_TYPE(AppRender) // EVENT_CLASS_CATEGORY(EventCategoryApplication) // }; //} /*enum class Event : entt::hashed_string::hash_type; using EventRegistry = entt::basic_registry<Event>;*/ //using Event = entt::hashed_string; //using EventType = entt::hashed_string::hash_type; //using Event = entt::hashed_string::data; //class EventHandler //{ // //static Add(); //private: // static EventRegistry eventReg; //}; /*class Event { using value_type = entt::basic_hashed_string<char>; Event(const char* eventName) : value(eventName) { } bool operator==(const Event& e) { return value == e.value; } private: value_type value; };*/ } <file_sep>/Dazy/src/Core/Log.h #pragma once #include "Base.h" #pragma warning(push, 0) #include <spdlog/spdlog.h> #include <spdlog/fmt/ostr.h> #pragma warning(pop) namespace Dazy { using LogLevel = spdlog::level::level_enum; class Logger { public: static void Init(); static Ref<spdlog::logger>& GetCore() { return coreLogger; } static Ref<spdlog::logger>& Get() { return defaultLogger; } private: static Ref<spdlog::logger> coreLogger; static Ref<spdlog::logger> defaultLogger; }; } // Core logger #ifdef _DEBUG #define LOG_CORE_TRACE(...) ::Dazy::Logger::GetCore()->trace(__VA_ARGS__) #define LOG_CORE_DEBUG(...) ::Dazy::Logger::GetCore()->debug(__VA_ARGS__) #else #define LOG_CORE_TRACE(...) ((void)0) #define LOG_CORE_DEBUG(...) ((void)0) #endif #define LOG_CORE_INFO(...) ::Dazy::Logger::GetCore()->info(__VA_ARGS__) #define LOG_CORE_WARN(...) ::Dazy::Logger::GetCore()->warn(__VA_ARGS__) #define LOG_CORE_ERROR(...) ::Dazy::Logger::GetCore()->error(__VA_ARGS__) #define LOG_CORE_CRITICAL(...) ::Dazy::Logger::GetCore()->critical(__VA_ARGS__) #define LOG_CORE(level, ...) ::Dazy::Logger::GetCore()->log(level, __VA_ARGS__) // Default logger #ifdef _DEBUG #define LOG_TRACE(...) ::Dazy::Logger::Get()->trace(__VA_ARGS__) #define LOG_DEBUG(...) ::Dazy::Logger::Get()->debug(__VA_ARGS__) #else #define LOG_TRACE(...) ((void)0) #define LOG_DEBUG(...) ((void)0) #endif #define LOG_INFO(...) ::Dazy::Logger::Get()->info(__VA_ARGS__) #define LOG_WARN(...) ::Dazy::Logger::Get()->warn(__VA_ARGS__) #define LOG_ERROR(...) ::Dazy::Logger::Get()->error(__VA_ARGS__) #define LOG_CRITICAL(...) ::Dazy::Logger::Get()->critical(__VA_ARGS__) #define LOG(level, ...) ::Dazy::Logger::Get()->log(level, __VA_ARGS__)<file_sep>/Dazy/src/Core/Core.h #pragma once #include "PlatformDetection.h" #include "PrimitiveTypes.h" #include "Base.h" #include "Log.h" #include "Assertion.h"<file_sep>/premake/Sandbox.lua function add_sandbox() project( "Sandbox" ) kind "ConsoleApp" location "Sandbox" staticruntime "on" files { "%{prj.name}/**.h", "%{prj.name}/**.cpp", } includedirs { "Dazy/src", "Dazy/src/Core", "ThirdParty/spdlog/include", "ThirdParty", } links("Dazy") end<file_sep>/Sandbox/src/SandboxApp.cpp #include "SandboxApp.h" // entry point #include "EntryPoint.h" Dazy::Application* Dazy::CreateApplication() { return new Sandbox(); } Sandbox::Sandbox() { } Sandbox::~Sandbox() { } <file_sep>/premake/Dazy.lua function add_dazy() project( "Dazy" ) kind "StaticLib" location "Dazy" staticruntime "on" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp", } includedirs { "%{prj.name}/src", "%{prj.name}/src/Core", "ThirdParty/spdlog/include", "ThirdParty/glfw/include", } links{ "glfw" } end<file_sep>/Dazy/src/Core/PrimitiveTypes.h #pragma once using uint8 = unsigned char; using uint16 = unsigned short int; using uint32 = unsigned int; using uint64 = unsigned long long; using int8 = signed char; using int16 = signed short int; using int32 = signed int; using int64 = signed long long; static_assert(sizeof(int8) == 1, "int8 size must be 1 bytes."); static_assert(sizeof(int16) == 2, "int16 size must be 2 bytes."); static_assert(sizeof(int32) == 4, "int32 size must be 4 bytes."); static_assert(sizeof(int64) == 8, "int64 size must be 8 bytes."); using wchar = wchar_t; // using tchar = wchar; /* // An 8-bit unicode character type. In-memory only. 8-bit representation. (since C++20) using char8 = char8_t; // A 16-bit unicode character type. In-memory only. using char16 = char16_t; // A 32-bit unicode character type. In-memory only. 32-bit representation. using char32 = char32_t; */ <file_sep>/Dazy/src/Application.cpp #include "Application.h" #include "Log.h" #include "Window/Window.h" #include <glad/glad.h> #include "glm.hpp" namespace Dazy { Application* Application::instance = nullptr; Application::Application(const char* name) { window = std::unique_ptr<Window>(new Window(WindowData())); window->Init(); glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); float vertices[3 * 3] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glGenBuffers(1, &indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); unsigned int indices[3] = { 0, 1, 2 }; glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); std::string vertexSrc = R"( #version 330 core layout(location = 0) in vec3 a_Position; out vec3 v_Position; void main() { v_Position = a_Position; gl_Position = vec4(a_Position, 1.0); } )"; std::string fragmentSrc = R"( #version 330 core layout(location = 0) out vec4 color; in vec3 v_Position; void main() { color = vec4(v_Position * 0.5 + 0.5, 1.0); } )"; shader.reset(new Shader(vertexSrc, fragmentSrc)); } Application::~Application() { window->DeInit(); } Application* Application::GetInstance() { if (!Application::instance) Application::instance = CreateApplication(); return Application::instance; } void Application::Run() { while (!window->IsCloseRequested()) { glClearColor(0.1, 0.1, 0.1, 1); glClear(GL_COLOR_BUFFER_BIT); shader->Bind(); glBindVertexArray(vertexArray); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr); window->OnUpdate(); } } } <file_sep>/Dazy/src/Platform/Windows/WindowsWindow.cpp //#include "WindowsWindow.h" // //#include <GLFW/glfw3.h> //#include <glad/glad.h> // //namespace Dazy //{ // static bool GLFWInitialized = false; // // static void GLFWErrorCallback(int error, const char* description) // { // LOG_CORE_ERROR("GLFW Error ({0}): {1}", error, description); // } // // Window* Window::Create(const WindowProps& props) // { // return new WindowsWindow(props); // } // // WindowsWindow::WindowsWindow(const WindowProps& props) // { // Init(props); // } // // WindowsWindow::~WindowsWindow() // { // Shutdown(); // } // // void WindowsWindow::Init(const WindowProps& props) // { // data.title = props.title; // data.width = props.width; // data.height = props.height; // // LOG_CORE_INFO("Creating window {0} ({1}, {2})", props.title, props.width, props.height); // // if (!GLFWInitialized) // { // // TODO: glfwTerminate on system shutdown // int success = glfwInit(); // ASSERT_MSG(success, "Could not intialize GLFW!"); // // glfwSetErrorCallback(GLFWErrorCallback); // GLFWInitialized = true; // } // // window = glfwCreateWindow((int)props.width, (int)props.height, data.title.c_str(), nullptr, nullptr); // glfwMakeContextCurrent(window); // // int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); // ASSERT_MSG(status, "Failed to initialize Glad!"); // // glfwSetWindowUserPointer(window, &data); // SetVSync(true); // // //glfwSetWindowSizeCallback(window, [](GLFWwindow* window, int width, int height) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // data.width = width; // // data.height = height; // // // WindowResizeEvent event(width, height); // // data.eventCallback(event); // //}); // // //glfwSetWindowCloseCallback(window, [](GLFWwindow* window) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // WindowCloseEvent event; // // data.eventCallback(event); // //}); // // //glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // // switch (action) // // { // // case GLFW_PRESS: // // { // // KeyPressedEvent event(key, 0); // // data.eventCallback(event); // // break; // // } // // case GLFW_RELEASE: // // { // // KeyReleasedEvent event(key); // // data.eventCallback(event); // // break; // // } // // case GLFW_REPEAT: // // { // // KeyPressedEvent event(key, 1); // // data.eventCallback(event); // // break; // // } // // } // //}); // // //glfwSetMouseButtonCallback(window, [](GLFWwindow* window, int button, int action, int mods) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // // switch (action) // // { // // case GLFW_PRESS: // // { // // MouseButtonPressedEvent event(button); // // data.eventCallback(event); // // break; // // } // // case GLFW_RELEASE: // // { // // MouseButtonReleasedEvent event(button); // // data.eventCallback(event); // // break; // // } // // } // //}); // // //glfwSetScrollCallback(window, [](GLFWwindow* window, double xOffset, double yOffset) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // // MouseScrolledEvent event((float)xOffset, (float)yOffset); // // data.eventCallback(event); // //}); // // //glfwSetCursorPosCallback(window, [](GLFWwindow* window, double xPos, double yPos) // //{ // // WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); // // // MouseMovedEvent event((float)xPos, (float)yPos); // // data.eventCallback(event); // //}); // } // // void WindowsWindow::Shutdown() // { // glfwDestroyWindow(window); // } // // void WindowsWindow::OnUpdate() // { // glfwPollEvents(); // glfwSwapBuffers(window); // } // // void WindowsWindow::SetVSync(bool enabled) // { // if (enabled) // glfwSwapInterval(1); // else // glfwSwapInterval(0); // // data.VSync = enabled; // } // // bool WindowsWindow::IsVSync() const // { // return data.VSync; // } //} <file_sep>/Sandbox/src/SandboxApp.h #pragma once #include "Application.h" class Sandbox : public Dazy::Application { public: Sandbox(); ~Sandbox(); };<file_sep>/Dazy/src/Core/Log.cpp #include "Log.h" #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/basic_file_sink.h> namespace Dazy { Ref<spdlog::logger> Logger::coreLogger; Ref<spdlog::logger> Logger::defaultLogger; void Logger::Init() { std::vector<spdlog::sink_ptr> logSinks; logSinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); logSinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("Dazy.log", true)); logSinks[0]->set_pattern("%^[%T] %n: %v%$"); logSinks[1]->set_pattern("[%T] [%l] %n: %v"); coreLogger = std::make_shared<spdlog::logger>("Dazy", begin(logSinks), end(logSinks)); spdlog::register_logger(coreLogger); defaultLogger = std::make_shared<spdlog::logger>("APP", begin(logSinks), end(logSinks)); spdlog::register_logger(defaultLogger); #ifdef _DEBUG coreLogger->set_level(spdlog::level::trace); coreLogger->flush_on(spdlog::level::trace); defaultLogger->set_level(spdlog::level::trace); defaultLogger->flush_on(spdlog::level::trace); #else coreLogger->set_level(spdlog::level::info); coreLogger->flush_on(spdlog::level::info); defaultLogger->set_level(spdlog::level::info); defaultLogger->flush_on(spdlog::level::info); #endif } } <file_sep>/Dazy/src/Core/Assertion.h #pragma once #include "PlatformDetection.h" #include "Log.h" // debug break #ifdef _DEBUG #if defined(_PLATFORM_WINDOWS) #define DEBUGBREAK() __debugbreak() #elif defined(_PLATFORM_LINUX) #include <signal.h> #define DEBUGBREAK() raise(SIGTRAP) #else #error "Platform doesn't support debugbreak yet!" #endif #define _ENABLE_ASSERTS #else #define DEBUGBREAK() #endif #ifdef _ENABLE_ASSERTS #define ASSERT(expr) assert(expr) #define ASSERT_MSG(expr, msg) assert((expr)&&(msg)) #else #define ASSERT(expr) ((void)0) #define ASSERT_MSG(expr, msg) ((void)0) #endif<file_sep>/Dazy/src/Application.h #pragma once #include "Core.h" #include "Graphics/Shader.h" int main(int argc, char** argv); namespace Dazy { class Window; class Application { protected: Application(const char* name = "Dazy App"); public: virtual ~Application(); static Application* GetInstance(); void Run(); private: std::unique_ptr<Window> window; bool running = true; unsigned int vertexArray, vertexBuffer, indexBuffer; std::unique_ptr<Shader> shader; static Application* instance; friend int ::main(int argc, char** argv); }; // To be defined in client Application* CreateApplication(); } <file_sep>/premake5.lua require 'premake/ThirdParty' workspace 'Dazy' architecture 'x64' configurations { 'Debug', 'Release' } flags { "MultiProcessorCompile" } outputdir = '%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}' targetdir ('out/bin/' .. outputdir .. '/%{prj.name}') objdir ('out/bin-int' .. outputdir .. '/%{prj.name}') -- ThirdParty add_third_party('glfw') add_third_party('glad') add_third_party('glm') group '' IncludeDir = {} IncludeDir['glfw'] = 'ThirdParty/glfw/include' IncludeDir['glad'] = 'ThirdParty/glad/include' IncludeDir['entt'] = 'ThirdParty/entt/single_include/entt' IncludeDir['glm'] = 'ThirdParty/glm/glm' project 'Dazy' location 'Dazy' kind 'StaticLib' language 'C++' buildoptions '/utf-8' files { '%{prj.name}/src/**.h', '%{prj.name}/src/**.cpp', } includedirs { --'%{prj.name}/src', '%{prj.name}/src/Core', 'ThirdParty/spdlog/include', 'ThirdParty/spdlog/include/spdlog/fmt', '%{IncludeDir.glfw}', '%{IncludeDir.glad}', '%{IncludeDir.entt}', '%{IncludeDir.glm}', } links(third_party_libraries) filter 'system:windows' cppdialect 'C++17' systemversion 'latest' defines { 'GLFW_INCLUDE_NONE', '_CRT_SECURE_NO_WARNINGS', } filter 'configurations:Debug' defines '_DEBUG' symbols 'On' filter 'configurations:Release' defines '_RELEASE' optimize 'On' project 'Sandbox' location 'Sandbox' kind 'ConsoleApp' language 'C++' buildoptions '/utf-8' files { '%{prj.name}/src/**.h', '%{prj.name}/src/**.cpp', '%{wks}/ThirdParty/glm/glm/**.hpp', '%{wks}/ThirdParty/glm/glm/**.inl', } includedirs { --'%{prj.name}/src', 'Dazy/src', 'Dazy/src/Core', 'ThirdParty/spdlog/include', 'ThirdParty/spdlog/include/spdlog/fmt', '%{IncludeDir.entt}', '%{IncludeDir.glm}', } links { 'Dazy' } filter 'system:windows' cppdialect 'C++17' systemversion 'latest' filter 'configurations:Debug' defines '_DEBUG' symbols 'On' filter 'configurations:Release' defines '_RELEASE' optimize 'On'<file_sep>/Dazy/src/Core/PlatformDetection.h #pragma once // Platform detect #ifdef _WIN32 #ifdef _WIN64 #define _PLATFORM_WINDOWS #else #error "Windows X86 is not supported" #endif #elif defined(__APPLE__) || defined(__MACH__) #include <TargetConditionals.h> #if TARGET_IPHONE_SIMULATOR == 1 #error "IOS simulator not supported" #elif TARGET_OS_IPHONE == 1 #define _PLATFORM_IOS #error "IOS is not supported" #elif TARGET_OS_MAC == 1 #define _PLATFORM_MACOS #else #error "Unknown Apple platform" #endif #elif defined(__ANDROID__) #define _PLATFORM_ANDROID #error "Android is not supported" #elif defined(__linux__) #define _PLATFORM_LINUX #else #error "Unknown platform" #endif<file_sep>/Dazy/src/EntryPoint.h #pragma once #include "Core.h" #include "Application.h" #ifdef _PLATFORM_WINDOWS int main(int argc, char** argv) { Dazy::Logger::Init(); auto app = Dazy::Application::GetInstance(); app->Run(); delete app; } #endif
ee4ff3fceee00c19eacc2ed4e7ef82939f35633d
[ "Markdown", "C", "C++", "Lua" ]
24
Lua
jihyuk124/Dazy
8d3150f611d1750088e96207b4a3e3cef545b861
ebc89d05b868348e8bde9fba61e56e73303a78bd
refs/heads/master
<file_sep>#! /bin/bash lsmod |tail -n +2 |cut -f1 -d' ' | sort <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-lightdm APT-INIT APT-INSTALL xfce4-minimal APT-INSTALL xfce4-terminal xfce4-appfinder thunar APT-CLEAN ADD xfce4-settings.tgz /var/tmp/ RUN "cd /home/altlinux/.config; tar -xf /var/tmp/xfce4-settings.tgz; " RUN rm -f /var/tmp/xfce4-settings.tgz COMMIT altlinux-p8-clb-xfce CLEAN <file_sep>#! /bin/bash metafiles_cpio="/lib/modules/__KV__/modules.builtin /lib/modules/__KV__/modules.order" metafiles_squashfs="$metafiles_cpio /boot/System.map-__KV__ /boot/config-__KV__" function usage() { echo -e "Usage:" echo "$0 <kernel> <img-type> <modules-list-file> [<docker-container-id>]" echo "img-type: squashfs, cpio" echo "if <docker-container-id> is specified, this script will be run inside this container." echo "otherwise it will be run in your host system." } function err_exit() { [ -n "$1" ] && echo -e "$1\n" usage exit 1 } function mod_dep_info() { local MODNAME=$1 # Get full path to a module file. Must be exist. local MODPATH=$(modinfo -k $KERN_VER -F filename $MODNAME) if [ -z "$MODPATH" ]; then echo -n "Will lookup '$MODNAME' in buildin modules... " >&2 # There are a great mess with - and _ in module names MODNAME=$(echo $MODNAME | sed -r -e 's/[_-]/[_-]/g') [ -r "$BUILDIN_MODULES" ] && grep -q "/${MODNAME}\.ko$" $BUILDIN_MODULES && echo "found." >&2 # if found, will not print a module name, but return without error. Otherwise, return with error. return $? fi # Get list of firmware files, required for this module local FIRMWARE=$(modinfo -k $KERN_VER -F firmware $MODNAME) # Get list of dependencies modules. local DEPMODS=$(modinfo -k $KERN_VER -F depends $MODNAME) # If we have dependencies modules, then recursively get full path of them, # its firmwares and further dependencies. if [ -n "$DEPMODS" ]; then for MODULE in $(echo $DEPMODS |tr ',' ' '); do mod_dep_info $MODULE done fi # Print results on STDOUT echo $MODPATH if [ -n "$FIRMWARE" ]; then for FW_FILE in $FIRMWARE; do echo "/lib/firmware/$FW_FILE" done fi } [ `whoami` == 'root' ] || { echo 'Wonna be a root' exit 1 } [ -w "." ] || err_exit "Current directory is not writable" [ -z "$1" ] && err_exit "Please specify kernel version (e.g. \`uname -r\`)" KERN_VER=$1 [ -z "$2" ] && err_exit "Please specify image type (squashfs/cpio)" IMG_TYPE=$2 echo $IMG_TYPE |grep -E -q "^(squashfs|cpio)$" || err_exit "Unsupported image type $IMG_TYPE" [ -z "$3" ] && err_exit "Please specify modules list file" MODLIST="$3" [ -r "$MODLIST" ] || err_exit "Can't read modules list file $MODLIST" IMG_NAME="$(basename ${MODLIST}|sed -e 's/modlist/modules/').${KERN_VER}.${IMG_TYPE}" BUILDIN_MODULES="/lib/modules/${KERN_VER}/modules.builtin" # If docker CID specified... if [ -n "$4" ]; then CID=$4 # this container must be exist and running if ! docker ps |tail -n +2 |grep -q "^$CID " ; then err_exit "No running docker container $CID found" fi # Copy this script and modlist inside the container docker cp -L $0 $CID:/usr/local/bin/ docker cp -L $MODLIST $CID:/var/tmp/ echo $(basename $0) will be executed in container $CID. # Run this script inside container, work dir: /var/tmp docker exec $CID bash -c "cd /var/tmp; /usr/local/bin/$(basename $0) $KERN_VER $IMG_TYPE /var/tmp/$(basename $MODLIST)" [ $? -gt 0 ] && err_exit "Error creating image with modules" # And copy results back into host system, to the current dir echo "Copying modules image from container to the current directory..." docker cp $CID:/var/tmp/$IMG_NAME ./ ls -l ./$IMG_NAME exit $? fi # Check if required kernel version is installed [ -d /lib/modules/$KERN_VER -a -r /lib/modules/$KERN_VER ] || { err_exit "Can't read /lib/modules/$KERN_VER dir, wrong kernel version?" } DO_DEPMOD=0 if [ "$IMG_TYPE" == "squashfs" ]; then MKSQAUSH=$(which mksquashfs) [ -z "$MKSQAUSH" ] && err_exit "For image type '$IMG_TYPE' there are mksquashfs utility required." DO_DEPMOD=1 fi TDIR=`mktemp -d` # Clean tmp dir if exit by error trap 'rm -rf "${TDIR}" >/dev/null 2>&1; echo "Emergency exit on error" >&2; exit 1' TERM INT echo "Copy modules..." cat $MODLIST | grep -E "^[a-zA-Z0-9/]" | while read MODULE; do if echo $MODULE |grep -q "^/"; then # If it absolute path then just copy this file FILE=$MODULE [ -r "$FILE" ] || { echo "File $FILE not found, stop" >&2 kill $$ exit 1 } echo $FILE else # Module name assumed if ! mod_dep_info $MODULE; then echo "Module $MODULE not found, stop" >&2 kill $$ exit 1 fi fi # Get list of found modules & firmware on STDIN and copy each file to temporary dir. # Some of (firmware) files can be missed. done | sort -u |xargs -I {} install -D -m 0600 {} ${TDIR}/{} METAFILES="$(eval "echo \$metafiles_$IMG_TYPE")" for MF in $METAFILES; do MF=$(echo $MF |sed -e "s/__KV__/$KERN_VER/g") if [ ! -r "$MF" ]; then echo "File $MF not found, stop" >&2 exit 1 fi install -D -m 0644 $MF ${TDIR}/${MF} done if [ $DO_DEPMOD -eq 1 ]; then # Will run depmod only for squashfs images. echo "Generating module dependencies in image ..." depmod -a -b $TDIR $KERN_VER fi echo "Packing image..." if [ "$IMG_TYPE" == "squashfs" ]; then mksquashfs $TDIR $IMG_NAME -noappend elif [ "$IMG_TYPE" == "cpio" ]; then CUR_DIR=$PWD; pushd $TDIR; find . -print0 | cpio --null -o --format=newc | gzip -9 > $CUR_DIR/$IMG_NAME popd fi rm -rf $TDIR echo $IMG_TYPE image created: $IMG_NAME <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-xorg APT-INIT APT-INSTALL freerdp freerdp-plugins-standard xfreerdp APT-INSTALL yad APT-INSTALL fonts-ttf-liberation fonts-bitmap-terminus menu-icons-default APT-CLEAN ADD rdp.shell /usr/local/bin/ RUN "cat > /etc/rc.d/rc.local <<EOT #! /bin/bash nohup su - -c 'xinit /usr/local/bin/rdp.shell' altlinux >/dev/null 2>/dev/null & EOT " RUN chmod +x /etc/rc.d/rc.local COMMIT altlinux-p8-clb-freerdp CLEAN <file_sep>#! /bin/bash ID=$1 MODE=${2:-diff} function usage() { cat << EOT Usage: $0 <docker-object> [<mode>] <docker-object> - image or container's name or ID. <mode> - diff (default) - export only this layer (object's "upper" dir), merged - export united this layer with all parents (object's "merged" dir) chain - export this layer and all its parents layers in diff mode. EOT } function err_exit() { [ -n "$1" ] && echo -e "$1\n" usage exit 1 } function obj_info() { local ID=$1 echo Looking docker objects for \"$ID\"... if OBJ=$(docker inspect $ID --type image --format='{{.Id}}' 2>/dev/null) ; then NAME=$(docker inspect $ID --format='{{index .RepoTags 0}}' |sed -e 's|/|_|g') TYPE=image elif OBJ=$(docker inspect $ID --type container --format='{{.Id}}' 2>/dev/null) ; then NAME=$(docker inspect $ID --format='{{.Name}}' |sed -e 's|^/||' -e 's|/|_|g') TYPE=container fi [ -z "$OBJ" ] && err_exit "Found nothing" NAME=$(echo $NAME |sed -e 's/:latest$//') # Better to avoid to create such images [ "$NAME" == "<no value>" ] && NAME="no_value" echo "Selected object: $OBJ" echo "Type: ${TYPE}; Name: ${NAME}" echo "Selected mode: $MODE" } [ `whoami` == 'root' ] || { echo 'Wonna be a root' exit 1 } [ -z "$ID" ] && err_exit "Please specify a docker object" echo $MODE |grep -Eq "^(diff|merged|chain)$" || err_exit "Wrong mode $MODE" obj_info $ID ID=$(echo $ID | sed -e 's|/|_|g') case $MODE in diff) # Get object's UpperDir UDIR=`docker inspect --format='{{.GraphDriver.Data.UpperDir}}' $OBJ` [ -d "$UDIR" ] || err_exit "Can't locate UpperDir for object $OBJ" # And export it into squashfs image mksquashfs $UDIR $ID.squashfs -noappend -comp xz echo "SquashFS diff layer for object $OBJ created: $ID.squashfs" ;; merged) # Get object's UpperDir UDIR=`docker inspect --format='{{.GraphDriver.Data.UpperDir}}' $OBJ` [ -d "$UDIR" ] || err_exit "Can't locate upper dir for object $OBJ" # Get object's LowerDir chain LDIR=`docker inspect --format='{{.GraphDriver.Data.LowerDir}}' $OBJ |sed -e 's|.*-init/diff:||'` if [ -z "$LDIR" -o "$LDIR" == "<no value>" ]; then echo "Warning, 'merged' mode selected, but there are no LowerDir for object $OBJ" echo "Only UpperDir will be processed" mksquashfs $UDIR $ID.squashfs -noappend -comp xz echo "SquashFS diff layer for object $OBJ created: $ID.squashfs" exit else # Split LowerDir into parts and check that every dir from this chain is exist echo $LDIR |tr ":" "\n" |while read LDIR_PART; do [ -d "$LDIR_PART" ] || err_exit "Can't locate LowerDir part $LDIR_PART for object $OBJ" done fi # Complete merged chain for mount: UpperDir and all LowerDir chain MOUNTCHAIN="${UDIR}:${LDIR}" TDIR=`mktemp -d` # Mount merged chain to temporary dir mount -t overlay overlay -o lowerdir=$MOUNTCHAIN $TDIR || { echo "Error mounting overlays $MOUNTCHAIN for object $OBJ" >&2 rmdir $TDIR exit 1 } # And export it into squashfs image mksquashfs $TDIR ${ID}-merged.squashfs -noappend -comp xz echo "SquashFS all merged layers for object $OBJ created: $ID.squashfs" umount $TDIR rmdir $TDIR ;; chain) # Look for a parent object, if exists PARENT_OBJ=`docker inspect --format='{{.Parent}}' $OBJ` [ -n "$PARENT_OBJ" ] || err_exit "No parent object found for $OBJ" ALL_OBJECTS=$ID MNF_NAME="${ID}.manifest" # Make image for current object in a DIFF mode $0 $ID diff # While we have a parent object... while [ -n "$PARENT_OBJ" ]; do # Get name for parent's object obj_info $PARENT_OBJ [ -n "$NAME" ] || err_exit "Can't get name for docker object $PARENT_OBJ" # Collect all parents names into this variable ALL_OBJECTS="$NAME $ALL_OBJECTS" # Make image for current parent object in a DIFF mode $0 $NAME diff # Get next parent object PARENT_OBJ=`docker inspect --format='{{.Parent}}' $PARENT_OBJ` done # Write a manifest template for initial object and all it's parents [ -f "$MNF_NAME" ] && rm -f $MNF_NAME for L_OBJ in $ALL_OBJECTS; do echo "LAYER=${L_OBJ}.squashfs" >> $MNF_NAME done echo "Manifest $MNF_NAME created" ;; esac <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-lightdm APT-INIT APT-INSTALL openbox pcmanfm2 eject APT-INSTALL lxde-common lxde-lxpanel lxde-lxsession lxde-lxsession-edit lxde-lxrandr lxde-lxtask APT-INSTALL lxde-lxappearance lxde-lxappearance-obconf lxde-lxshortcut lxde-lxinput lxde-lxhotkey APT-INSTALL lxde-settings-upstream lxde-icon-theme tango-icon-theme lxde-lxlauncher lxde-lxterminal APT-CLEAN COMMIT altlinux-p8-clb-lxde CLEAN <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-lightdm APT-INIT APT-INSTALL fluxbox sakura APT-CLEAN COMMIT altlinux-p8-clb-fluxbox CLEAN <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-base APT-INIT APT-INSTALL squashfs-tools firmware-linux APT-INSTALL kernel-image-un-def kernel-modules-bcmwl-un-def kernel-modules-drm-nouveau-un-def APT-INSTALL kernel-modules-ide-un-def kernel-modules-r8168-un-def kernel-modules-v4l-un-def APT-INSTALL kernel-modules-drm-un-def kernel-modules-drm-ancient-un-def kernel-modules-drm-radeon-un-def APT-INSTALL kernel-modules-kvm-un-def kernel-modules-rtl8723de-un-def kernel-modules-virtualbox-addition-un-def APT-CLEAN <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-base APT-INIT APT-INSTALL NetworkManager-daemon dhcp-client tcpdump iptables elinks curl netcat rsync APT-REMOVE bash-completion APT-CLEAN RUN sed -i -e \'s/nullok //\' /etc/pam.d/system-auth-use_first_pass RUN systemctl enable NetworkManager COMMIT altlinux-p8-clb-network CLEAN <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-network APT-INIT APT-INSTALL xorg-server xinit xinitrc xauth xterm xorg-utils APT-INSTALL xorg-dri-intel xorg-dri-nouveau xorg-dri-radeon xorg-dri-virgl APT-INSTALL xorg-drv-intel xorg-drv-libinput xorg-drv-nouveau xorg-drv-nv xorg-drv-qxl APT-INSTALL xorg-drv-radeon xorg-drv-vmware xorg-drv-vmmouse xorg-drv-synaptics APT-CLEAN RUN systemctl set-default multi-user RUN "cat > /etc/rc.d/rc.local <<EOT #! /bin/bash nohup su - -c 'xinit' altlinux >/dev/null 2>/dev/null & EOT " RUN chmod +x /etc/rc.d/rc.local COMMIT altlinux-p8-clb-xorg CLEAN <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-xorg APT-INIT APT-INSTALL firefox-esr APT-INSTALL livecd-webkiosk-firefox APT-INSTALL fonts-ttf-liberation fonts-bitmap-terminus menu-icons-default APT-INSTALL unclutter APT-CLEAN RUN "cat > /etc/rc.d/rc.local <<EOT #! /bin/bash nohup su - -c 'xinit /usr/local/bin/ff-kiosk.shell' altlinux >/dev/null 2>/dev/null & EOT " RUN chmod +x /etc/rc.d/rc.local RUN 'cat > /usr/local/bin/ff-kiosk.shell <<EOT #! /bin/bash if grep -q "url=" /proc/cmdline; then HOME_URL=\$(sed -e "s/.* url=//" -e "s/ .*//" /proc/cmdline) fi HOME_URL=\${HOME_URL:-http://habrahabr.ru} ratpoison & unclutter & /usr/bin/xset s off -dpms firefox "\$HOME_URL" EOT ' RUN chmod +x /usr/local/bin/ff-kiosk.shell HDIR=/home/altlinux RUN mkdir -p ${HDIR}/.mozilla/firefox/kiosk RUN mkdir -p \"${HDIR}/.mozilla/firefox/Crash Reports\" RUN "cat > ${HDIR}/.mozilla/firefox/profiles.ini <<EOT [General] StartWithLastProfile=1 [Profile0] Name=kiosk IsRelative=1 Path=kiosk EOT " RUN "cat > ${HDIR}/.mozilla/firefox/kiosk/prefs.js <<EOT user_pref(\"browser.shell.checkDefaultBrowser\", false); EOT " RUN "cat >${HDIR}/.mozilla/firefox/Crash\ Reports/crashreporter.ini <<EOT [Crash Reporter] SubmitReport=0 EOT " RUN cp /etc/skel/.ratpoisonrc /home/altlinux/ RUN chown -R altlinux: /home/altlinux RUN rm -rf /etc/net/ifaces/eth0 COMMIT altlinux-p8-clb-ff-kiosk CLEAN <file_sep>#!/bin/sh COMMON_RDP_OPTS='/f /cert-ignore' function err_msg() { yad --image dialog-error --borders=15 --width=500 --undecorated --center \ --text "<span color='red' size='x-large'>\tError:\n</span>\t$1" --button=gtk-ok:0 } while true; do frmdata=$(yad --image remote_access_section --width=450 --borders=15 --undecorated \ --center --text "<span size='xx-large'> Connect to remote desktop:\n</span>" \ --form --field='Server' "$frm_host" --field='Username' "$frm_user" \ --field='Password:H' "$frm_passw" --field='Domain' "$frm_domain" --field='Gateway' "$frm_gw") frm_host=$(echo $frmdata | cut -f1 -d'|') frm_user=$(echo $frmdata | cut -f2 -d'|') frm_passw=$(echo $frmdata | cut -f3 -d'|') frm_domain=$(echo $frmdata | cut -f4 -d'|') frm_gw=$(echo $frmdata | cut -f5 -d'|') if [ -z "$frm_host" ]; then err_msg "Server must be specified" continue fi RDP_OPTS=$COMMON_RDP_OPTS [ -n "$frm_host" ] && RDP_OPTS="$RDP_OPTS /v:$frm_host" [ -n "$frm_user" ] && RDP_OPTS="$RDP_OPTS /u:$frm_user" [ -n "$frm_passw" ] && RDP_OPTS="$RDP_OPTS /p:$frm_passw" [ -n "$frm_domain" ] && RDP_OPTS="$RDP_OPTS /d:$frm_domain" [ -n "$frm_gw" ] && RDP_OPTS="$RDP_OPTS /g:$frm_gw" RDP_OUTP=$(xfreerdp $RDP_OPTS 2>&1) ret=$? [ $ret -eq 12 ] && ret=0 if [ $ret -gt 0 ]; then IFS= RDP_OUTP=$(echo $RDP_OUTP|sed -e 's/.* - //g') IFS=$' \t\n' MSG="Error connecting to the server '$frm_host'" [ -n "$RDP_OUTP" ] && MSG="${MSG}\n\n<span size='x-small'>freerdp output:\n$RDP_OUTP</span>" err_msg "$MSG" fi done <file_sep>#! /bin/bash . docker-functions FROM altlinux-p8-clb-xorg APT-INIT APT-INSTALL lightdm-gtk-greeter APT-INSTALL fonts-ttf-liberation fonts-bitmap-terminus APT-INSTALL pam-ck-connector2 pm-utils polkit APT-CLEAN RUN systemctl set-default graphical RUN 'sed -i -e "s/^#\(autologin-user=\).*$/\1altlinux/" -e "s/^#\(autologin-user-timeout=0\)/\1/" /etc/lightdm/lightdm.conf' RUN '[ -f /etc/rc.d/rc.local ] && rm -f /etc/rc.d/rc.local' COMMIT altlinux-p8-clb-lightdm CLEAN
a8f2fea850fe04b6c842a837e2778b137187f3e2
[ "Shell" ]
13
Shell
Prividen/colaboot-utils
d143365715a51167727e0b69c93a5e485128d9a0
2e02945896bcf58242ad50ace683aa4f725c4b03
refs/heads/master
<repo_name>ahrjarrett/local-state-mngmt-with-apollo<file_sep>/src/App.js import React from "react"; import { useQuery, gql } from "@apollo/client"; import mutation from "./mutation"; import logo from "./logo.svg"; import "./App.css"; export const QUERY = gql` query getDarkMode { isDarkMode @client } `; function App() { const { data } = useQuery(QUERY); let classNames = "App"; if (data?.isDarkMode) { classNames += " dark"; } return ( <div className={classNames}> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <input type="checkbox" id="switch" onChange={mutation} /> <label for="switch">Dark Mode toggle</label> </header> </div> ); } export default App; <file_sep>/src/index.js import React from "react"; import { render } from "react-dom"; import App from "./App"; import { ApolloClient, ApolloProvider } from "@apollo/client"; import { cache } from "./cache"; export const client = new ApolloClient({ cache, connectToDevTools: true, }); render( <ApolloProvider client={client}> <App /> </ApolloProvider>, document.getElementById("root") ); <file_sep>/src/cache.js import { InMemoryCache } from "@apollo/client"; import { isDarkModeVar } from "./localStorage"; export const cache = new InMemoryCache({ typePolicies: { Query: { fields: { isDarkMode: { read() { return isDarkModeVar(); }, }, }, }, }, });
7f713cbde865babe5a882e30b619a00a73b24d69
[ "JavaScript" ]
3
JavaScript
ahrjarrett/local-state-mngmt-with-apollo
0e48ac99be347316282f78655facbdaa7dfa0163
9c848a73a4e4a34eac042f1fd6cbd0337c83332e
refs/heads/master
<repo_name>andrewmo2014/RayTracing<file_sep>/Noise.cpp #include "Noise.h" #include "PerlinNoise.h" #include <iostream> #include <cmath> Vector3f Noise::getColor(const Vector3f & pos) { //Fill in this function ONLY. //INTERPOLATE BETWEEN TWO COLORS BY WEIGHTED AVERAGE //return Vector3f(1,1,1); float M; if (type){ M = sin(frequency*pos[0] + amplitude*PerlinNoise::octaveNoise(pos, octaves)); } else{ ///Grain; float G = 20*(PerlinNoise::octaveNoise(Vector3f(pos[0], pos[1], pos[2]), octaves)); M = 1.0f*(G - (int)G); } M = (M+1.0f)/2.0f; return M*color[0] + (1-M)*color[1]; } Noise::Noise(int _octaves,const Vector3f & color1, const Vector3f &color2,float freq,float amp, float typ): octaves(_octaves),frequency(freq),amplitude(amp), type(typ){ color[0] = color1; color[1] = color2; init = true; } Noise::Noise(const Noise & n): octaves(n.octaves),frequency(n.frequency), amplitude(n.amplitude),type(n.type),init(n.init) { color[0] = n.color[0]; color[1] = n.color[1]; } bool Noise::valid() { return init; } Noise::Noise(): octaves(0),init(false) {} <file_sep>/README.txt README.txt ========================================================================================== Author: <NAME> | Date: 12/05/2012 | 6.837 Computer Graphics | Assignment 5 | ================================= __________________________________________________________________________________________ Compiling Instructions ========================================================================================== When I completed the assignment, I managed to run Linux through my Macbook Pro laptop with a Virtual Machine called VirtualBox. I also tested on the campus Athena computer to make sure that it worked correctly. Here are instructions 1. Unzip submission on Stellar and extract all files to designated directory 2. In terminal, cd to directory containing "assn4" folder 3. command make 4. if images not already in folder: command sh test_cases.sh This should reproduce the images generated from this assignment ranging from names a_1-13 a_1-a_8 : Comparing my images to solution a_9-a_10 : Comparing bunny zero bounce to solution a_11-a_13 : Showing new spotted noise on vase 5. "assn5" folder contains all necessary files including updated files, classes, subclasses, etc. 6. Note, in this assignment, I made it so you have to call -jitter -filter together or none at all (I did not implement them separately) __________________________________________________________________________________________ Collaboration ========================================================================================== I had no further assitance other than the help I received from Professor/TAs at office hours. __________________________________________________________________________________________ References ========================================================================================== ⁃ 6.837 Lecture Notes (Very Helpful) - http://www.cplusplus.com/reference/ - http://www.d.umn.edu/~ddunham/cs5721f07/schedule/resources/lab_opengl07.html __________________________________________________________________________________________ Problems ========================================================================================== Currently, my code is functioning properly. It took some time debugging, but should be a good solution. My main problem was normalizing the normals. Also, I think I accounted for an extra bounc that was hard to figure out. Luckily the updated executable allowed me to separate between refraction and reflection. Now, All my solution images have a correct image except for the bunny in scene 6. I think my shadow/reflection may be off by a bit (due to not-normalizing properly?) and is a very minor discrepancy. __________________________________________________________________________________________ Extra Credit ========================================================================================== Here are some added features to the assignment: • ***In Addition to Extra Credit from before*** (refer to previous assignment 4 for pics/documentation) • New Noise (Spotted) Attempted to make wood texture but created this nice looking pstted texture. Applied it to different colors. This required adding a new parameter to noise and type variable (is marble or is spotted) • Attempted to put in Stadford Dragon to the scene Did not work. tried to copy obj file from "http://www.d.umn.edu/~ddunham/cs5721f07/schedule/resources/models/dragon.obj", but indices too large. Did not follow through trying to figure it out. However, I will still try to do it. __________________________________________________________________________________________ Comments ========================================================================================== I felt very guided on this assignment by the lecture notes. By following the slides and implementing the correst formulas and constraints, I saw progress fast. The only thing that threw me off was normalizing normals. I am still confused when I should/should not normalize vectors (for both normals and directions). This resulted in very small discepancies in lighting/shadows on my pictures. After realizing that I didn't normalize (or normalized when I shouldn't have), I was able to fix my mistakes. Also, I managed to find out that I was accounting for an extra bounce when I shouldn't off. Ironiccaly my refraction algorithm worked first and I had to debug reflection/shadows. Luckily the new executable allowed me to see between the two while debugging. They may be some discrepany due to jitter/blurring/ray slightly off, however, the overall product looks correct. If I didn't spend so much time debugging, I would have nejoyed working on Extra Credit. To be honest, I thought thislast assignment would be very intense, however, it was just an extension from our previous assignemnt 4. I had a lot of fun in the course and learned a lot. I am glad I took it and appreciate all the help/guidance 6.837 had provided me. Thanks <file_sep>/RayTracer.cpp #include "RayTracer.h" #include "Camera.h" #include "Ray.h" #include "Hit.h" #include "Group.h" #include "Material.h" #include "Light.h" #include <cmath> #include <iostream> #define EPSILON 0.001 //IMPLEMENT THESE FUNCTIONS //These function definitions are mere suggestions. Change them as you like. Vector3f mirrorDirection( const Vector3f& normal, const Vector3f& incoming) { return (normal*(2*(Vector3f::dot(normal, incoming))) - incoming).normalized(); } bool transmittedDirection( const Vector3f& normal, const Vector3f& incoming, float index_n, float index_nt, Vector3f& transmitted) { float n_r = index_n / index_nt; float NDotD = Vector3f::dot(normal,incoming); float radical = (1.0f - n_r*n_r*(1.0f-NDotD*NDotD)); if (radical < 0){ return false; } transmitted = normal*(n_r*NDotD-sqrt(radical)) - (incoming*n_r); transmitted.normalized(); return true; } RayTracer::RayTracer( SceneParser * scene, int max_bounces, bool my_shadows //more arguments if you need... ) : m_scene(scene) { g=scene->getGroup(); m_maxBounces = max_bounces; m_shadows = my_shadows; } RayTracer::~RayTracer() { } Vector3f RayTracer::traceRay( Ray& ray, float tmin, int bounces, float refr_index, Hit& hit ) const { if (g->intersect(ray, hit, tmin)){ Vector3f pixCol = Vector3f(0.0f, 0.0f, 0.0f); //Ambient color pixCol = pixCol + hit.getMaterial()->getDiffuseColor()*m_scene->getAmbientLight(); //Diffuse color + SHADOWS for (int indL = 0; indL < m_scene->getNumLights(); indL++){ Light* lit = m_scene->getLight(indL); Vector3f litDir; Vector3f litCol; float distToLit; lit->getIllumination(ray.pointAtParameter(hit.getT()), litDir, litCol, distToLit); //cast shadows if (m_shadows){ Ray shadowRay = Ray(ray.pointAtParameter(hit.getT()), litDir); Hit shadowHit = Hit(distToLit, NULL, NULL); if (!g->intersect(shadowRay, shadowHit, EPSILON)){ Vector3f shadingCol = hit.getMaterial()->Shade(ray, hit, litDir, litCol); pixCol = pixCol + shadingCol; } } else{ Vector3f shadingCol = hit.getMaterial()->Shade(ray, hit, litDir, litCol); pixCol = pixCol + shadingCol; } } if (bounces>m_maxBounces-1){ return pixCol; } //Reflectance Vector3f mirrDir = mirrorDirection( hit.getNormal().normalized(), -1.0f*ray.getDirection()); Ray mirrRay = Ray(ray.pointAtParameter(hit.getT()), mirrDir); Hit mirrHit = Hit(FLT_MAX, NULL, Vector3f(0.0f, 0.0f, 0.0f)); Vector3f mirrColor = hit.getMaterial()->getSpecularColor()*traceRay( mirrRay, EPSILON, bounces+1, refr_index, mirrHit ); //pixCol = pixCol + mirrColor; //Refraction float new_refr_index; Vector3f normal = hit.getNormal().normalized(); if (Vector3f::dot(ray.getDirection(), normal) > 0){ new_refr_index = 1.0f; normal = normal*-1.0f; } else{ new_refr_index = hit.getMaterial()->getRefractionIndex(); } //check if not total reflection Vector3f transmitted; if (transmittedDirection( normal, -1.0f*ray.getDirection(), refr_index, new_refr_index, transmitted)){ Ray transRay = Ray(ray.pointAtParameter(hit.getT()), transmitted); Hit transHit = Hit(); Vector3f transColor = hit.getMaterial()->getSpecularColor()*traceRay( transRay, EPSILON, bounces+1, new_refr_index, transHit ); float R_0 = pow((new_refr_index - refr_index)/(new_refr_index + refr_index), 2); //std::cout << R_0 << std::endl; float c; if (refr_index <= new_refr_index){ c = abs(Vector3f::dot(-1.0f*ray.getDirection(), normal)); } else{ c = abs(Vector3f::dot(transmitted, normal)); } float R = R_0 + (1-R_0)*pow(1-c, 5); //std::cout << c << std::endl; //R = 0; pixCol = pixCol + (1-R)*transColor + (R)*mirrColor; } //total relfection instead else{ pixCol = pixCol + mirrColor; } return pixCol; } else{ return m_scene->getBackgroundColor(ray.getDirection()); } } <file_sep>/test_cases.sh #!/bin/sh ./a5 -input scene06_bunny_1k.txt -size 300 300 -output a_2.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene10_sphere.txt -size 300 300 -output a_4.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene11_cube.txt -size 300 300 -output a_6.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene12_vase.txt -size 300 300 -output a_8.tga -shadows -bounces 4 -jitter -filter ./a5soln -input scene06_bunny_1k.txt -size 300 300 -output a_1.tga -shadows -bounces 4 -bounces 4 -jitter -filter ./a5soln -input scene10_sphere.txt -size 300 300 -output a_3.tga -shadows -bounces 4 -jitter -filter ./a5soln -input scene11_cube.txt -size 300 300 -output a_5.tga -shadows -bounces 4 -jitter -filter ./a5soln -input scene12_vase.txt -size 300 300 -output a_7.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene06_bunny_1k.txt -size 300 300 -output a_10.tga -shadows -bounces 0 -jitter -filter ./a5soln -input scene06_bunny_1k.txt -size 300 300 -output a_9.tga -shadows -bounces 0 -jitter -filter ./a5 -input scene12_vase_spotted.txt -size 300 300 -output a_11.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene12_vase_planet.txt -size 300 300 -output a_12.tga -shadows -bounces 4 -jitter -filter ./a5 -input scene12_vase_cow.txt -size 300 300 -output a_13.tga -shadows -bounces 4 -jitter -filter
07957b00824c8e8626955b9151bf47860a98394d
[ "Text", "C++", "Shell" ]
4
C++
andrewmo2014/RayTracing
87d8f9209955708e041e941b19cfff58bb4b1430
dd64a3600581db631215975e094943dbb4cf52cd
refs/heads/master
<repo_name>khcqcn/cmusphinx<file_sep>/sphinx_fsttools/sphinx_lm_fst.cc /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2008 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file sphinx_lm_fst.cc * * Build finite-state transducers from Sphinx language models. */ #include <fst/fstlib.h> namespace sb { #include <ngram_model.h> #include <ckd_alloc.h> #include <hash_table.h> #include <assert.h> #include <stdarg.h> #include <err.h> }; #include "fstprinter.h" using namespace fst; using namespace sb; using sb::int32; /* Override conflicting typedefs */ typedef VectorFst<LogArc> LogVectorFst; typedef StdArc::StateId StateId; typedef StdArc::Label Label; static const arg_t args[] = { { "-lm", REQARG_STRING, NULL, "Language model input file" }, { "-binfst", ARG_STRING, NULL, "Binary FST output file" }, { "-txtfst", ARG_STRING, NULL, "Text FST output file" }, { "-exact", ARG_BOOLEAN, "no", "Use exact representation (Allauzen, 2003) (FIXME: Not yet implemented)" }, { "-sym", ARG_STRING, NULL, "Use this symbol table file for word IDs" }, { "-symout", ARG_STRING, NULL, "Write symbol table file for word IDs to this file" }, { "-ssymout", ARG_STRING, NULL, "Write symbol table file for states to this file" }, { "-maxn", ARG_INT32, "0", "Limit model to N-grams of this order (0 to use all)" }, { "-verbose", ARG_BOOLEAN, "no", "Print verbose debug info" }, { NULL, 0, NULL, NULL } }; static int verbose = 0; static void dprintf(char const *format, ...) { va_list args; va_start(args, format); if (verbose) vprintf(format, args); va_end(args); } static void add_mgram_states(StdVectorFst *model, int m, ngram_model_t *lm, logmath_t *lmath, hash_table_t *sidtab) { ngram_iter_t *itor = ngram_model_mgrams(lm, m); /* Add states for each M-gram at this order M. */ for (; itor; itor = ngram_iter_next(itor)) { /* Retrieve M-gram information. */ int32 prob, bowt; int32 const *wids = ngram_iter_get(itor, &prob, &bowt); /* If the final word is not in the symbol table then skip it. */ Label wid = model->InputSymbols()->Find(ngram_word(lm, wids[m])); if (wid == -1) { dprintf("Skipping unknown word %s\n", ngram_word(lm, wids[m])); continue; } /* Any M-gram starting with </s> is meaningless, so skip it. */ /* Except if M == 1! */ if (m != 0 && 0 == strcmp(ngram_word(lm, wids[0]), "</s>")) continue; /* Find the source state for this arc. */ StateId src; if (m == 0) { /* Use the epsilon state as the source. */ src = 0; } else if (hash_table_lookup_bkey_int32(sidtab, (char const *)wids, m * sizeof(*wids), &src) != 0) { /* We currently expect w(1,N-1) to exist, and in fact it * always should, by the definition of a backoff model, * unless one of the words is not in the symbol table (in * which case we want to skip this M-gram anyway). */ continue; } StateId dest; bool final, newstate; /* Only one final state is necessary, so don't create any new ones. */ if (0 == strcmp(ngram_word(lm, wids[m]), "</s>")) { final = true; newstate = false; /* Look for an existing unigram </s> state. */ if (hash_table_lookup_bkey_int32(sidtab, (char const *)(wids + m), sizeof(*wids), &dest) != 0) { dest = model->AddState(); dprintf("Final state %d\n", dest); model->SetFinal(dest, 0); newstate = true; } } else { final = false; newstate = true; dest = model->AddState(); } /* <s> is a non-event (FIXME: should be configurable) */ if (0 == strcmp(ngram_word(lm, wids[m]), "<s>")) { /* Also its target should be the initial state. */ if (m == 0) { dprintf("Initial state %d\n", dest); model->SetStart(dest); } } else { model->AddArc(src, StdArc(wid, wid, -logmath_log_to_ln(lmath, prob), dest)); dprintf("Adding %d-gram arc %d => %d %s/%.4f\n", m+1, src, dest, ngram_word(lm, wids[m]), logmath_log_to_log10(lmath, prob)); } /* Track state IDs. */ if (newstate) { /* Ugh, we have to copy the keys... */ int32 *newwids; int len; if (final) { newwids = (int32 *)ckd_malloc(sizeof(*wids)); newwids[0] = wids[m]; len = 1; } else { len = m+1; newwids = (int32 *)ckd_malloc(len * sizeof(*wids)); memcpy(newwids, wids, len * sizeof(*wids)); } hash_table_enter_bkey_int32(sidtab, (char *)newwids, len * sizeof(*newwids), dest); dprintf("Entered state ID mapping %d <=", dest); for (int j = 0; j < len; ++j) { dprintf(" %s", ngram_word(lm, wids[j])); } dprintf("\n"); } /* Create a backoff arc to the suffix M-1-gram, if it exists. */ if (bowt && !final) { int32 bo = 0; /* epsilon state */ if (m > 0 && hash_table_lookup_bkey_int32(sidtab, (char const *)(wids + 1), m * sizeof(*wids), &bo) != 0) { continue; } /* Add a backoff arc back to the M-1-gram state. */ model->AddArc(dest, StdArc(0, 0, -logmath_log_to_ln(lmath, bowt), bo)); dprintf("Adding backoff arc %d => %d %.4f\n", dest, bo, logmath_log_to_log10(lmath, bowt)); } } } static void add_ngram_arcs(StdVectorFst *model, int n, hash_table_t *sidtab, ngram_model_t *lm, logmath_t *lmath) { ngram_iter_t *itor = ngram_model_mgrams(lm, n-1); /* Add arcs for all N-grams to N-1-gram states. */ for (; itor; itor = ngram_iter_next(itor)) { /* Retrieve N-gram information. */ int32 prob, bowt; int32 const *wids = ngram_iter_get(itor, &prob, &bowt); /* Get word symbol ID for arc. */ Label wid = model->InputSymbols()->Find(ngram_word(lm, wids[n-1])); if (wid == -1) continue; /* <s> is a non-event (FIXME: should be configurable) */ if (0 == strcmp(ngram_word(lm, wids[n-1]), "<s>")) continue; /* Find source and destination states. Source is w(1,N-1) and * destination is w(2,N). */ int32 src, dest; if (hash_table_lookup_bkey_int32(sidtab, (char const *)wids, (n-1) * sizeof(*wids), &src) != 0) { /* We currently expect w(1,N-1) to exist, and in fact it * always should, by the definition of a backoff model, * unless one of the words is not in the symbol table. */ int j; for (j = 0; j < n; ++j) { if (model->InputSymbols()->Find(ngram_word(lm, wids[j])) == -1) break; } if (j == n) { dprintf("Failed to find prefix %d-gram for", n-1); for (int j = 0; j < n; ++j) { dprintf(" %s", ngram_word(lm, wids[j])); } dprintf("\n"); } continue; } /* It's entirely possible that w(2,N), however, might not * exist, particularly in a pruned language model. In this * case we will back off to shorter final N-grams without * applying any backoff weight (this is consistent with what * the ARPA file header says) */ int32 endn = n - 1; while (endn > 0 && hash_table_lookup_bkey_int32(sidtab, (char const *)(wids + n - endn), endn * sizeof(*wids), &dest) != 0) { dprintf("Failed to find state ID for final %d-gram", endn); for (int j = n - endn; j < n; ++j) { dprintf(" %s", ngram_word(lm, wids[j])); } dprintf("\n"); --endn; } if (endn == 0) { /* FIXME: This is probably a serious error. */ dprintf("Failed to find any suffix N-grams for"); for (int j = 0; j < n; ++j) { dprintf(" %s", ngram_word(lm, wids[j])); } dprintf("\n"); continue; } /* Add the arc. */ model->AddArc(src, StdArc(wid, wid, -logmath_log_to_ln(lmath, prob), dest)); dprintf("Adding %d-gram arc %d => %d %s/%.4f\n", n, src, dest, ngram_word(lm, wids[n-1]), logmath_log_to_log10(lmath, prob)); } } int main(int argc, char *argv[]) { cmd_ln_t *config; ngram_model_t *lm; logmath_t *lmath; int32 const *counts; int32 n, nn; if ((config = cmd_ln_parse_r(NULL, args, argc, argv, TRUE)) == NULL) { return 1; } lmath = logmath_init(1.0001, 0, 0); lm = ngram_model_read(NULL, cmd_ln_str_r(config, "-lm"), NGRAM_AUTO, lmath); n = ngram_model_get_size(lm); if ((nn = cmd_ln_int32_r(config, "-maxn")) != 0) n = nn; counts = ngram_model_get_counts(lm); verbose = cmd_ln_boolean_r(config, "-verbose"); /* FIXME: Should this be in the Log semiring instead? */ StdVectorFst model; /* If there is a symbol table file, use it. Otherwise, construct * it from the unigram strings. */ SymbolTable *sym; char const *filename; if ((filename = cmd_ln_str_r(config, "-sym")) != NULL) { sym = SymbolTable::ReadText(filename); dprintf("Read symbols from %s, next index %lld\n", filename, sym->AvailableKey()); } else { sym = new SymbolTable("words"); sym->AddSymbol("&epsilon;", 0); for (int32 i = 0; i < counts[0]; ++i) { sym->AddSymbol(ngram_word(lm, i)); } dprintf("Constructed symbols from LM, next index %lld\n", sym->AvailableKey()); } model.SetInputSymbols(sym); model.SetOutputSymbols(sym); /* The algorithm goes like this: * * Create an epsilon state * For M in 1 to N-1: * For each M-gram w(1,M): * Create a state q(1,M) * Create an arc from state q(1,M-1) to q(1,M) with weight P(w(1,M)) * Create an arc from state q(1,M) to q(2,M) with weight bowt(w(1,M-1)) * For each N-gram w(1,N): * Create an arc from state q(1,N-1) to q(2,N) with weight P(w(1,N)) */ StateId eps = model.AddState(); assert(eps == 0); /* Hash all M-grams to State IDs. */ int nngrams = 0; for (int i = 0; i < n; ++i) nngrams += counts[i]; dprintf("Allocating hash table for %d N-grams\n", nngrams); hash_table_t *sidtab = hash_table_new(nngrams, HASH_CASE_YES); /* Do M-grams from 1 to N-1, tracking state IDs. */ for (int m = 0; m < n-1; ++m) { add_mgram_states(&model, m, lm, lmath, sidtab); } /* Now do N-grams. */ add_ngram_arcs(&model, n, sidtab, lm, lmath); /* Find backoff paths which overestimate probabilities and remove * them by creating explicit backoff states (Allauzen, 2003) */ /* And now ... elaborately free the N-gram hash table, writing a * state symbol table in the process. */ char const *ssym = cmd_ln_str_r(config, "-ssymout"); FILE *ssymfh = NULL; if (ssym) ssymfh = fopen(ssym, "w"); if (ssymfh) fprintf(ssymfh, "&epsilon;\t%d\n", eps); for (hash_iter_t *itor = hash_table_iter(sidtab); itor; itor = hash_table_iter_next(itor)) { if (ssymfh) { int32 *wids = (int32 *)hash_entry_key(itor->ent); fprintf(ssymfh, "%s", ngram_word(lm, wids[0])); for (int j = 1; j < (int)(hash_entry_len(itor->ent) / 4); ++j) { fprintf(ssymfh, "_%s", ngram_word(lm, wids[j])); } fprintf(ssymfh, "\t%d\n", (int32)(long)hash_entry_val(itor->ent)); } ckd_free((void *)itor->ent->key); } hash_table_free(sidtab); /* The model should already be deterministic (aside from * containing epsilon arcs). We should connect it though to * remove impossible word sequences. However, this means the * state symbol table would be meaningless. So don't do that. */ /* Also sort it so it can be composed with a dictionary. */ ArcSort(&model, ILabelCompare<StdArc>()); /* Write the model in the requested format. */ char const *outfile; if ((outfile = cmd_ln_str_r(config, "-binfst")) != NULL) { model.Write(outfile); } if ((outfile = cmd_ln_str_r(config, "-txtfst")) != NULL) { FstPrinter<StdArc> printer(model, model.InputSymbols(), model.OutputSymbols(), NULL, true); ostream *ostrm = new ofstream(outfile); printer.Print(ostrm, outfile); } if ((outfile = cmd_ln_str_r(config, "-symout")) != NULL) { model.InputSymbols()->WriteText(outfile); } ngram_model_free(lm); cmd_ln_free_r(config); return 0; } <file_sep>/jsgfparser/Makefile all: jsgfparser CPPFLAGS := -DYYDEBUG=1 CFLAGS := -g -Wall `pkg-config --cflags sphinxbase` LIBS := `pkg-config --libs sphinxbase` jsgfparser: jsgf.tab.o jsgf.lex.o jsgf_impl.o main.o gcc -o $@ jsgf.lex.o jsgf.tab.o jsgf_impl.o main.o $(LIBS) jsgf.lex.h jsgf.lex.c: jsgf.l jsgf.h flex -o $@ $< jsgf.tab.h jsgf.tab.c: jsgf.y jsgf.h bison -d $< -o $@ jsgf.tab.o: jsgf.tab.c jsgf.lex.h jsgf_impl.o: jsgf_impl.c jsgf.h main.o: main.c jsgf.h clean: $(RM) *.tab.* *.o *.lex.* jsgfparser <file_sep>/pocketsphinx/python/Makefile.am EXTRA_DIST = pocketsphinx.c \ pocketsphinx.pyx \ pocketsphinx.pxd pkginclude_HEADERS = pocketsphinx.pxd noinst_HEADERS = bogus_pygobject.h if BUILD_PYTHON all-local: pymod-build-stamp install-exec-local: pymod-build-stamp $(PYTHON) setup.py install --prefix $(DESTDIR)$(prefix) uninstall-local: $(PYTHON) setup.py bogus_uninstall --prefix $(DESTDIR)$(prefix) clean-local: $(PYTHON) setup.py clean --all # This is dumb, but distutils is completely incapable of VPATH building test -z "$(VPATH)" || $(RM) pocketsphinx.c $(RM) pymod-build-stamp pymod-build-stamp: $(srcdir)/pocketsphinx.c # This is dumb, but distutils is completely incapable of VPATH building test -z "$(VPATH)" || cp "$(srcdir)/pocketsphinx.c" pocketsphinx.c $(PYTHON) setup.py build touch $@ endif if BUILD_CYTHON $(srcdir)/pocketsphinx.c: $(srcdir)/pocketsphinx.pyx $(srcdir)/pocketsphinx.pxd cython -o $@ $< $(CPPFLAGS) -I$(sphinxbase)/python endif <file_sep>/SphinxTrain/src/programs/cdcn_train/read_backup_distributions.c /* ==================================================================== * Copyright (c) 1994-2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <stdio.h> #include <stdlib.h> #include "header.h" int read_backup_distribution(char *filen, float ***mean, float ***variance, float **pi, int *Nmodes, int Ndim) { int j, k, imodes, idim; float **varbuff, **meanbuff, *cbuff; FILE *dist; if ((dist = fopen(filen, "r")) == NULL) { printf("Unable to open distribution file\n"); return (0); } fscanf(dist, "%d %d", &imodes, &idim); *Nmodes = imodes; if (idim != Ndim) { printf("ERROR in read_distribution:\n"); printf ("Distribution dimensionality != Dimensionality of data given\n"); return (0); } varbuff = (float **) ckd_calloc_2d(imodes, idim, sizeof(float)); meanbuff = (float **) ckd_calloc_2d(imodes, idim, sizeof(float)); cbuff = (float *) ckd_calloc(imodes, sizeof(float)); for (k = 0; k < imodes; ++k) { fscanf(dist, "%f", &cbuff[k]); for (j = 0; j < idim; ++j) fscanf(dist, "%f ", &meanbuff[k][j]); for (j = 0; j < idim; ++j) fscanf(dist, "%f ", &varbuff[k][j]); } fclose(dist); *variance = varbuff; *mean = meanbuff; *pi = cbuff; return (1); } <file_sep>/archive_s3/s3.2/src/wid.c /* * wid.c -- Mapping word-IDs between LM and dictionary. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "wid.h" s3lmwid_t *wid_dict_lm_map (dict_t *dict, lm_t *lm) { int32 u, n; s3wid_t w; s3lmwid_t *map; assert (dict_size(dict) > 0); map = (s3lmwid_t *) ckd_calloc (dict_size(dict), sizeof(s3lmwid_t)); for (n = 0; n < dict_size(dict); n++) map[n] = BAD_S3LMWID; n = 0; for (u = 0; u < lm_n_ug(lm); u++) { w = dict_wordid (dict, lm_wordstr(lm, u)); lm_lmwid2dictwid(lm, u) = w; if (NOT_S3WID(w)) { n++; } else { if (dict_filler_word (dict, w)) E_ERROR("Filler dictionary word '%s' found in LM\n", lm_wordstr(lm, u)); if (w != dict_basewid (dict, w)) { E_ERROR("LM word '%s' is an alternative pronunciation in dictionary\n", lm_wordstr(lm, u)); w = dict_basewid (dict, w); lm_lmwid2dictwid(lm, u) = w; } for (; IS_S3WID(w); w = dict_nextalt(dict, w)) map[w] = (s3lmwid_t) u; } } if (n > 0) E_INFO("%d LM words not in dictionary; ignored\n", n); return map; } int32 wid_wordprob2alt (dict_t *dict, wordprob_t *wp, int32 n) { int32 i, j; s3wid_t w; for (i = 0, j = n; i < n; i++) { w = wp[i].wid; for (w = dict_nextalt (dict, w); IS_S3WID(w); w = dict_nextalt (dict, w)) { wp[j].wid = w; wp[j].prob = wp[i].prob; j++; } } return j; } <file_sep>/archive_s3/s3/src/libutil/cmd_ln.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * cmd_ln.h -- Command line argument parsing. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ /********************************************************************* * * $Header$ * * Carnegie Mellon ARPA Speech Group * * Copyright (c) 1994 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * file: cmd_ln.h * * traceability: * * description: * This module defines, parses and manages the validation * of command line arguments. * * author: * <NAME> (<EMAIL>) * *********************************************************************/ #ifndef _LIBUTIL_CMD_LN_H_ #define _LIBUTIL_CMD_LN_H_ #ifndef NULL #define NULL ((void *)0) #endif typedef int (*validation_fn_t)(char *switch_name, void *arg); #define CMD_LN_NO_VALIDATION ((validation_fn_t)NULL) #define CMD_LN_NO_DEFAULT ((char *)NULL) typedef enum { CMD_LN_UNDEF, CMD_LN_INT32, CMD_LN_FLOAT32, CMD_LN_FLOAT64, CMD_LN_STRING, CMD_LN_STRING_LIST, CMD_LN_BOOLEAN } arg_type_t; typedef struct { char *switch_name; /* name of the command line switch */ arg_type_t type; /* type of the argument */ validation_fn_t validate_arg; /* a function which validates argument values */ void *default_value; /* the default value of the argument, if any */ char *doc; /* a documentation string for the argument */ } arg_def_t; /* Initializes the command line parsing subsystem */ void cmd_ln_initialize(void); /* Defines the set of acceptable command line arguments * given the list of command line argument defintions * contained in the switch_definition_array. An element * of the array contains the following information: * * . switch name (e.g. "-dictionary") * * . type of the argument following the switch * * . an optional validation function for the * value given on the command line. * * . a translation function for the * value given on the command line. This * function is optional except for * enumerated types. * * This function allocates memory, if necessary, for * parsed command line arguments. */ int cmd_ln_define(arg_def_t *defn); /* * Reads the command line and converts the arguments, * if necessary, according to their definitions. */ int cmd_ln_parse(int argc, char *argv[]); /* * Calls the validation functions for each of the * command line arguments. */ int cmd_ln_validate(); /* Returns a pointer to the parsed command line argument. (The returned pointer must not be given to the function free()) It is const because the caller should not modify the thing referred to by this pointer. */ const void * cmd_ln_access(char *switch_name); /* Prints out the command line argument definitions to stderr */ void cmd_ln_print_definitions(void); void cmd_ln_print_configuration( void ); #endif /* CMD_LN_H */ /* * Log record. Maintained by CVS. * * $Log$ * Revision 1.3 2002/12/03 23:03:02 egouvea * Updated slow decoder with current working version. * Added copyright notice to Makefiles, *.c and *.h files. * Updated some of the documentation. * * Revision 1.1.1.1 2002/12/03 20:20:46 robust * Import of s3decode. * * */ <file_sep>/sphinx_fsttools/sphinx_dict_fst.cc /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2008 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file sphinx_dict_fst.cc * * Build finite-state transducers from Sphinx dictionaries. */ #include <fst/fstlib.h> namespace sb { #include <cmd_ln.h> #include <hash_table.h> #include <err.h> #include "dict.h" #include "mdef.h" }; #include "fstprinter.h" using namespace fst; using namespace sb; using sb::int32; /* Override conflicting typedefs */ typedef StdArc::StateId StateId; typedef StdArc::Label Label; static const arg_t args[] = { { "-mdef", ARG_STRING, NULL, "Model definition input file" }, { "-dict", REQARG_STRING, NULL, "Main pronunciation dictionary (lexicon) input file" }, { "-dictcase", ARG_BOOLEAN, "no", "Dictionary is case sensitive (NOTE: case insensitivity applies to ASCII characters only)" }, { "-fdict", ARG_STRING, NULL, "Noise word pronunciation dictionary input file" }, { "-usealt", ARG_BOOLEAN, "no", "Keep alternate pronunciation markers on word strings" }, { "-binfst", ARG_STRING, NULL, "Binary FST output file" }, { "-txtfst", ARG_STRING, NULL, "Text FST output file" }, { "-isym", ARG_STRING, NULL, "Input symbol table output file" }, { "-osym", ARG_STRING, NULL, "Output symbol table output file" }, { "-closure", ARG_BOOLEAN, "yes", "Output Kleene closure of dictionary" }, { "-determinize", ARG_BOOLEAN, "no", "Determinize output FST" }, { "-minimize", ARG_BOOLEAN, "yes", "Minimize output FST (only if -determinize yes)" }, { NULL, 0, NULL, NULL } }; static StdVectorFst * dict_to_fst(dict_t *dict, bool usealt) { /* Create a mutable FST, and symbol tables. */ StdVectorFst *model = new StdVectorFst; SymbolTable *isym = new SymbolTable("phones"); SymbolTable *osym = new SymbolTable("words"); StateId start = model->AddState(); StateId end = model->AddState(); model->SetStart(start); model->SetFinal(end, 0); /* Populate symbol tables with phones and words from the dictionary. */ isym->AddSymbol("&epsilon;", 0); for (int32 i = 0; i < dict_n_ciphone(dict); ++i) { isym->AddSymbol(dict_ciphone_str(dict, i), i+1); } Label first_wbound = isym->AddSymbol("#0"); Label last_wbound = first_wbound; osym->AddSymbol("&epsilon;", 0); for (int32 i = 0; i < dict_n_words(dict); ++i) { if (usealt) { osym->AddSymbol(dict_word_str(dict, i), i+1); } else { if (osym->Find(dict_base_str(dict, i)) == -1) { osym->AddSymbol(dict_base_str(dict, i), dict_base_wid(dict, i) + 1); } } } /* Track boundary symbols for each unique pronunciation. */ hash_table_t *pbsym = hash_table_new(dict_n_words(dict), HASH_CASE_YES); /* For each word in the dictionary: */ for (int32 i = 0; i < dict_n_words(dict); ++i) { /* Look for homophones. */ int32 wbound; if (hash_table_lookup_bkey_int32(pbsym, (char const *)dict->dict_list[i]->ci_phone_ids, dict_pronlen(dict, i) * sizeof(*dict->dict_list[i]->ci_phone_ids), &wbound) != 0) { wbound = first_wbound; } else { ++wbound; if (wbound > last_wbound) { char wbsym[16]; sprintf(wbsym, "#%d", wbound - first_wbound); isym->AddSymbol(wbsym, wbound); last_wbound = wbound; } printf("Word %s has duplicate pronunciation, using #%d\n", dict_word_str(dict, i), wbound - first_wbound); } hash_table_replace_bkey_int32(pbsym, (char const *)dict->dict_list[i]->ci_phone_ids, dict_pronlen(dict, i) * sizeof(*dict->dict_list[i]->ci_phone_ids), wbound); /* Build arcs for this word. */ Label wid; if (usealt) { wid = osym->Find(dict_word_str(dict, i)); } else { wid = osym->Find(dict_base_str(dict, i)); } StateId n = start; for (int32 j = 0; j < dict_pronlen(dict, i); ++j) { StateId m = model->AddState(); Label ci = dict_ciphone(dict, i, j) + 1; if (j == 0) model->AddArc(n, StdArc(ci, wid, 0, m)); else model->AddArc(n, StdArc(ci, 0, 0, m)); n = m; } model->AddArc(n, StdArc(wbound, 0, 0, end)); } hash_table_free(pbsym); model->SetInputSymbols(isym); model->SetOutputSymbols(osym); return model; } int main(int argc, char *argv[]) { /* Load Sphinx model files. */ dict_t *dict; mdef_t *mdef = NULL; cmd_ln_t *config; if ((config = cmd_ln_parse_r(NULL, args, argc, argv, TRUE)) == NULL) { return 1; } if (cmd_ln_str_r(config, "-mdef")) { if ((mdef = mdef_init(cmd_ln_str_r(config, "-mdef"), TRUE)) == NULL) { E_ERROR("Failed to load model definition file from %s\n", cmd_ln_str_r(config, "-mdef")); return 1; } } if ((dict = dict_init(config, mdef)) == NULL) { E_ERROR("Failed to load dictionary files\n"); return 1; } /* Create FST from dict. */ StdVectorFst *model = dict_to_fst(dict, cmd_ln_boolean_r(config, "-usealt")); /* Determinize, minimize, and epsilon-remove the model. */ if (cmd_ln_boolean_r(config, "-determinize")) { StdVectorFst *detmodel = new StdVectorFst(); Determinize(*model, detmodel); if (cmd_ln_boolean_r(config, "-minimize")) { Minimize(detmodel); } delete model; model = detmodel; } if (cmd_ln_boolean_r(config, "-closure")) Closure(model, CLOSURE_PLUS); /* Also sort it so it can be composed with a grammar. */ ArcSort(model, OLabelCompare<StdArc>()); /* Write the model in the requested format. */ char const *outfile; if ((outfile = cmd_ln_str_r(config, "-binfst")) != NULL) { model->Write(outfile); } if ((outfile = cmd_ln_str_r(config, "-txtfst")) != NULL) { FstPrinter<StdArc> printer(*model, model->InputSymbols(), model->OutputSymbols(), NULL, false); ostream *ostrm = new ofstream(outfile); printer.Print(ostrm, outfile); } if ((outfile = cmd_ln_str_r(config, "-isym")) != NULL) { model->InputSymbols()->WriteText(outfile); } if ((outfile = cmd_ln_str_r(config, "-osym")) != NULL) { model->OutputSymbols()->WriteText(outfile); } dict_free(dict); mdef_free(mdef); cmd_ln_free_r(config); return 0; } <file_sep>/SphinxTrain/include/s3/cmd_ln.h /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.h * * Description: * This module defines, parses and manages the validation * of command line arguments. * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #ifndef S3CMD_LN_H #define S3CMD_LN_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/prim_type.h> #include <s3/feat.h> #ifndef NULL #define NULL (void *)0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif typedef int (*validation_fn_t)(char *switch_name, void *arg); #define CMD_LN_NO_VALIDATION (validation_fn_t)NULL #define CMD_LN_NO_DEFAULT (char *)NULL typedef enum { CMD_LN_UNDEF, CMD_LN_INT32, CMD_LN_FLOAT32, CMD_LN_FLOAT64, CMD_LN_STRING, CMD_LN_STRING_LIST, CMD_LN_BOOLEAN } arg_type_t; typedef struct arg_def_s { char *switch_name; /* name of the command line switch */ arg_type_t type; /* type of the argument */ validation_fn_t validate_arg; /* a function which validates argument values */ const void *default_value; /* the default value of the argument, if any */ char *doc; /* a documentation string for the argument */ } arg_def_t; /* Initializes the command line parsing subsystem */ void cmd_ln_initialize(void); void cmd_ln_print_configuration(void); /* Defines the set of acceptable command line arguments * given the list of command line argument defintions * contained in the switch_definition_array. An element * of the array contains the following information: * * . switch name (e.g. "-dictionary") * * . type of the argument following the switch * * . an optional validation function for the * value given on the command line. * * . a translation function for the * value given on the command line. This * function is optional except for * enumerated types. * * This function allocates memory, if necessary, for * parsed command line arguments. */ int cmd_ln_define(arg_def_t *defn); /* * Directs the module to skip/not skip the printing * of the entire comment line to stderr. Default * is not to skip. */ void cmd_ln_skip_print(int state); /* * Reads the command line and converts the arguments, * if necessary, according to their definitions. */ int cmd_ln_parse(int argc, char *argv[]); /* * Calls the validation functions for each of the * command line arguments. */ int cmd_ln_validate(void); /* Returns a pointer to the parsed command line argument. (The returned pointer must not be given to the function free()) It is const because the caller should not modify the thing referred to by this pointer. */ const void * cmd_ln_access(char *switch_name); /* * Some convenient wrappers around this function. */ #define cmd_ln_str(name) ((char *)cmd_ln_access(name)) #define cmd_ln_int32(name) (*((int32 *)cmd_ln_access(name))) #define cmd_ln_float32(name) (*((float32 *)cmd_ln_access(name))) #define cmd_ln_float64(name) (*((float64 *)cmd_ln_access(name))) #define cmd_ln_boolean(name) (*((int32 *)cmd_ln_access(name))) /* Prints out the command line argument definitions to stderr */ void cmd_ln_print_definitions(void); #ifdef __cplusplus } #endif #endif /* S3CMD_LN_H */ /* * Log record. Maintained by CVS. * * $Log$ * Revision 1.5 2004/11/22 23:19:05 egouvea * Implemented suppport for log spec. The option was there from the * command line, but, alas, the code wasn't implemented. * * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.5 1996/07/29 16:40:50 eht * added missing function prototype * * Revision 1.4 1996/03/25 15:48:45 eht * Added void prototype for functions w/ no arguments * * Revision 1.3 1996/01/26 18:29:54 eht * Define TRUE and FALSE correctly * * Revision 1.2 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.1 1995/08/15 13:44:14 eht * Initial revision * * */ <file_sep>/tools/riddler/java/edu/cmu/sphinx/tools/riddler/persist/audio/AudioDescriptor.java /** * Copyright 1999-2007 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * <p/> * User: <NAME> * Date: Jan 13, 2007 * Time: 9:37:06 PM */ package edu.cmu.sphinx.tools.riddler.persist.audio; import javax.persistence.*; /** * Describes an Audio record and holds its data. * @see edu.cmu.sphinx.tools.riddler.persist.Corpus * @author <NAME> */ @Entity public abstract class AudioDescriptor { protected int samplesPerSecond; protected int channelCount; protected String filename; @Id @GeneratedValue(strategy = GenerationType.TABLE) protected String id; protected AudioDescriptor() { } public AudioDescriptor(int samplesPerSecond, int channelCount, String filename) { this.samplesPerSecond = samplesPerSecond; this.channelCount = channelCount; this.filename = filename; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getSamplesPerSecond() { return samplesPerSecond; } public void setSamplesPerSecond(int samplesPerSecond) { this.samplesPerSecond = samplesPerSecond; } public int getChannelCount() { return channelCount; } public void setChannelCount(int channelCount) { this.channelCount = channelCount; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } } <file_sep>/archive_s3/s3.0/pgm/misc/realign.c /* * realign.c -- Try to improve phone alignment for utternaces, given an initial alignment. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 16-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libfeat/libfeat.h> #include <s3.h> static char *cepdir; static int32 cepsize; static char uttid[4096]; static float32 *var; /* Feature dimension variances */ typedef struct { char p[16]; int32 sf, nf; } pseg_t; static pseg_t *pseg; static int32 n_pseg; static void load_pseg (char *line) { char *lp, wd[1024]; int32 k, len, sf, nf; n_pseg = 0; lp = line; while ((k = sscanf (lp, "%s %d %d%n", wd, &sf, &nf, &len)) == 3) { lp += len; strcpy (pseg[n_pseg].p, wd); pseg[n_pseg].sf = sf; pseg[n_pseg].nf = nf; n_pseg++; } assert (k == 1); assert (wd[0] == '('); k = strlen(wd); assert (wd[k-1] == ')'); wd[k-1] = '\0'; strcpy (uttid, wd+1); } static float64 eucl_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = f1[i] - f2[i]; dist += d*d; } return sqrt(dist); } static float64 maha_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = (f1[i] - f2[i]); dist += d*d / var[i]; } return sqrt(dist); } static void compute_var (float32 **mfc, int32 nfr) { float32 *sum, *mean; int32 i, j; sum = (float32 *) ckd_calloc (cepsize, sizeof(float32)); mean = (float32 *) ckd_calloc (cepsize, sizeof(float32)); for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += mfc[i][j]; } for (i = 0; i < cepsize; i++) mean[i] = sum[i]/(float64)nfr; for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += (mfc[i][j] - mean[j]) * (mfc[i][j] - mean[j]); } for (i = 0; i < cepsize; i++) var[i] = sum[i]/(float64)nfr; /* Hack!! Scale variances */ for (i = 0; i < cepsize; i++) printf (" %.3f", var[i]); printf ("\n"); for (i = 0; i < cepsize; i++) var[i] *= (1.0 + (float64)(i*cepsize*0.5)/(float64)cepsize); for (i = 0; i < cepsize; i++) printf (" %.3f", var[i]); printf ("\n"); ckd_free (sum); ckd_free (mean); } static void realign (float32 **mfc, int32 nfr) { } static void process_psegfile (char *cepdir) { char cepfile[4096], line[16384]; int32 nfr; float32 **mfc; while (fgets (line, sizeof(line), stdin) != NULL) { load_pseg (line); sprintf (cepfile, "%s/%s.mfc", cepdir, uttid); if ((nfr = s2mfc_read (cepfile, 0, (int32)0x70000000, &mfc)) <= 0) E_FATAL("MFC file read (%s) failed\n", cepfile); E_INFO("%d frames, %d phone segments\n", nfr, n_pseg); compute_var (mfc, nfr); } } main (int32 argc, char *argv[]) { char *psegfile; int32 i; if (argc != 2) E_FATAL("Usage: %s cepdir\n", argv[0]); cepdir = argv[1]; feat_init ("s3_1x39"); cepsize = feat_cepsize (); var = (float32 *) ckd_calloc (cepsize, sizeof(float32)); pseg = (pseg_t *) ckd_calloc (S3_MAX_FRAMES, sizeof(pseg_t)); process_psegfile (cepdir); exit(0); } <file_sep>/SphinxTrain/src/programs/bw/viterbi.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: viterbi.h * * Description: * * Author: * <NAME> *********************************************************************/ #ifndef VITERBI_H #define VITERBI_H #include <s3/prim_type.h> #include <s3/vector.h> #include <s3/state.h> #include <s3/model_inventory.h> #include <s3/s3phseg_io.h> int32 write_phseg(const char *filename, model_inventory_t *modinv, state_t *state_seq, uint32 **active_astate, uint32 *n_active_astate, uint32 n_state, uint32 n_obs, float64 **active_alpha, float64 *scale, uint32 **bp); int32 write_s2stseg(const char *filename, state_t *state_seq, uint32 **active_astate, uint32 *n_active_astate, uint32 n_state, uint32 n_obs, uint32 **bp); int32 viterbi_update(float64 *log_forw_prob, vector_t **feature, uint32 n_obs, state_t *state, uint32 n_state, model_inventory_t *inv, float64 a_beam, float32 spthresh, s3phseg_t *phseg, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 pass2var, int32 var_is_full, FILE *pdumpfh, float32 ***lda); #endif /* VITERBI_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:38:16 eht * *** empty log message *** * * Revision 1.1 1996/07/29 16:22:23 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/wave2feat/wave2feat.c /* ==================================================================== * Copyright (c) 1996-2004 Car<NAME> University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <stdio.h> #include <stdlib.h> #if !defined(WIN32) #include <unistd.h> #include <sys/file.h> #if !defined(O_BINARY) #define O_BINARY 0 #endif #endif #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #if defined(WIN32) #include <io.h> #include <errno.h> #endif #include "fe.h" #include "fe_internal.h" #include "wave2feat.h" #include "parse_cmd_ln.h" #include <s3/common.h> /* 7-Feb-00 <NAME> - wrapper created for new front end - does blockstyle processing if necessary. If input stream is greater than DEFAULT_BLOCKSIZE samples (currently 200000) then it will read and write in DEFAULT_BLOCKSIZE chunks. Had to change fe_process_utt(). Now the 2d feature array is allocated internally to that function rather than externally in the wrapper. Added usage display with -help switch for help 14-Feb-00 <NAME> - added NIST header parsing for big endian/little endian parsing. kind of a hack. changed -wav switch to -nist to avoid future confusion with MS wav files added -mach_endian switch to specify machine's byte format */ int32 main(int32 argc, char **argv) { param_t *P; P = fe_parse_options(argc,argv); if (fe_convert_files(P) != FE_SUCCESS){ E_FATAL("error converting files...exiting\n"); } fe_free_param(P); return(0); } int32 fe_convert_files(param_t *P) { fe_t *FE; char *infile,*outfile, fileroot[MAXCHARS]; FILE *ctlfile; int16 *spdata=NULL; int32 splen = 0,total_samps,frames_proc,nframes,nblocks,last_frame; int32 fp_in,fp_out, last_blocksize=0,curr_block,total_frames; float32 **cep = NULL, **last_frame_cep; int32 return_value; int32 warn_zero_energy = OFF; int32 process_utt_return_value; if ((FE = fe_init(P))==NULL){ E_ERROR("Initialization failed...exiting\n"); return(FE_MEM_ALLOC_ERROR); } if (P->is_batch){ int32 nskip = P->nskip; int32 runlen = P->runlen; if ((ctlfile = fopen(P->ctlfile,"r")) == NULL){ E_ERROR("Unable to open control file %s\n",P->ctlfile); return(FE_CONTROL_FILE_ERROR); } while (fscanf(ctlfile,"%s",fileroot)!=EOF){ if (nskip > 0) { --nskip; continue; } if (runlen > 0) { --runlen; } else if (runlen == 0) { break; } fe_build_filenames(P,fileroot,&infile,&outfile); if (P->verbose) E_INFO("%s\n",infile); return_value = fe_openfiles(P,FE,infile,&fp_in,&total_samps,&nframes,&nblocks,outfile,&fp_out); if (return_value != FE_SUCCESS){ return(return_value); } warn_zero_energy = OFF; if (nblocks*P->blocksize>=total_samps) last_blocksize = total_samps - (nblocks-1)*P->blocksize; if (!fe_start_utt(FE)){ curr_block=1; total_frames=frames_proc=0; /*execute this loop only if there is more than 1 block to be processed */ while(curr_block < nblocks){ splen = P->blocksize; if ((spdata = (int16 *)calloc(splen,sizeof(int16)))==NULL){ E_ERROR("Unable to allocate memory block of %d shorts for input speech\n",splen); return(FE_MEM_ALLOC_ERROR); } if (fe_readblock_spch(P,fp_in,splen,spdata)!=splen){ E_ERROR("error reading speech data\n"); return(FE_INPUT_FILE_READ_ERROR); } process_utt_return_value = fe_process_utt(FE,spdata,splen,&cep, &frames_proc); if (process_utt_return_value != FE_SUCCESS) { if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { return(process_utt_return_value); } } if (frames_proc>0) fe_writeblock_feat(P,FE,fp_out,frames_proc,cep); if (cep != NULL) { ckd_free_2d((void **)cep); cep = NULL; } curr_block++; total_frames += frames_proc; if (spdata!=NULL) { free(spdata); spdata = NULL; } } /* process last (or only) block */ if (spdata!=NULL) { free(spdata); spdata = NULL; } splen=last_blocksize; if ((spdata = (int16 *)calloc(splen,sizeof(int16)))==NULL){ E_ERROR("Unable to allocate memory block of %d shorts for input speech\n",splen); return(FE_MEM_ALLOC_ERROR); } if (fe_readblock_spch(P,fp_in,splen,spdata)!=splen){ E_ERROR("error reading speech data\n"); return(FE_INPUT_FILE_READ_ERROR); } process_utt_return_value = fe_process_utt(FE,spdata,splen,&cep, &frames_proc); if (process_utt_return_value != FE_SUCCESS) { if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { return(process_utt_return_value); } } if (frames_proc>0) fe_writeblock_feat(P,FE,fp_out,frames_proc,cep); if (cep != NULL) { ckd_free_2d((void **)cep); cep = NULL; } curr_block++; if (P->logspec != ON) last_frame_cep = (float32 **)ckd_calloc_2d(1,FE->NUM_CEPSTRA,sizeof(float32)); else last_frame_cep = (float32 **)ckd_calloc_2d(1,FE->MEL_FB->num_filters,sizeof(float32)); process_utt_return_value = fe_end_utt(FE, last_frame_cep[0], &last_frame); if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { assert(process_utt_return_value == FE_SUCCESS); } if (last_frame>0){ fe_writeblock_feat(P,FE,fp_out,last_frame,last_frame_cep); frames_proc++; } total_frames += frames_proc; fe_closefiles(fp_in,fp_out); if (spdata != NULL) { free(spdata); spdata = NULL; } if (last_frame_cep != NULL) { ckd_free_2d((void **)last_frame_cep); last_frame_cep = NULL; } if (ON == warn_zero_energy) { E_WARN("File %s has some frames with zero energy. Consider using dither\n", infile); } } else{ E_ERROR("fe_start_utt() failed\n"); return(FE_START_ERROR); } } fe_close(FE); } else if (P->is_single){ fe_build_filenames(P,fileroot,&infile,&outfile); if (P->verbose) printf("%s\n",infile); return_value = fe_openfiles(P,FE,infile,&fp_in,&total_samps,&nframes,&nblocks,outfile,&fp_out); if (return_value != FE_SUCCESS){ return(return_value); } warn_zero_energy = OFF; if (nblocks*P->blocksize>=total_samps) last_blocksize = total_samps - (nblocks-1)*P->blocksize; if (!fe_start_utt(FE)){ curr_block=1; total_frames=frames_proc=0; /*execute this loop only if there are more than 1 block to be processed */ while(curr_block < nblocks){ splen = P->blocksize; if ((spdata = (int16 *)calloc(splen,sizeof(int16)))==NULL){ E_ERROR("Unable to allocate memory block of %d shorts for input speech\n",splen); return(FE_MEM_ALLOC_ERROR); } if (fe_readblock_spch(P,fp_in,splen,spdata)!=splen){ E_ERROR("Error reading speech data\n"); return(FE_INPUT_FILE_READ_ERROR); } process_utt_return_value = fe_process_utt(FE,spdata,splen,&cep, &frames_proc); if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { assert(process_utt_return_value == FE_SUCCESS); } if (frames_proc>0) fe_writeblock_feat(P,FE,fp_out,frames_proc,cep); if (cep != NULL) { ckd_free_2d((void **)cep); cep = NULL; } curr_block++; total_frames += frames_proc; if (spdata!=NULL) { free(spdata); spdata = NULL; } } /* process last (or only) block */ if (spdata!=NULL) { free(spdata); spdata = NULL; } splen =last_blocksize; if ((spdata = (int16 *)calloc(splen,sizeof(int16)))==NULL){ E_ERROR("Unable to allocate memory block of %d shorts for input speech\n",splen); return(FE_MEM_ALLOC_ERROR); } if (fe_readblock_spch(P,fp_in,splen,spdata)!=splen){ E_ERROR("Error reading speech data\n"); return(FE_INPUT_FILE_READ_ERROR); } process_utt_return_value = fe_process_utt(FE,spdata,splen,&cep, &frames_proc); if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { assert(process_utt_return_value == FE_SUCCESS); } if (frames_proc>0) fe_writeblock_feat(P,FE,fp_out,frames_proc,cep); if (cep != NULL) { ckd_free_2d((void **)cep); cep = NULL; } curr_block++; if (P->logspec != ON) last_frame_cep = (float32 **)ckd_calloc_2d(1,FE->NUM_CEPSTRA,sizeof(float32)); else last_frame_cep = (float32 **)ckd_calloc_2d(1,FE->MEL_FB->num_filters,sizeof(float32)); process_utt_return_value = fe_end_utt(FE, last_frame_cep[0], &last_frame); if (FE_ZERO_ENERGY_ERROR == process_utt_return_value) { warn_zero_energy = ON; } else { assert(process_utt_return_value == FE_SUCCESS); } if (last_frame>0){ fe_writeblock_feat(P,FE,fp_out,last_frame,last_frame_cep); frames_proc++; } total_frames += frames_proc; fe_closefiles(fp_in,fp_out); if (cep != NULL) { free(spdata); spdata = NULL; } if (last_frame_cep != NULL) { ckd_free_2d((void **)last_frame_cep); last_frame_cep = NULL; } } else{ E_ERROR("fe_start_utt() failed\n"); return(FE_START_ERROR); } fe_close(FE); if (ON == warn_zero_energy) { E_WARN("File %s has some frames with zero energy. Consider using dither\n", infile); } } else{ E_ERROR("Unknown mode - single or batch?\n"); return(FE_UNKNOWN_SINGLE_OR_BATCH); } return(FE_SUCCESS); } void fe_validate_parameters(param_t *P) { if ((P->is_batch) && (P->is_single)) { E_FATAL("You cannot define an input file and a control file at the same time\n"); } if (P->wavfile == NULL && P->wavdir == NULL){ E_FATAL("No input file or file directory given\n"); } if (P->cepfile == NULL && P->cepdir == NULL){ E_FATAL("No cepstra file or file directory given\n"); } if (P->ctlfile==NULL && P->cepfile==NULL && P->wavfile==NULL){ E_FATAL("No control file given\n"); } if (P->nchans>1){ E_INFO("Files have %d channels of data\n", P->nchans); E_INFO("Will extract features for channel %d\n", P->whichchan); } if (P->whichchan > P->nchans) { E_FATAL("You cannot select channel %d out of %d\n", P->whichchan, P->nchans); } if ((P->UPPER_FILT_FREQ * 2) > P->SAMPLING_RATE) { E_WARN("Upper frequency higher than Nyquist frequency"); } if (P->doublebw==ON) { E_INFO("Will use double bandwidth filters\n"); } } param_t *fe_parse_options(int32 argc, char **argv) { param_t *P; int32 format; char *endian; parse_cmd_ln(argc, argv); if ((P=(param_t *)malloc(sizeof(param_t)))==NULL){ E_FATAL("memory alloc failed in fe_parse_options()\n...exiting\n"); } fe_init_params(P); P->wavfile = cmd_ln_str("-i"); if (P->wavfile != CMD_LN_NO_DEFAULT) { P->is_single = ON; } P->cepfile = cmd_ln_str("-o"); P->ctlfile = cmd_ln_str("-c"); if (P->ctlfile != CMD_LN_NO_DEFAULT) { char *nskip; char *runlen; P->is_batch = ON; nskip = cmd_ln_str("-nskip"); runlen = cmd_ln_str("-runlen"); if ( nskip != CMD_LN_NO_DEFAULT ) { P->nskip = atoi(nskip); } if ( runlen != CMD_LN_NO_DEFAULT ) { P->runlen = atoi(runlen); } } P->wavdir = cmd_ln_str("-di"); P->cepdir = cmd_ln_str("-do"); P->wavext = cmd_ln_str("-ei"); P->cepext = cmd_ln_str("-eo"); format = cmd_ln_int32("-raw"); if (format) { P->input_format = RAW; } format = cmd_ln_int32("-nist"); if (format) { P->input_format = NIST; } format = cmd_ln_int32("-mswav"); if (format) { P->input_format = MSWAV; } P->nchans = cmd_ln_int32("-nchans"); P->whichchan = cmd_ln_int32("-whichchan"); P->PRE_EMPHASIS_ALPHA = cmd_ln_float32("-alpha"); P->SAMPLING_RATE = cmd_ln_float32("-samprate"); P->WINDOW_LENGTH = cmd_ln_float32("-wlen"); P->FRAME_RATE = cmd_ln_int32("-frate"); if (!strcmp(cmd_ln_str("-feat"), "sphinx")) { P->FB_TYPE = MEL_SCALE; P->output_endian = BIG; } else { E_ERROR("MEL_SCALE IS CURRENTLY THE ONLY IMPLEMENTATION\n\n"); E_FATAL("Make sure you specify '-feat sphinx'\n"); } P->NUM_FILTERS = cmd_ln_int32("-nfilt"); P->NUM_CEPSTRA = cmd_ln_int32("-ncep"); P->LOWER_FILT_FREQ = cmd_ln_float32("-lowerf"); P->UPPER_FILT_FREQ = cmd_ln_float32("-upperf"); P->warp_type = cmd_ln_str("-warp_type"); P->warp_params = cmd_ln_str("-warp_params"); P->FFT_SIZE = cmd_ln_int32("-nfft"); if (cmd_ln_int32("-doublebw")) { P->doublebw = ON; } else { P->doublebw = OFF; } P->blocksize = cmd_ln_int32("-blocksize"); P->verbose = cmd_ln_int32("-verbose"); endian = cmd_ln_str("-mach_endian"); if (!strcmp("big", endian)) { P->machine_endian = BIG; } else { if (!strcmp("little", endian)) { P->machine_endian = LITTLE; } else { E_FATAL("Machine must be big or little Endian\n"); } } endian = cmd_ln_str("-input_endian"); if (!strcmp("big", endian)) { P->input_endian = BIG; } else { if (!strcmp("little", endian)) { P->input_endian = LITTLE; } else { E_FATAL("Input must be big or little Endian\n"); } } P->dither = cmd_ln_int32("-dither"); P->seed = cmd_ln_int32("-seed"); P->logspec = cmd_ln_int32("-logspec"); fe_validate_parameters(P); return (P); } int32 fe_build_filenames(param_t *P, char *fileroot, char **infilename, char **outfilename) { char cbuf[MAXCHARS]; char chanlabel[MAXCHARS]; if (P->nchans>1) sprintf(chanlabel, ".ch%d", P->whichchan); if (P->is_batch){ sprintf(cbuf,"%s",""); if (P->wavdir == NULL) { E_FATAL("Input directory not defined\n"); } strcat(cbuf,P->wavdir); strcat(cbuf,"/"); if (fileroot == NULL) { E_FATAL("File name not defined\n"); } strcat(cbuf,fileroot); strcat(cbuf,"."); if (P->wavext == NULL) { E_FATAL("Input file extension not defined\n"); } strcat(cbuf,P->wavext); if (infilename != NULL) { *infilename = fe_copystr(*infilename,cbuf); } sprintf(cbuf,"%s",""); if (P->cepdir == NULL) { E_FATAL("Output directory not defined\n"); } strcat(cbuf,P->cepdir); strcat(cbuf,"/"); strcat(cbuf,fileroot); if (P->nchans>1) strcat(cbuf, chanlabel); strcat(cbuf,"."); if (P->cepext == NULL) { E_FATAL("Output file extension not defined\n"); } strcat(cbuf,P->cepext); if (outfilename != NULL) { *outfilename = fe_copystr(*outfilename,cbuf); } } else if (P->is_single){ sprintf(cbuf,"%s",""); strcat(cbuf,P->wavfile); if (infilename != NULL) { *infilename = fe_copystr(*infilename,cbuf); } sprintf(cbuf,"%s",""); strcat(cbuf,P->cepfile); if (outfilename != NULL) { *outfilename = fe_copystr(*outfilename,cbuf); } } else{ E_FATAL("Unspecified Batch or Single Mode\n"); } return 0; } char *fe_copystr(char *dest_str, char *src_str) { int i,src_len, len; char *s; src_len = strlen(src_str); len = src_len; s = (char *)malloc(len+1); for (i=0;i<src_len;i++) *(s+i) = *(src_str+i); *(s+src_len) = NULL_CHAR; return(s); } int32 fe_count_frames(fe_t *FE, int32 nsamps, int32 count_partial_frames) { int32 frame_start,frame_count = 0; for (frame_start=0;frame_start+FE->FRAME_SIZE<=nsamps; frame_start+=FE->FRAME_SHIFT) { frame_count++; } /* <EMAIL>, 2006-04-25: Update this to match the updated * partial frame condition in fe_process_utt(). */ if (count_partial_frames){ if (frame_count*FE->FRAME_SHIFT < nsamps) frame_count++; } return(frame_count); } int32 fe_openfiles(param_t *P, fe_t *FE, char *infile, int32 *fp_in, int32 *nsamps, int32 *nframes, int32 *nblocks, char *outfile, int32 *fp_out) { struct stat filestats; int fp=0, len=0, outlen, numframes, numblocks; FILE *fp2; char line[MAXCHARS]; int got_it=0; /* Note: this is kind of a hack to read the byte format from the NIST header */ if (P->input_format == NIST){ if ((fp2 = fopen(infile,"rb")) == NULL){ E_ERROR("Cannot read %s\n",infile); return(FE_INPUT_FILE_READ_ERROR); } *line=0; got_it = 0; while(strcmp(line,"end_head") && !got_it){ fscanf(fp2,"%s",line); if (!strcmp(line,"sample_byte_format")){ fscanf(fp2,"%s",line); if (!strcmp(line,"-s2")){ fscanf(fp2,"%s",line); if (!strcmp(line,"01")){ P->input_endian=LITTLE; got_it=1; } else if(!strcmp(line,"10")){ P->input_endian=BIG; got_it = 1; } else E_ERROR("Unknown/unsupported byte order\n"); } else E_ERROR("Error determining byte format\n"); } } if (!got_it){ E_WARN("Can't find byte format in header, setting to machine's endian\n"); P->input_endian = P->machine_endian; } fclose(fp2); } else if (P->input_format == RAW){ /* P->input_endian = P->machine_endian; */ } else if (P->input_format == MSWAV){ P->input_endian = LITTLE; /* Default for MS WAV riff files*/ } if ((fp = open(infile, O_RDONLY | O_BINARY, 0644))<0){ fprintf(stderr,"Cannot open %s\n",infile); return (FE_INPUT_FILE_OPEN_ERROR); } else{ if (fstat(fp,&filestats)!=0) printf("fstat failed\n"); if (P->input_format == NIST){ short *hdr_buf; len = (filestats.st_size-HEADER_BYTES)/sizeof(short); /* eat header */ hdr_buf = (short *)calloc(HEADER_BYTES/sizeof(short),sizeof(short)); if (read(fp,hdr_buf,HEADER_BYTES)!=HEADER_BYTES){ E_ERROR("Cannot read %s\n",infile); return (FE_INPUT_FILE_READ_ERROR); } free(hdr_buf); } else if (P->input_format == RAW){ len = filestats.st_size/sizeof(int16); } else if (P->input_format == MSWAV){ /* Read the header */ MSWAV_hdr *hdr_buf = NULL; /* MC: read till just before datatag */ const int hdr_len_to_read = offsetof (MSWAV_hdr, datatag); if ((hdr_buf = (MSWAV_hdr *) calloc(1, sizeof(MSWAV_hdr))) == NULL) { E_ERROR("Cannot allocate for input file header\n"); return (FE_INPUT_FILE_READ_ERROR); } if (read(fp,hdr_buf,hdr_len_to_read) != hdr_len_to_read){ E_ERROR("Cannot allocate for input file header\n"); return (FE_INPUT_FILE_READ_ERROR); } /* Check header */ if (strncmp(hdr_buf->rifftag, "RIFF", 4) != 0 || strncmp(hdr_buf->wavefmttag, "WAVEfmt", 7) != 0) { E_ERROR("Error in mswav file header\n"); return (FE_INPUT_FILE_READ_ERROR); } { /* There may be other "chunks" before the data chunk, * which we can ignore. We have to find the start of * the data chunk, which begins with the string * "data". */ int16 found=OFF; char readChar; char *dataString = "data"; int16 charPointer = 0; while (found != ON) { if (read(fp,&readChar,sizeof(char)) != sizeof(char)){ E_ERROR("Failed reading wav file.\n"); return (FE_INPUT_FILE_READ_ERROR); } if (readChar == dataString[charPointer]) { charPointer++; } if (charPointer == (int)strlen(dataString)) { found = ON; strcpy(hdr_buf->datatag, dataString); if (read(fp,&(hdr_buf->datalength),sizeof(int32)) != sizeof(int32)){ E_ERROR("Failed reading wav file.\n"); return (FE_INPUT_FILE_READ_ERROR); } } } } if (P->input_endian!=P->machine_endian) { /* If machine is Big Endian*/ hdr_buf->datalength = SWAPL(&(hdr_buf->datalength)); hdr_buf->data_format = SWAPW(&(hdr_buf->data_format)); hdr_buf->numchannels = SWAPW(&(hdr_buf->numchannels)); hdr_buf->BitsPerSample = SWAPW(&(hdr_buf->BitsPerSample)); hdr_buf->SamplingFreq = SWAPL(&(hdr_buf->SamplingFreq)); hdr_buf->BytesPerSec = SWAPL(&(hdr_buf->BytesPerSec)); } /* Check Format */ if (hdr_buf->data_format != 1 || hdr_buf->BitsPerSample != 16){ E_ERROR("MS WAV file not in 16-bit PCM format\n"); return (FE_INPUT_FILE_READ_ERROR); } len = hdr_buf->datalength / sizeof(short); P->nchans = hdr_buf->numchannels; /* DEBUG: Dump Info */ if (P->verbose) { E_INFO("Reading MS Wav file %s:\n", infile); E_INFO("\t16 bit PCM data, %d channels %d samples\n",P->nchans,len); E_INFO("\tSampled at %d\n",hdr_buf->SamplingFreq); } free(hdr_buf); } else { E_ERROR("Unknown input file format\n"); return(FE_INPUT_FILE_OPEN_ERROR); } } len = len/P->nchans; *nsamps = len; *fp_in = fp; numblocks = (int)((float)len/(float)P->blocksize); if (numblocks*P->blocksize<len) numblocks++; *nblocks = numblocks; if ((fp = open(outfile, O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, 0644)) < 0) { E_ERROR("Unable to open %s for writing features\n",outfile); return(FE_OUTPUT_FILE_OPEN_ERROR); } else{ /* compute number of frames and write cepfile header */ numframes = fe_count_frames(FE,len,COUNT_PARTIAL); if (P->logspec != ON) outlen = numframes*FE->NUM_CEPSTRA; else outlen = numframes*FE->MEL_FB->num_filters; if (P->output_endian != P->machine_endian) SWAPL(&outlen); if (write(fp, &outlen, 4) != 4) { E_ERROR("Data write error on %s\n",outfile); close(fp); return(FE_OUTPUT_FILE_WRITE_ERROR); } if (P->output_endian != P->machine_endian) SWAPL(&outlen); } *nframes = numframes; *fp_out = fp; return 0; } int32 fe_readblock_spch(param_t *P, int32 fp, int32 nsamps, int16 *buf) { int32 bytes_read, cum_bytes_read, nreadbytes, actsamps, offset, i, j, k; int16 *tmpbuf; int32 nchans, whichchan; nchans = P->nchans; whichchan = P->whichchan; if (nchans==1){ if (P->input_format==RAW || P->input_format==NIST || P->input_format==MSWAV){ nreadbytes = nsamps*sizeof(int16); if ((bytes_read = read(fp,buf,nreadbytes))!=nreadbytes){ E_ERROR("error reading block\n"); return(0); } } else{ E_ERROR("unknown input file format\n"); return(0); } cum_bytes_read = bytes_read; } else if (nchans>1){ if (nsamps<P->blocksize){ actsamps = nsamps*nchans; tmpbuf = (int16 *)calloc(nsamps*nchans,sizeof(int16)); cum_bytes_read = 0; if (P->input_format==RAW || P->input_format==NIST){ k=0; nreadbytes = actsamps*sizeof(int16); if ((bytes_read = read(fp,tmpbuf,nreadbytes))!=nreadbytes){ E_ERROR("error reading block (got %d not %d)\n",bytes_read,nreadbytes); return(0); } for (j=whichchan-1;j<actsamps;j=j+nchans){ buf[k] = tmpbuf[j]; k++; } cum_bytes_read += bytes_read/nchans; } else{ E_ERROR("unknown input file format\n"); return(0); } free(tmpbuf); } else{ tmpbuf = (int16 *)calloc(nsamps,sizeof(int16)); actsamps = nsamps/nchans; cum_bytes_read = 0; if (actsamps*nchans != nsamps){ E_WARN("Blocksize %d is not an integer multiple of Number of channels %d\n",nsamps, nchans); } if (P->input_format==RAW || P->input_format==NIST){ for (i=0;i<nchans;i++){ offset = i*actsamps; k=0; nreadbytes = nsamps*sizeof(int16); if ((bytes_read = read(fp,tmpbuf,nreadbytes))!=nreadbytes){ E_ERROR("error reading block (got %d not %d)\n",bytes_read,nreadbytes); return(0); } for (j=whichchan-1;j<nsamps;j=j+nchans){ buf[offset+k] = tmpbuf[j]; k++; } cum_bytes_read += bytes_read/nchans; } } else{ E_ERROR("unknown input file format\n"); return(0); } free(tmpbuf); } } else{ E_ERROR("unknown number of channels!\n"); return(0); } if (P->input_endian!=P->machine_endian){ for(i=0;i<nsamps;i++) SWAPW(&buf[i]); } return(cum_bytes_read/sizeof(int16)); } int32 fe_writeblock_feat(param_t *P, fe_t *FE, int32 fp, int32 nframes, float32 **feat) { int32 i, length, nwritebytes; if (P->logspec == ON) length = nframes*FE->MEL_FB->num_filters; else length = nframes*FE->NUM_CEPSTRA; if (P->output_endian != P->machine_endian){ for (i=0;i<length;++i) SWAPF(feat[0]+i); } nwritebytes = length*sizeof(float32); if (write(fp, feat[0], nwritebytes) != nwritebytes) { close(fp); E_FATAL("Error writing block of features\n"); } if (P->output_endian != P->machine_endian){ for (i=0;i<length;++i) SWAPF(feat[0]+i); } return(length); } int32 fe_closefiles(int32 fp_in, int32 fp_out) { close(fp_in); close(fp_out); return 0; } int32 fe_free_param(param_t *P) { /* but no one calls it (29/09/00) */ return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.35 2006/02/25 00:53:48 egouvea * Added the flag "-seed". If dither is being used and the seed is less * than zero, the random number generator is initialized with time(). If * it is at least zero, it's initialized with the provided seed. This way * we have the benefit of having dither, and the benefit of being * repeatable. * * This is consistent with what sphinx3 does. Well, almost. The random * number generator is still what the compiler provides. * * Also, moved fe_init_params to fe_interface.c, so one can initialize a * variable of type param_t with meaningful values. * * Revision 1.34 2006/02/20 23:55:51 egouvea * Moved fe_dither() to the "library" side rather than the app side, so * the function can be code when using the front end as a library. * * Revision 1.33 2006/02/17 00:31:34 egouvea * Removed switch -melwarp. Changed the default for window length to * 0.025625 from 0.256 (so that a window at 16kHz sampling rate has * exactly 410 samples). Cleaned up include's. Replaced some E_FATAL() * with E_WARN() and return. * * Revision 1.32 2006/02/16 20:11:20 egouvea * Fixed the code that prints a warning if any zero-energy frames are * found, and recommending the user to add dither. Previously, it would * only report the zero energy frames if they happened in the last * utterance. Now, it reports for each utterance. * * Revision 1.31 2006/02/16 00:18:26 egouvea * Implemented flexible warping function. The user can specify at run * time which of several shapes they want to use. Currently implemented * are an affine function (y = ax + b), an inverse linear (y = a/x) and a * piecewise linear (y = ax, up to a frequency F, and then it "breaks" so * Nyquist frequency matches in both scales. * * Added two switches, -warp_type and -warp_params. The first specifies * the type, which valid values: * * -inverse or inverse_linear * -linear or affine * -piecewise or piecewise_linear * * The inverse_linear is the same as implemented by EHT. The -mel_warp * switch was kept for compatibility (maybe remove it in the * future?). The code is compatible with EHT's changes: cepstra created * from code after his changes should be the same as now. Scripts that * worked with his changes should work now without changes. Tested a few * cases, same results. * */ <file_sep>/SphinxTrain/src/programs/bldtree/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 <NAME> University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description:\n\ \n\ Given a set of questions. Build decision tree for a set of feature of\n\ a particular phone. By default, decision tree are not built for \n\ filler phones and the phone tagged with SIL. One very confusing \n\ parameters of this tool is -stwt, if you are training a n-state \n\ HMM, you need to specify n values after this flag. "; const char examplestr[] = " bld_tree -treefn tree -moddeffn mdef -mixwfn mixw -meanfn mean -varfn \n\ var -psetfn questions -stwt 1.0 0.05 0.01 -state 0 -ssplitmin 1 \n\ -ssplitmax 7 -ssplitthr 1e-10 -csplitmin 1 -csplitmax 2000 -csplitthr \n\ 1e-10 -cntthresh 10"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-treefn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Name of output tree file to produce" }, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition file of the discrete models" }, /* ADDITION FOR CONTINUOUS_TREES */ { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".semi.", "The type of models to build trees on" }, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "means file for tree building using continuous HMMs" }, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "variances file for tree building using continuous HMMs" }, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "variances file contains full covariances" }, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "The minimum variance"}, { "-cntthresh", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "Ignore all states with counts less than this"}, /* END ADDITION FOR CONTINUOUS_TREES */ { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "PDF's for tree building using semicontinuous HMMs" }, { "-psetfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "phone set definitions for phonetic questions" }, { "-phone", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Build trees over n-phones having this base phone"}, { "-allphones", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Build trees over all n-phones"}, { "-state", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Build tree for this state position. E.g. For a three state HMM, this value can be 0,1 or 2. For a 5 state HMM, this value can be 0,1,2,3 or 4, and so on "}, { "-mwfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1e-4", "Mixing weight floor for tree building"}, { "-stwt", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Weights on neighboring states, This flag needs a string of numbers equal to the number of HMM-states"}, { "-ssplitthr", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "8e-4", "Simple node splitting threshold" }, { "-ssplitmin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "Minimum of simple tree splits to do."}, { "-ssplitmax", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "5", "The maximum number of bifurcations in the simple tree before it is used to build complex questions."}, { "-csplitthr", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "8e-4", "Compound node splitting threshold" }, { "-csplitmin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "Minimum # of compound tree splits to do" }, { "-csplitmax", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "100", "Minimum # of compound tree splits to do" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2005/06/13 22:18:22 dhdfu * Add -allphones arguments to decision tree and state tying code. Allows senones to be shared across multiple base phones (though they are currently still restricted to the same state). This can improve implicit pronunciation modeling in some cases, such as grapheme-based models, though it usually has little effect. Building the big trees can take a very long time. * * Revision 1.6 2004/11/29 01:43:44 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/11/29 01:11:18 egouvea * Fixed license terms in some new files. * * Revision 1.4 2004/11/29 00:49:20 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.3 2004/08/26 05:50:09 arthchan2003 * update bldtree's on-line help to clarify the use of -stwt. * * Revision 1.2 2004/08/08 01:58:55 arthchan2003 * adding help and example strings for bldtree * * Revision 1.1 2004/06/17 19:39:46 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libfbs/align.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * align.h -- Exported time-aligner functions and data structures. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * $Log$ * Revision 1.2 2002/12/03 23:02:37 egouvea * Updated slow decoder with current working version. * Added copyright notice to Makefiles, *.c and *.h files. * Updated some of the documentation. * * Revision 1.1.1.1 2002/12/03 20:20:46 robust * Import of s3decode. * * * 13-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed align_sen_active to flag active senones instead of building a list * of them. * * 15-Jul-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #ifndef _LIBFBS_ALIGN_H_ #define _LIBFBS_ALIGN_H_ #include <libutil/libutil.h> #include "s3types.h" /* State level segmentation/alignment; one entry per frame */ typedef struct align_stseg_s { s3pid_t pid; /* Phone id */ int8 state; /* State id within phone */ int8 start; /* Whether this is an entry into phone start state */ int32 score; /* Acoustic score for transition to this state from the previous one in the list */ int32 bsdiff; /* Distance between this state and the best in this frame */ struct align_stseg_s *next; /* Next state (in the next frame) in alignment */ } align_stseg_t; /* Phone level segmentation/alignment information */ typedef struct align_phseg_s { s3pid_t pid; /* Phone id */ s3frmid_t sf, ef; /* Start and end frame for this phone occurrence */ int32 score; /* Acoustic score for this segment of alignment */ int32 bsdiff; /* Distance between this and the best unconstrained state sequence for the same time segment */ struct align_phseg_s *next; /* Next entry in alignment */ } align_phseg_t; /* Word level segmentation/alignment information */ typedef struct align_wdseg_s { s3wid_t wid; /* Word id */ s3frmid_t sf, ef; /* Start and end frame for this word occurrence */ int32 score; /* Acoustic score for this segment of alignment */ int32 bsdiff; /* Distance between this and the best unconstrained state sequence for the same time segment */ struct align_wdseg_s *next; /* Next entry in alignment */ } align_wdseg_t; int32 align_init ( void ); int32 align_build_sent_hmm (char *transcript); int32 align_destroy_sent_hmm ( void ); int32 align_start_utt (char *uttid); /* * Called at the beginning of a frame to flag the active senones (any senone used * by active HMMs) in that frame. */ void align_sen_active (s3senid_t *senlist, /* Out: senlist[s] TRUE iff active in frame */ int32 n_sen); /* In: Size of senlist[] array */ /* Step time aligner one frame forward */ int32 align_frame (int32 *senscr); /* In: array of senone scores this frame */ /* * Wind up utterance and return final result (READ-ONLY). Results only valid until * the next utterance is begun. */ int32 align_end_utt (align_stseg_t **stseg, /* Out: list of state segmentation */ align_phseg_t **phseg, /* Out: list of phone segmentation */ align_wdseg_t **wdseg); /* Out: list of word segmentation */ #endif <file_sep>/archive_s3/s3.0/pgm/misc/testvq-int32.c #include <libutil/libutil.h> static int32 N_CB; /* E.g., 256 */ #define N_SEN 6000 #define N_DEN 16 #define N_DIM 39 static int32 dist2 (float32 *pre, int32 ***id, float32 **diff, int32 n_cl) { int32 c, d, i; float64 s; int32 *idl; for (c = 0; c < N_SEN; c++) { for (d = 0; d < N_DEN; d++) { idl = id[c][d]; s = 0; for (i = 0; i < n_cl; i++) s += pre[idl[i]]; diff[c][d] = s; } } } static int32 gauden_dist (float32 ***mean, float32 ***var, float32 *obs, float32 **diff) { float32 *m1, *v1, *m2, *v2; float64 dd1, dd2, s1, s2; int32 c, d, i; for (c = 0; c < N_CB; c++) { for (d = 0; d < N_DEN; d += 2) { m1 = mean[c][d]; m2 = mean[c][d+1]; v1 = var[c][d]; v2 = var[c][d+1]; s1 = 0.0; s2 = 0.0; for (i = 0; i < N_DIM; i++) { dd1 = obs[i] - m1[i]; s1 += dd1 * dd1 * v1[i]; dd2 = obs[i] - m2[i]; s2 += dd2 * dd2 * v2[i]; } diff[c][d] = s1; diff[c][d+1] = s2; } } } main (int32 argc, char *argv[]) { float32 ***mean, ***var, *obs, **diff, *pre; int32 c, d, i, j, r, f, n_cl; float32 *m, *v; int32 ***id; timing_t *tm; if (argc != 4) E_FATAL("Usage: %s <random-seed> <#clusters> <#cb>\n", argv[0]); if (sscanf (argv[1], "%d", &r) != 1) E_FATAL("Usage: %s <random-seed> <#clusters> <#cb>\n", argv[0]); if (sscanf (argv[2], "%d", &n_cl) != 1) E_FATAL("Usage: %s <random-seed> <#clusters> <#cb>\n", argv[0]); if (sscanf (argv[3], "%d", &N_CB) != 1) E_FATAL("Usage: %s <random-seed> <#clusters> <#cb>\n", argv[0]); srandom (r); mean = (float32 ***) ckd_calloc_3d (N_CB, N_DEN, N_DIM, sizeof(float32)); var = (float32 ***) ckd_calloc_3d (N_CB, N_DEN, N_DIM, sizeof(float32)); obs = (float32 *) ckd_calloc (N_DIM, sizeof(float32)); pre = (float32 *) ckd_calloc (N_CB * N_DEN * n_cl, sizeof(float32)); id = (int32 ***) ckd_calloc_3d (N_SEN, N_DEN, n_cl, sizeof(int32)); diff = (float32 **) ckd_calloc_2d (N_SEN, N_DEN, sizeof(float32)); for (c = 0; c < N_CB; c++) { for (d = 0; d < N_DEN; d++) { m = mean[c][d]; v = var[c][d]; for (i = 0; i < N_DIM; i++) { r = random() & 0x00007fff; if (r == 0) r = 1; m[i] = (float64)r * (1.0 / 32768.0); r = random() & 0x00007fff; if (r == 0) r = 1; v[i] = (float64)r * (1.0 / 32768.0); } } } j = 0; for (c = 0; c < N_CB; c++) { for (d = 0; d < N_DEN; d++) { for (i = 0; i < n_cl; i++) { r = random() & 0x00007fff; if (r == 0) r = 1; pre[j] = (float64)r * (1.0 / 32768.0); j++; } } } for (c = 0; c < N_SEN; c++) { for (d = 0; d < N_DEN; d++) { for (i = 0; i < n_cl; i++) { r = (random() & 0x7fffffff) % (N_CB * N_DEN); r *= n_cl; id[c][d][i] = r+i; } } } tm = timing_new ("timer"); timing_reset (tm); timing_start (tm); for (i = 0; i < N_DIM; i++) { r = random() & 0x00007fff; if (r == 0) r = 1; obs[i] = (float64)r * (1.0 / 32768.0); } for (f = 0; f < 100; f++) { gauden_dist (mean, var, obs, diff); dist2 (pre, id, diff, n_cl); } timing_stop (tm); printf ("%.2f sec CPU, %.2f sec elapsed\n", tm->t_tot_cpu, tm->t_tot_elapsed); } <file_sep>/archive_s3/s3/src/misc/lm.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * lm.c -- Word trigram LM module. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 07-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libutil/libutil.h> #include "s3types.h" #include "lm.h" #include "logs3.h" #include "s3.h" #if (! NO_DICT) #include "dict.h" #endif #define MAX_UG (65534) #define SWAP_UINT16(x) x = ( (((x)<<8)&0x0000ff00) | (((x)>>8)&0x00ff) ) #define SWAP_UINT32(x) x = ( (((x)<<24)&0xff000000) | (((x)<<8)&0x00ff0000) | \ (((x)>>8)&0x0000ff00) | (((x)>>24)&0x000000ff) ) #define MIN_PROB_F ((float32)-99.0) /* * Apply LW, UW, WIP. Convert values from from prob or log10(prob) to logS3(prob). */ static void lm_set_param (lm_t *lm, float64 lw, float64 uw, float64 wip) { int32 i, loguw, loguw_, p1, p2, loguniform; lm->lw = (float32) lw; lm->uw = (float32) uw; lm->wip = logs3 (wip); /* Interpolate unigram probs with uniform PDF, with weight uw */ loguw = logs3 (uw); loguw_ = logs3 (1.0 - uw); loguniform = logs3 (1.0/(lm->n_ug-1)); for (i = 0; i < lm->n_ug; i++) { if (strcmp (lm->wordstr[i], START_WORD) == 0) lm->ug[i].prob.l = log10_to_logs3 (lm->ug[i].prob.f) * lw + lm->wip; else { p1 = log10_to_logs3 (lm->ug[i].prob.f) + loguw; p2 = loguniform + loguw_; p1 = logs3_add (p1, p2); lm->ug[i].prob.l = p1 * lw + lm->wip; } lm->ug[i].bowt.l = log10_to_logs3 (lm->ug[i].bowt.f) * lw; } for (i = 0; i < lm->n_bgprob; i++) lm->bgprob[i].l = log10_to_logs3 (lm->bgprob[i].f) * lw + lm->wip; if (lm->n_tg > 0) { for (i = 0; i < lm->n_tgprob; i++) lm->tgprob[i].l = log10_to_logs3 (lm->tgprob[i].f) * lw + lm->wip; for (i = 0; i < lm->n_tgbowt; i++) lm->tgbowt[i].l = log10_to_logs3 (lm->tgbowt[i].f) * lw; } } static int32 lm_fread_int32 (lm_t *lm) { int32 val; if (fread (&val, sizeof(int32), 1, lm->fp) != 1) E_FATAL("fread failed\n"); if (lm->byteswap) SWAP_UINT32(val); return (val); } /* * Read LM dump (<lmname>.DMP) file and make it the current LM. * Same interface as lm_read except that the filename refers to a .DMP file. */ static lm_t *lm_read_dump (char *file, float64 lw, float64 uw, float64 wip) { lm_t *lm; int32 i, j, k, vn; char str[1024]; char *tmp_word_str; int32 notindict; lm = (lm_t *) ckd_calloc (1, sizeof(lm_t)); cur_lm = lm; if ((lm->fp = fopen (file, "rb")) == NULL) E_FATAL("fopen(%s,rb) failed\n", file); /* Standard header string-size; set byteswap flag based on this */ if (fread (&k, sizeof(int32), 1, lm->fp) != 1) E_FATAL("fread(%s) failed\n", file); if (k == strlen(darpa_hdr)+1) lm->byteswap = 0; else { SWAP_UINT32(k); if (k == strlen(darpa_hdr)+1) lm->byteswap = 1; else { SWAP_UINT32(k); E_FATAL("Bad magic number: %d(%08x), not an LM dumpfile??\n", k, k); } } /* Read and verify standard header string */ if (fread (str, sizeof (char), k, lm->fp) != k) E_FATAL("fread(%s) failed\n", file); if (strncmp (str, darpa_hdr, k) != 0) E_FATAL("Bad header\n"); /* Original LM filename string size and string */ k = lm_fread_int32 (lm); if ((k < 1) || (k > 1024)) E_FATAL("Bad original filename size: %d\n", k); if (fread (str, sizeof (char), k, lm->fp) != k) E_FATAL("fread(%s) failed\n", file); /* Version#. If present (must be <= 0); otherwise it's actually the unigram count */ vn = lm_fread_int32 (lm); if (vn <= 0) { /* Read and skip orginal file timestamp; (later compare timestamps) */ k = lm_fread_int32 (lm); /* Read and skip format description */ for (;;) { if ((k = lm_fread_int32 (lm)) == 0) break; if (fread (str, sizeof(char), k, lm->fp) != k) E_FATAL("fread(%s) failed\n", file); } /* Read #ug */ lm->n_ug = lm_fread_int32 (lm); } else { /* No version number, actually a unigram count */ lm->n_ug = vn; } if ((lm->n_ug <= 0) || (lm->n_ug > MAX_UG)) E_FATAL("Bad #unigrams: %d\n", lm->n_ug); /* #bigrams */ lm->n_bg = lm_fread_int32 (lm); if (lm->n_bg < 0) E_FATAL("Bad #bigrams: %d\n", lm->n_bg); /* #trigrams */ lm->n_tg = lm_fread_int32 (lm); if (lm->n_tg < 0) E_FATAL("Bad #trigrams: %d\n", lm->n_tg); /* Read unigrams; remember sentinel ug at the end! */ lm->ug = (ug_t *) ckd_calloc (lm->n_ug+1, sizeof(ug_t)); if (fread (lm->ug, sizeof(ug_t), lm->n_ug+1, lm->fp) != lm->n_ug+1) E_FATAL("fread(%s) failed\n", file); if (lm->byteswap) for (i = 0; i <= lm->n_ug; i++) { SWAP_UINT32(lm->ug[i].dictwid); SWAP_UINT32(lm->ug[i].prob.l); SWAP_UINT32(lm->ug[i].bowt.l); SWAP_UINT32(lm->ug[i].firstbg); } E_INFO("%8d unigrams\n", lm->n_ug); /* Space for in-memory bigrams/trigrams info; FOR NOW, DISK-BASED LM OPTION ONLY!! */ lm->bg = NULL; lm->tg = NULL; /* Skip bigrams; remember sentinel at the end */ if (lm->n_bg > 0) { lm->bgoff = ftell (lm->fp); fseek (lm->fp, (lm->n_bg+1) * sizeof(bg_t), SEEK_CUR); E_INFO("%8d bigrams [on disk]\n", lm->n_bg); lm->membg = (membg_t *) ckd_calloc (lm->n_ug, sizeof(membg_t)); } /* Skip trigrams */ if (lm->n_tg > 0) { lm->tgoff = ftell (lm->fp); fseek (lm->fp, lm->n_tg * sizeof(tg_t), SEEK_CUR); E_INFO("%8d trigrams [on disk]\n", lm->n_tg); lm->tginfo = (tginfo_t **) ckd_calloc (lm->n_ug, sizeof(tginfo_t *)); } if (lm->n_bg > 0) { /* Bigram probs table size */ lm->n_bgprob = lm_fread_int32 (lm); if ((lm->n_bgprob <= 0) || (lm->n_bgprob > 65536)) E_FATAL("Bad bigram prob table size: %d\n", lm->n_bgprob); /* Allocate and read bigram probs table */ lm->bgprob = (lmlog_t *) ckd_calloc (lm->n_bgprob, sizeof (lmlog_t)); if (fread (lm->bgprob, sizeof (lmlog_t), lm->n_bgprob, lm->fp) != lm->n_bgprob) E_FATAL("fread(%s) failed\n", file); if (lm->byteswap) { for (i = 0; i < lm->n_bgprob; i++) SWAP_UINT32(lm->bgprob[i].l); } E_INFO("%8d bigram prob entries\n", lm->n_bgprob); } if (lm->n_tg > 0) { /* Trigram bowt table size */ lm->n_tgbowt = lm_fread_int32 (lm); if ((lm->n_tgbowt <= 0) || (lm->n_tgbowt > 65536)) E_FATAL("Bad trigram bowt table size: %d\n", lm->n_tgbowt); /* Allocate and read trigram bowt table */ lm->tgbowt = (lmlog_t *) ckd_calloc (lm->n_tgbowt, sizeof (lmlog_t)); if (fread (lm->tgbowt, sizeof (lmlog_t), lm->n_tgbowt, lm->fp) != lm->n_tgbowt) E_FATAL("fread(%s) failed\n", file); if (lm->byteswap) { for (i = 0; i < lm->n_tgbowt; i++) SWAP_UINT32(lm->tgbowt[i].l); } E_INFO("%8d trigram bowt entries\n", lm->n_tgbowt); /* Trigram prob table size */ lm->n_tgprob = lm_fread_int32 (lm); if ((lm->n_tgprob <= 0) || (lm->n_tgprob > 65536)) E_FATAL("Bad trigram bowt table size: %d\n", lm->n_tgprob); /* Allocate and read trigram bowt table */ lm->tgprob = (lmlog_t *) ckd_calloc (lm->n_tgprob, sizeof (lmlog_t)); if (fread (lm->tgprob, sizeof (lmlog_t), lm->n_tgprob, lm->fp) != lm->n_tgprob) E_FATAL("fread(%s) failed\n", file); if (lm->byteswap) { for (i = 0; i < lm->n_tgprob; i++) SWAP_UINT32(lm->tgprob[i].l); } E_INFO("%8d trigram prob entries\n", lm->n_tgprob); /* Trigram seg table size */ k = lm_fread_int32 (lm); if (k != (lm->n_bg+1)/BG_SEG_SZ+1) E_FATAL("Bad trigram seg table size: %d\n", k); /* Allocate and read trigram seg table */ lm->tg_segbase = (int32 *) ckd_calloc (k, sizeof(int32)); if (fread (lm->tg_segbase, sizeof(int32), k, lm->fp) != k) E_FATAL("fread(%s) failed\n", file); if (lm->byteswap) { for (i = 0; i < k; i++) SWAP_UINT32(lm->tg_segbase[i]); } E_INFO("%8d trigram segtable entries\n", k); } /* Read word string names */ k = lm_fread_int32 (lm); if (k <= 0) E_FATAL("Bad wordstrings size: %d\n", k); tmp_word_str = (char *) ckd_calloc (k, sizeof (char)); if (fread (tmp_word_str, sizeof(char), k, lm->fp) != k) E_FATAL("fread(%s) failed\n", file); /* First make sure string just read contains ucount words (PARANOIA!!) */ for (i = 0, j = 0; i < k; i++) if (tmp_word_str[i] == '\0') j++; if (j != lm->n_ug) E_FATAL("Bad #words: %d\n", j); /* Break up string just read into words */ lm->startwid = lm->endwid = -1; lm->wordstr = (char **) ckd_calloc (lm->n_ug, sizeof(char *)); j = 0; notindict = 0; for (i = 0; i < lm->n_ug; i++) { #if (! NO_DICT) lm->ug[i].dictwid = dict_wordid (tmp_word_str+j); #else lm->ug[i].dictwid = i; #endif if (IS_WID(lm->ug[i].dictwid)) lm->dict2lmwid[lm->ug[i].dictwid] = i; else notindict++; if (strcmp (tmp_word_str+j, START_WORD) == 0) lm->startwid = i; else if (strcmp (tmp_word_str+j, FINISH_WORD) == 0) lm->endwid = i; lm->wordstr[i] = (char *) ckd_salloc (tmp_word_str+j); j += strlen(tmp_word_str+j) + 1; } free (tmp_word_str); E_INFO("%8d word strings\n", i); if (notindict > 0) E_INFO("%d LM words not in dict; ignored\n", notindict); /* Force bowt(</s>) = MIN_PROB_F */ lm->ug[lm->endwid].bowt.f = MIN_PROB_F; /* Force ugprob(<s>) = MIN_PROB_F */ lm->ug[lm->startwid].prob.f = MIN_PROB_F; return (0); } int32 lm_read (char *file, float64 lw, float64 uw, float64 wip) { int32 i, dictsize; lm_t *lm; E_INFO ("Reading %s, lw %.3f, uw %.3f, wip %.3f\n", file, lw, uw, wip); #if (! NO_DICT) dictsize = dict_size (); #else dictsize = MAX_UG; #endif lm->dict2lmwid = (s3lmwid_t *) ckd_calloc (dictsize, sizeof(s3lmwid_t)); for (i = 0; i < dictsize; i++) lm->dict2lmwid[i] = BAD_LMWID; /* For now, only dump files can be read */ lm = lm_read_dump (file, lw, uw, wip); lm_set_param (lm, lw, uw, wip); return lm; } main (int32 argc, char *argv[]) { char line[4096]; int32 score, k; if (argc < 2) E_FATAL("Usage: %s <LMdumpfile>\n", argv[0]); lm_read (argv[1], "", 9.5, 0.5, 0.65); for (;;) { printf ("> "); if (fgets (line, sizeof(line), stdin) == NULL) break; score = sentence_lmscore (line); k = strlen(line); if (line[k-1] == '\n') line[k-1] = '\0'; printf ("LMScr(%s) = %d\n", line, score); } } #endif <file_sep>/archive_s3/s3.2/src/fillpen.h /* * fillpen.c -- Filler penalties (penalties for words that do not show up in * the main LM. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 11-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #ifndef _S3_FILLPEN_H_ #define _S3_FILLPEN_H_ #include <libutil/libutil.h> #include "dict.h" typedef struct { dict_t *dict; /* Reference dictionary for which the filler word probabilities are maintained in this structure */ int32 *prob; /* Filler word probability (in logs3 space, after langwt and inspen application) */ float64 lw; /* Language weight */ float64 wip; /* Word insertion penalty */ } fillpen_t; /* * Initialize filler probabilities (penalties, whatever) module and return a pointer to the * structure created. Filler word probabilities are simple unigram probabilities. Here is an * example of such a file (one entry per line; a word and a probability): * <sil> 0.10792 * <uh> 0.00866 * <um> 0.00147 * If the first character in a line is a '#', the line is treated as a comment and ignored. * If no filler probabilities file is provided, the silence word gets silprob, and all other * filler words get fillprob. As with the trigram LM, the resulting log-probabilities are * multiplied by a language weight and finally a word insertion penalty is tacked on. */ fillpen_t *fillpen_init (dict_t *dict, /* In: Dictionary containing filler words */ char *file, /* In: Filler word probabilities file, if any */ float64 silprob, /* In: Default probability for silence word */ float64 fillprob, /* In: Default probability for non-silence filler words */ float64 lw, /* In: Language weight (see lm.h) */ float64 wip); /* In: Word insertion penalty (see lm.h) */ /* * Return the filler word probability for the given dictionary word-ID. */ int32 fillpen (fillpen_t *f, /* In: Filler word probabilities structure */ s3wid_t w); /* In: Dictionary word-ID of filler word */ #endif <file_sep>/tools/riddler/dotNet/RiddlerTest.cs namespace edu.cmu.sphinx.riddler { using System; using NUnit.Framework; using System.Collections.Generic; internal class EntryComparer : IEqualityComparer<metadataWrapperEntry> { #region IEqualityComparer<metadataWrapperEntry> Members public bool Equals(metadataWrapperEntry x, metadataWrapperEntry y) { return x.key.Equals(y.key) && x.value.Equals(y.value); } public int GetHashCode(metadataWrapperEntry obj) { return obj.key.GetHashCode() * obj.value.GetHashCode(); } #endregion } /// <summary>NUnit test suite for Sphinx Riddler web services</summary> /// [TestFixture] public class RiddlerTest { RiddlerBeanService riddler; /// <summary> /// /// </summary> [SetUp] public void Init() { riddler = new RiddlerBeanService(); } /// <summary> /// /// </summary> /// [Test] public void CreateAndFetchDictionaryAndMetadata() { metadataWrapper mdw = new metadataWrapper(); metadataWrapperEntry datum = new metadataWrapperEntry(); datum.key = "SomeKey"; datum.value = "SomeValue"; metadataWrapperEntry datum2 = new metadataWrapperEntry(); datum2.key = "AnotherKey"; datum2.value = "AnotherValue"; mdw.contents = new metadataWrapperEntry[] { datum, datum2 }; string dictId = riddler.createDictionary(mdw); string retrieved = riddler.getDictionary(mdw); Assert.AreEqual(dictId, retrieved); metadataWrapper mdwRetrieved = riddler.getDictionaryMetadata(dictId); // annoyance-- have to use an IDictionary because we need to specify an equality comparator // (you don't get one for free from the stub impl of metadataWrapperEntry) IDictionary<metadataWrapperEntry, int> tmpDict = new Dictionary<metadataWrapperEntry, int>(new EntryComparer()); foreach (metadataWrapperEntry e in mdwRetrieved.contents) tmpDict.Add(new KeyValuePair<metadataWrapperEntry, int>(e, 42)); Assert.IsTrue(tmpDict.Contains(new KeyValuePair<metadataWrapperEntry, int>(datum, 42))); Assert.IsTrue(tmpDict.Contains(new KeyValuePair<metadataWrapperEntry, int>(datum2, 42))); } [Test] [ExpectedException(typeof(System.Web.Services.Protocols.SoapException))] public void FetchNonexistentDictionary() { metadataWrapper mdw = new metadataWrapper(); metadataWrapperEntry datum = new metadataWrapperEntry(); datum.key = "KeyX"; datum.value = "ValueY"; mdw.contents = new metadataWrapperEntry[] { datum }; riddler.getDictionary(mdw); } [Test] [ExpectedException(typeof(System.Web.Services.Protocols.SoapException))] public void FetchNonexistentDictionaryMetadata() { riddler.getDictionaryMetadata("nonexistent-dictionary-ID"); } [Test] [Ignore("ignored test")] public void IgnoredTest() { throw new Exception(); } } }<file_sep>/archive_s3/s3.2/src/beam.c /* * beam.c -- Various forms of pruning beam * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 09-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "beam.h" #include "logs3.h" beam_t *beam_init (float64 svq, float64 hmm, float64 ptr, float64 wd) { beam_t *beam; beam = (beam_t *) ckd_calloc (1, sizeof(beam_t)); beam->subvq = logs3 (svq); beam->hmm = logs3 (hmm); beam->ptrans = logs3 (ptr); beam->word = logs3 (wd); return beam; } <file_sep>/SphinxTrain/src/libs/libs2io/s2_read_map.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_map_read.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_read_map.h> #include <s3/ckd_alloc.h> #include <s3/acmod_set.h> #include <s3/s2_param.h> #include <s3/prim_type.h> #include <s3/s3.h> #include <string.h> #include <assert.h> #include <stdio.h> static int extract_state_class(char *str, uint32 *state_id, uint32 *tying_class) { char *tmp; tmp = strchr(str, '<'); if ( tmp == NULL ) { E_ERROR("expected '<' in %s\n", str); return S3_ERROR; } ++tmp; *state_id = atoi(tmp); tmp = strchr(tmp, '>'); if ( tmp == NULL ) { E_ERROR("expected '>' in %s\n", str); return S3_ERROR; } ++tmp; *tying_class = atoi(tmp); return S3_SUCCESS; } /* Converts the state map, smap, into a global one-to-one mapping from model states onto consecutive integers from 0 to some max */ int s2_convert_smap_to_global(acmod_set_t *acmod_set, uint32 **smap, uint32 **out_state_of, uint32 *cluster_size) { uint32 i; uint32 t; uint32 offset; uint32 n_ci = acmod_set_n_ci(acmod_set); uint32 n = acmod_set_n_multi(acmod_set) + n_ci; acmod_id_t b; acmod_id_t id; uint32 state; uint32 *state_of; uint32 ci_seno; offset = n_ci * (S2_N_STATE-1); E_INFO("|CI states| == %d\n", offset); /* convert the cluster_size matrix into an offset table */ for (i = 0; i < n_ci; i++) { t = cluster_size[i]; cluster_size[i] = offset; offset += t; E_INFO("|%s| == %d (%d)\n", acmod_set_id2name(acmod_set, i), t, offset); } cluster_size[i] = offset; /* total # of states */ state_of = ckd_calloc(offset, sizeof(uint32)); /* map the ci phones to unshared distribution */ for (id = 0; id < n_ci; id++) { for (state = 0; state < S2_N_STATE-1; state++) { ci_seno = id * (S2_N_STATE-1) + state; smap[id][state] = ci_seno; state_of[ci_seno] = state; } } /* use the ci phone offsets to convert ci phone relative mappings to a global one-to-one mapping onto consecutive integers from 0 to some max */ for (; id < n; id++) { for (state = 0; state < S2_N_STATE-1; state++) { if (smap[id][state] == TYING_NO_ID) { uint32 base_id; base_id = acmod_set_base_phone(acmod_set, id); E_WARN("%s<%d> is unmapped, approximating with CI state <%d>.\n", acmod_set_id2name(acmod_set, id), state, state); smap[id][state] = smap[base_id][state]; /* no state_of[] assignment need bee done since it was done above */ } else { b = acmod_set_base_phone(acmod_set, id); smap[id][state] += cluster_size[b]; state_of[ smap[id][state] ] = state; } } } *out_state_of = state_of; return S3_SUCCESS; } int s2_read_seno_mapping_file(uint32 **smap, uint32 *cluster_size, const char *seno_mapping_file, acmod_set_t *acmod_set) { char big_str[1024]; FILE *fp; acmod_id_t base; acmod_id_t left; acmod_id_t right; word_posn_t posn; acmod_id_t triacmod_id; uint32 state_id = 0; uint32 tying_class = 0; uint32 n_map = 0; fp = fopen(seno_mapping_file, "r"); if (fp == NULL) { E_WARN_SYSTEM("can't open senone mapping file %s", seno_mapping_file); return S3_ERROR; } /* read in the mapping for triphones */ while (fgets(big_str, 1024, fp) != NULL) { big_str[strlen(big_str)-1] = '\0'; acmod_set_s2_parse_triphone(acmod_set, &base, &left, &right, &posn, big_str); triacmod_id = acmod_set_tri2id(acmod_set, base, left, right, posn); assert(triacmod_id != NO_ACMOD); extract_state_class(big_str, &state_id, &tying_class); if (cluster_size[base] < tying_class) cluster_size[base] = tying_class; assert(state_id < S2_N_STATE-1); /* tying class in seno map file is 1 based, want zero based */ smap[triacmod_id][state_id] = tying_class-1; ++n_map; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.6 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.5 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.4 1995/10/09 15:08:24 eht * changed ckd_alloc interface to remove need for __FILE__, __LINE__ * arguments * * Revision 1.3 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.2 1995/09/07 19:31:16 eht * For unmapped CD states, approximate them with the corresponding * CI state. * * Revision 1.1 1995/05/22 19:19:38 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/lexicon.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: lexicon.h * * Traceability: * * Description: * * Author: * $Author$ *********************************************************************/ #ifndef LEXICON_H #define LEXICON_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/acmod_set.h> #include <s3/hash.h> #include <s3/prim_type.h> #include <s3/lts.h> typedef uint32 word_id_t; #define WORD_NO_ID (0xffffffff) typedef struct lex_entry_str { char *ortho; word_id_t word_id; char **phone; acmod_id_t *ci_acmod_id; uint32 phone_cnt; struct lex_entry_str *next; } lex_entry_t; typedef struct lexicon_s { /* lex_entry_t *entry; */ lex_entry_t *head; lex_entry_t *tail; uint32 entry_cnt; hash_t ht; lts_t *lts_rules; acmod_set_t *phone_set; } lexicon_t; lexicon_t *lexicon_new(void); lexicon_t * lexicon_read(lexicon_t *prior_lex, const char *lex_file_name, acmod_set_t *phone_set); lex_entry_t * lexicon_lookup(lexicon_t *lexicon, char *word); #ifdef __cplusplus } #endif #endif /* LEXICON_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2005/09/15 19:36:01 dhdfu * Add (as yet untested) support for letter-to-sound rules (from CMU * Flite) when constructing sentence HMMs in Baum-Welch. Currently only * rules for CMUdict exist. Of course this is not a substitute for * actually checking pronunciations... * * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.4 1996/07/29 16:40:50 eht * make a name more consise * * Revision 1.3 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.2 1995/09/08 19:13:52 eht * Updated to remove references to pset module and add references * to acmod_set module * * Revision 1.1 1995/08/15 13:44:14 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/wave2feat/fe_sigproc.c /* ==================================================================== * Copyright (c) 1996-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <s3/err.h> #include "fe.h" #include "fe_internal.h" #include "fe_warp.h" /* 31 Jan 00 mseltzer - changed rounding of filter edges to -not- use rint() function. 3 Dec 99 mseltzer - corrected inverse DCT-2 period is 1/NumFilts not 1/(2*NumFilts) added "beta" factor in summation - changed mel filter bank construction so that left,right,center freqs are rounded to DFT points before filter is constructed */ int32 fe_build_melfilters(melfb_t *MEL_FB) { int32 i, whichfilt, start_pt; float32 leftfr, centerfr, rightfr, fwidth, height, *filt_edge; float32 melmax, melmin, dmelbw, freq, dfreq, leftslope=0,rightslope=0; /*estimate filter coefficients*/ MEL_FB->filter_coeffs = (float32 **)fe_create_2d(MEL_FB->num_filters, MEL_FB->fft_size, sizeof(float32)); MEL_FB->left_apex = (float32 *) calloc(MEL_FB->num_filters,sizeof(float32)); MEL_FB->width = (int32 *) calloc(MEL_FB->num_filters,sizeof(int32)); if (MEL_FB->doublewide==ON) filt_edge = (float32 *) calloc(MEL_FB->num_filters+4,sizeof(float32)); else filt_edge = (float32 *) calloc(MEL_FB->num_filters+2,sizeof(float32)); if (MEL_FB->filter_coeffs==NULL || MEL_FB->left_apex==NULL || MEL_FB->width==NULL || filt_edge==NULL){ fprintf(stderr,"memory alloc failed in fe_build_mel_filters()\n...exiting\n"); exit(0); } dfreq = MEL_FB->sampling_rate/(float32)MEL_FB->fft_size; melmax = fe_mel(MEL_FB->upper_filt_freq); melmin = fe_mel(MEL_FB->lower_filt_freq); dmelbw = (melmax-melmin)/(MEL_FB->num_filters+1); if (MEL_FB->doublewide==ON){ melmin = melmin-dmelbw; melmax = melmax+dmelbw; if ((fe_melinv(melmin)<0) || (fe_melinv(melmax)>MEL_FB->sampling_rate/2)){ fprintf(stderr,"Out of Range: low filter edge = %f (%f)\n",fe_melinv(melmin),0.0); fprintf(stderr," high filter edge = %f (%f)\n",fe_melinv(melmax),MEL_FB->sampling_rate/2); fprintf(stderr,"exiting...\n"); exit(0); } } if (MEL_FB->doublewide==ON){ for (i=0;i<=MEL_FB->num_filters+3; ++i){ filt_edge[i] = fe_melinv(i*dmelbw + melmin); } } else { for (i=0;i<=MEL_FB->num_filters+1; ++i){ filt_edge[i] = fe_melinv(i*dmelbw + melmin); } } for (whichfilt=0;whichfilt<MEL_FB->num_filters; ++whichfilt) { /*line triangle edges up with nearest dft points... */ if (MEL_FB->doublewide==ON){ leftfr = (float32)((int32)((filt_edge[whichfilt]/dfreq)+0.5))*dfreq; centerfr = (float32)((int32)((filt_edge[whichfilt+2]/dfreq)+0.5))*dfreq; rightfr = (float32)((int32)((filt_edge[whichfilt+4]/dfreq)+0.5))*dfreq; }else{ leftfr = (float32)((int32)((filt_edge[whichfilt]/dfreq)+0.5))*dfreq; centerfr = (float32)((int32)((filt_edge[whichfilt+1]/dfreq)+0.5))*dfreq; rightfr = (float32)((int32)((filt_edge[whichfilt+2]/dfreq)+0.5))*dfreq; } MEL_FB->left_apex[whichfilt] = leftfr; fwidth = rightfr - leftfr; /* 2/fwidth for triangles of area 1 */ height = 2/(float32)fwidth; if (centerfr != leftfr) { leftslope = height/(centerfr-leftfr); } if (centerfr != rightfr) { rightslope = height/(centerfr-rightfr); } /* Round to the nearest integer instead of truncating and adding one, which breaks if the divide is already an integer */ start_pt = (int32)(leftfr/dfreq + 0.5); freq = (float32)start_pt*dfreq; i=0; while (freq<centerfr){ MEL_FB->filter_coeffs[whichfilt][i] = (freq-leftfr)*leftslope; freq += dfreq; i++; } /* If the two floats are equal, the leftslope computation above results in Inf, so we handle the case here. */ if (freq==centerfr){ MEL_FB->filter_coeffs[whichfilt][i] = height; freq += dfreq; i++; } while (freq<rightfr){ MEL_FB->filter_coeffs[whichfilt][i] = (freq-rightfr)*rightslope; freq += dfreq; i++; } MEL_FB->width[whichfilt] = i; } free(filt_edge); return(0); } int32 fe_compute_melcosine(melfb_t *MEL_FB) { float32 period, freq; int32 i,j; period = (float32)2*MEL_FB->num_filters; if ((MEL_FB->mel_cosine = (float32 **) fe_create_2d(MEL_FB->num_cepstra,MEL_FB->num_filters, sizeof(float32)))==NULL){ fprintf(stderr,"memory alloc failed in fe_compute_melcosine()\n...exiting\n"); exit(0); } for (i=0; i<MEL_FB->num_cepstra; i++) { freq = 2*(float32)M_PI*(float32)i/period; for (j=0;j< MEL_FB->num_filters;j++) MEL_FB->mel_cosine[i][j] = (float32)cos((float64)(freq*(j+0.5))); } return(0); } float32 fe_mel(float32 x) { float32 warped = fe_warp_unwarped_to_warped(x); return (float32)(2595.0 * log10(1.0 + warped / 700.0)); } float32 fe_melinv(float32 x) { float32 warped = (float32)(700.0 * (pow(10.0, x / 2595.0) - 1.0)); return fe_warp_warped_to_unwarped(warped); } /* adds 1/2-bit noise */ int32 fe_dither(int16 *buffer, int32 nsamps) { int32 i; for (i=0;i<nsamps;i++) buffer[i] += (short)((!(lrand48()%4))?1:0); return 0; } void fe_pre_emphasis(int16 const *in, float64 *out, int32 len, float32 factor, int16 prior) { int32 i; out[0] = (float64)in[0]-factor*(float64)prior; for (i=1; i<len;i++) { out[i] = (float64)in[i] - factor*(float64)in[i-1]; } } void fe_short_to_double(int16 const *in, float64 *out, int32 len) { int32 i; for (i=0;i<len;i++) out[i] = (float64)in[i]; } void fe_create_hamming(float64 *in, int32 in_len) { int i; if (in_len>1){ for (i=0; i<in_len; i++) in[i] = 0.54 - 0.46*cos(2*M_PI*i/((float64)in_len-1.0)); } return; } void fe_hamming_window(float64 *in, float64 *window, int32 in_len) { int i; if (in_len>1){ for (i=0; i<in_len; i++) in[i] *= window[i]; } return; } int32 fe_frame_to_fea(fe_t *FE, float64 *in, float64 *fea) { float64 *spec, *mfspec; int32 returnValue = FE_SUCCESS; if (FE->FB_TYPE == MEL_SCALE){ spec = (float64 *)calloc(FE->FFT_SIZE, sizeof(float64)); mfspec = (float64 *)calloc(FE->MEL_FB->num_filters, sizeof(float64)); if (spec==NULL || mfspec==NULL){ fprintf(stderr,"memory alloc failed in fe_frame_to_fea()\n...exiting\n"); exit(0); } fe_spec_magnitude(in, FE->FRAME_SIZE, spec, FE->FFT_SIZE); fe_mel_spec(FE, spec, mfspec); returnValue = fe_mel_cep(FE, mfspec, fea); free(spec); free(mfspec); } else { fprintf(stderr,"MEL SCALE IS CURRENTLY THE ONLY IMPLEMENTATION!\n"); exit(0); } return returnValue; } void fe_spec_magnitude(float64 const *data, int32 data_len, float64 *spec, int32 fftsize) { int32 j, wrap; float64 *fft; if (NULL == (fft = (float64 *) calloc(fftsize,sizeof(float64)))) { E_FATAL("memory alloc failed in fe_spec_magnitude()\n...exiting\n"); } wrap = (data_len < fftsize) ? data_len : fftsize; memcpy(fft, data, wrap*sizeof(float64)); if (data_len > fftsize) { /*aliasing */ E_WARN("Aliasing. Consider using fft size (%d) > buffer size (%d)\n", fftsize, data_len); for (wrap = 0, j = fftsize; j < data_len; wrap++,j++) fft[wrap] += data[j]; } fe_fft_real(fft, fftsize); /* zero is a special case. */ spec[0] = fft[0]*fft[0]; for (j=1; j <= fftsize/2; j++) spec[j] = fft[j]*fft[j] + fft[fftsize-j]*fft[fftsize-j]; free(fft); return; } void fe_mel_spec(fe_t *FE, float64 const *spec, float64 *mfspec) { int32 whichfilt, start, i; float32 dfreq; dfreq = FE->SAMPLING_RATE/(float32)FE->FFT_SIZE; for (whichfilt = 0; whichfilt<FE->MEL_FB->num_filters; whichfilt++){ /* Round to the nearest integer instead of truncating and adding one, which breaks if the divide is already an integer */ start = (int32)(FE->MEL_FB->left_apex[whichfilt]/dfreq + 0.5); mfspec[whichfilt] = 0; for (i=0; i< FE->MEL_FB->width[whichfilt]; i++) mfspec[whichfilt] += FE->MEL_FB->filter_coeffs[whichfilt][i]*spec[start+i]; } } int32 fe_mel_cep(fe_t *FE, float64 *mfspec, float64 *mfcep) { int32 i,j; int32 period; float32 beta; int32 returnValue = FE_SUCCESS; period = FE->MEL_FB->num_filters; for (i=0;i<FE->MEL_FB->num_filters; ++i) { if (mfspec[i]>0) mfspec[i] = log(mfspec[i]); else { mfspec[i] = -1.0e+5; returnValue = FE_ZERO_ENERGY_ERROR; } } if (FE->LOG_SPEC == OFF) { for (i=0; i< FE->NUM_CEPSTRA; ++i){ mfcep[i] = 0; for (j=0;j<FE->MEL_FB->num_filters; j++){ if (j==0) beta = 0.5; else beta = 1.0; mfcep[i] += beta*mfspec[j]*FE->MEL_FB->mel_cosine[i][j]; } mfcep[i] /= (float32)period; } } else { for (i = 0; i < FE->FEATURE_DIMENSION; i++) { mfcep[i] = mfspec[i]; } } return returnValue; } /* This function has been replaced by fe_fft_real, and is no longer used. */ int32 fe_fft(complex const *in, complex *out, int32 N, int32 invert) { int32 s, k, /* as above */ lgN; /* log2(N) */ complex *f1, *f2, /* pointers into from array */ *t1, *t2, /* pointers into to array */ *ww; /* pointer into w array */ complex *w, *from, *to, /* as above */ wwf2, /* temporary for ww*f2 */ *buffer, /* from and to flipflop btw out and buffer */ *exch, /* temporary for exchanging from and to */ *wEnd; /* to keep ww from going off end */ float64 div, /* amount to divide result by: N or 1 */ x; /* misc. */ /* check N, compute lgN */ for (k = N, lgN = 0; k > 1; k /= 2, lgN++) { if (k%2 != 0 || N < 0) { fprintf(stderr, "fft: N must be a power of 2 (is %d)\n", N); return(-1); } } /* check invert, compute div */ if (invert == 1) div = 1.0; else if (invert == -1) div = N; else { fprintf(stderr, "fft: invert must be either +1 or -1 (is %d)\n", invert); return(-1); } /* get the to, from buffers right, and init */ buffer = (complex *)calloc(N, sizeof(complex)); if (lgN%2 == 0) { from = out; to = buffer; } else { to = out; from = buffer; } for (s = 0; s<N; s++) { from[s].r = in[s].r/div; from[s].i = in[s].i/div; } /* w = exp(-2*PI*i/N), w[k] = w^k */ w = (complex *) calloc(N/2, sizeof(complex)); for (k = 0; k < N/2; k++) { x = -6.28318530717958647*invert*k/N; w[k].r = cos(x); w[k].i = sin(x); } wEnd = &w[N/2]; /* go for it! */ for (k = N/2; k > 0; k /= 2) { for (s = 0; s < k; s++) { /* initialize pointers */ f1 = &from[s]; f2 = &from[s+k]; t1 = &to[s]; t2 = &to[s+N/2]; ww = &w[0]; /* compute <s,k> */ while (ww < wEnd) { /* wwf2 = ww*f2 */ wwf2.r = f2->r*ww->r - f2->i*ww->i; wwf2.i = f2->r*ww->i + f2->i*ww->r; /* t1 = f1+wwf2 */ t1->r = f1->r + wwf2.r; t1->i = f1->i + wwf2.i; /* t2 = f1-wwf2 */ t2->r = f1->r - wwf2.r; t2->i = f1->i - wwf2.i; /* increment */ f1 += 2*k; f2 += 2*k; t1 += k; t2 += k; ww += k; } } exch = from; from = to; to = exch; } free(buffer); free(w); return(0); } /* Translated from the FORTRAN (obviously) from "Real-Valued Fast * Fourier Transform Algorithms" by <NAME> et al., IEEE * Transactions on Acoustics, Speech, and Signal Processing, vol. 35, * no.6. Optimized to use a static array of sine/cosines. */ int32 fe_fft_real(float64 *x, int n) { int32 i, j, k, n1, n2, n4, i1, i2, i3, i4; float64 t1, t2, xt, cc, ss; static float64 *ccc = NULL, *sss = NULL; static int32 lastn = 0; int m; /* check fft size, compute fft order (log_2(n)) */ for (k = n, m = 0; k > 1; k >>= 1, m++) { if (((k % 2) != 0) || (n <= 0)) { E_FATAL("fft: number of points must be a power of 2 (is %d)\n", n); } } if (ccc == NULL || n != lastn) { if (ccc != NULL) { free(ccc); } if (sss != NULL) { free(sss); } ccc = calloc(n/4, sizeof(*ccc)); sss = calloc(n/4, sizeof(*sss)); for (i = 0; i < n/4; ++i) { float64 a; a = 2*M_PI*i/n; ccc[i] = cos(a); sss[i] = sin(a); } lastn = n; } j = 0; n1 = n-1; for (i = 0; i < n1; ++i) { if (i < j) { xt = x[j]; x[j] = x[i]; x[i] = xt; } k = n/2; while (k <= j) { j -= k; k /= 2; } j += k; } for (i = 0; i < n; i += 2) { xt = x[i]; x[i] = xt + x[i+1]; x[i+1] = xt - x[i+1]; } n2 = 0; for (k = 1; k < m; ++k) { n4 = n2; n2 = n4+1; n1 = n2+1; for (i = 0; i < n; i += (1<<n1)) { xt = x[i]; x[i] = xt + x[i+(1<<n2)]; x[i+(1<<n2)] = xt - x[i+(1<<n2)]; x[i+(1<<n4)+(1<<n2)] = -x[i+(1<<n4)+(1<<n2)]; for (j = 1; j < (1<<n4); ++j) { i1 = i + j; i2 = i - j + (1<<n2); i3 = i + j + (1<<n2); i4 = i - j + (1<<n1); /* a = 2*M_PI * j / n1; */ /* cc = cos(a); ss = sin(a); */ cc = ccc[j<<(m-n1)]; ss = sss[j<<(m-n1)]; t1 = x[i3] * cc + x[i4] * ss; t2 = x[i3] * ss - x[i4] * cc; x[i4] = x[i2] - t2; x[i3] = -x[i2] - t2; x[i2] = x[i1] - t1; x[i1] = x[i1] + t1; } } } return 0; } char **fe_create_2d(int32 d1, int32 d2, int32 elem_size) { char *store; char **out; int32 i, j; store = calloc(d1 * d2, elem_size); if (store == NULL) { fprintf(stderr,"fe_create_2d failed\n"); return(NULL); } out = calloc(d1, sizeof(void *)); if (out == NULL) { fprintf(stderr,"fe_create_2d failed\n"); free(store); return(NULL); } for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &((char *)store)[j*elem_size]; } return out; } void fe_free_2d(void **arr) { if (arr!=NULL){ free(arr[0]); free(arr); } } void fe_parse_general_params(param_t const *P, fe_t *FE) { if (P->SAMPLING_RATE != 0) FE->SAMPLING_RATE = P->SAMPLING_RATE; else FE->SAMPLING_RATE = (float32)atof(DEFAULT_SAMPLING_RATE); if (P->FRAME_RATE != 0) FE->FRAME_RATE = P->FRAME_RATE; else FE->FRAME_RATE = (int32)atoi(DEFAULT_FRAME_RATE); if (P->WINDOW_LENGTH != 0) FE->WINDOW_LENGTH = P->WINDOW_LENGTH; else FE->WINDOW_LENGTH = (float32)atof(DEFAULT_WINDOW_LENGTH); if (P->FB_TYPE != 0) FE->FB_TYPE = P->FB_TYPE; else FE->FB_TYPE = DEFAULT_FB_TYPE; FE->dither = P->dither; FE->seed = P->seed; if (P->PRE_EMPHASIS_ALPHA != 0) FE->PRE_EMPHASIS_ALPHA = P->PRE_EMPHASIS_ALPHA; else FE->PRE_EMPHASIS_ALPHA = (float32)atof(DEFAULT_PRE_EMPHASIS_ALPHA); if (P->NUM_CEPSTRA != 0) FE->NUM_CEPSTRA = P->NUM_CEPSTRA; else FE->NUM_CEPSTRA = atoi(DEFAULT_NUM_CEPSTRA); if (P->FFT_SIZE != 0) FE->FFT_SIZE = P->FFT_SIZE; else FE->FFT_SIZE = atoi(DEFAULT_FFT_SIZE); FE->LOG_SPEC = P->logspec; if (FE->LOG_SPEC == OFF) FE->FEATURE_DIMENSION = FE->NUM_CEPSTRA; else { if (P->NUM_FILTERS != 0) FE->FEATURE_DIMENSION = P->NUM_FILTERS; else { if (FE->SAMPLING_RATE == BB_SAMPLING_RATE) FE->FEATURE_DIMENSION = DEFAULT_BB_NUM_FILTERS; else if (FE->SAMPLING_RATE == NB_SAMPLING_RATE) FE->FEATURE_DIMENSION = DEFAULT_NB_NUM_FILTERS; else { E_FATAL("Please define the number of MEL filters needed\n"); } } } } void fe_parse_melfb_params(param_t const *P, melfb_t *MEL) { if (P->SAMPLING_RATE != 0) MEL->sampling_rate = P->SAMPLING_RATE; else MEL->sampling_rate = (float32)atof(DEFAULT_SAMPLING_RATE); if (P->FFT_SIZE != 0) MEL->fft_size = P->FFT_SIZE; else { if (MEL->sampling_rate == BB_SAMPLING_RATE) MEL->fft_size = DEFAULT_BB_FFT_SIZE; if (MEL->sampling_rate == NB_SAMPLING_RATE) MEL->fft_size = DEFAULT_NB_FFT_SIZE; else MEL->fft_size = atoi(DEFAULT_FFT_SIZE); } if (P->NUM_CEPSTRA != 0) MEL->num_cepstra = P->NUM_CEPSTRA; else MEL->num_cepstra = atoi(DEFAULT_NUM_CEPSTRA); if (P->NUM_FILTERS != 0) MEL->num_filters = P->NUM_FILTERS; else { if (MEL->sampling_rate == BB_SAMPLING_RATE) MEL->num_filters = DEFAULT_BB_NUM_FILTERS; else if (MEL->sampling_rate == NB_SAMPLING_RATE) MEL->num_filters = DEFAULT_NB_NUM_FILTERS; else { E_FATAL("Default value not defined for this sampling rate\nPlease explicitly set -nfilt\n"); } } if (P->UPPER_FILT_FREQ != 0) MEL->upper_filt_freq = P->UPPER_FILT_FREQ; else{ if (MEL->sampling_rate == BB_SAMPLING_RATE) MEL->upper_filt_freq = (float32) DEFAULT_BB_UPPER_FILT_FREQ; else if (MEL->sampling_rate == NB_SAMPLING_RATE) MEL->upper_filt_freq = (float32) DEFAULT_NB_UPPER_FILT_FREQ; else { E_FATAL("Default value not defined for this sampling rate\nPlease explicitly set -upperf\n"); } } if (P->LOWER_FILT_FREQ != 0) MEL->lower_filt_freq = P->LOWER_FILT_FREQ; else { if (MEL->sampling_rate == BB_SAMPLING_RATE) MEL->lower_filt_freq = (float32) DEFAULT_BB_LOWER_FILT_FREQ; else if (MEL->sampling_rate == NB_SAMPLING_RATE) MEL->lower_filt_freq = (float32) DEFAULT_NB_LOWER_FILT_FREQ; else { E_FATAL("Default value not defined for this sampling rate\nPlease explictly set -lowerf\n"); } } if (P->doublebw == ON) MEL->doublewide = ON; else MEL->doublewide = OFF; if (P->warp_type == NULL) { MEL->warp_type = DEFAULT_WARP_TYPE; } else { MEL->warp_type = P->warp_type; } MEL->warp_params = P->warp_params; if (fe_warp_set(MEL->warp_type) != FE_SUCCESS) { E_FATAL("Failed to initialize the warping function.\n"); } fe_warp_set_parameters(MEL->warp_params, MEL->sampling_rate); } void fe_print_current(fe_t const *FE) { E_INFO("Current FE Parameters:\n"); E_INFO("\tSampling Rate: %f\n", FE->SAMPLING_RATE); E_INFO("\tFrame Size: %d\n", FE->FRAME_SIZE); E_INFO("\tFrame Shift: %d\n", FE->FRAME_SHIFT); E_INFO("\tFFT Size: %d\n", FE->FFT_SIZE); E_INFO("\tLower Frequency: %g\n", FE->MEL_FB->lower_filt_freq); E_INFO("\tUpper Frequency: %g\n", FE->MEL_FB->upper_filt_freq); E_INFO("\tNumber of filters: %d\n", FE->MEL_FB->num_filters); E_INFO("\tNumber of Overflow Samps: %d\n", FE->NUM_OVERFLOW_SAMPS); E_INFO("\tStart Utt Status: %d\n", FE->START_FLAG); if (FE->dither) { E_INFO("Will add dither to audio\n"); E_INFO("Dither seeded with %d\n", FE->seed); } else { E_INFO("Will not add dither to audio\n"); } if (FE->MEL_FB->doublewide == ON) { E_INFO("Will use double bandwidth in mel filter\n"); } else { E_INFO("Will not use double bandwidth in mel filter\n"); } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.22 2006/02/25 00:53:48 egouvea * Added the flag "-seed". If dither is being used and the seed is less * than zero, the random number generator is initialized with time(). If * it is at least zero, it's initialized with the provided seed. This way * we have the benefit of having dither, and the benefit of being * repeatable. * * This is consistent with what sphinx3 does. Well, almost. The random * number generator is still what the compiler provides. * * Also, moved fe_init_params to fe_interface.c, so one can initialize a * variable of type param_t with meaningful values. * * Revision 1.21 2006/02/20 23:55:51 egouvea * Moved fe_dither() to the "library" side rather than the app side, so * the function can be code when using the front end as a library. * * Revision 1.20 2006/02/17 17:26:58 egouvea * warp_type was not being initialized in the library, but by the app. * * Revision 1.19 2006/02/17 00:31:34 egouvea * Removed switch -melwarp. Changed the default for window length to * 0.025625 from 0.256 (so that a window at 16kHz sampling rate has * exactly 410 samples). Cleaned up include's. Replaced some E_FATAL() * with E_WARN() and return. * * Revision 1.18 2006/02/16 17:07:03 egouvea * Removed unused file from Makefile, initialized leftslope, rightslope to make compiler happy * * Revision 1.17 2006/02/16 00:18:26 egouvea * Implemented flexible warping function. The user can specify at run * time which of several shapes they want to use. Currently implemented * are an affine function (y = ax + b), an inverse linear (y = a/x) and a * piecewise linear (y = ax, up to a frequency F, and then it "breaks" so * Nyquist frequency matches in both scales. * * Added two switches, -warp_type and -warp_params. The first specifies * the type, which valid values: * * -inverse or inverse_linear * -linear or affine * -piecewise or piecewise_linear * * The inverse_linear is the same as implemented by EHT. The -mel_warp * switch was kept for compatibility (maybe remove it in the * future?). The code is compatible with EHT's changes: cepstra created * from code after his changes should be the same as now. Scripts that * worked with his changes should work now without changes. Tested a few * cases, same results. * */ <file_sep>/SphinxTrain/src/programs/mixw_interp/cmd_ln_defn.h /* ==================================================================== * Copyright (c) 1998-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln_defn.h * * Description: * Command line definitions for bw * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef CMD_LN_DEFN_H #define CMD_LN_DEFN_H const char helpstr[] = "Description: \n\ \n\ A routine that provides and ad-hoc way of speaker adaptation by mixture \n\ weight interpolation. SD and SI model's mixture weight are first \n\ determined and they act as an inputs of this program. The output \n\ is the interpolated mixture weight. \n\ \n\ The interpolation is controlled by the value lambda (-sillambda) "; const char examplestr[]= "Example: \n\ \n\ mixw_interp -SImixwfn si_mixw -SDmixwfn sd_mxiw -outmixwfn final_mixw -SIlambad 0.7"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-SImixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The SI mixture weight parameter file name"}, { "-SDmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The SD mixture weight parameter file name"}, { "-outmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output interpolated mixture weight parameter file name"}, { "-SIlambda", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.5", "Weight given to SI mixing weights" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; #endif /* CMD_LN_DEFN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/08/10 21:58:51 arthchan2003 * Incorporate help and example for the four final tools * * Revision 1.4 2004/07/21 18:30:35 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * */ <file_sep>/SphinxTrain/README.txt This is SphinxTrain, Carnegie Mellon University's open source acoustic model trainer. This directory contains the scripts and instructions necessary for building models for the CMU Sphinx Recognizer. This distribution is free software, see COPYING for licence. For up-to-date information, please see the web site at http://cmusphinx.org Among the interesting resources there, you will find a link to "Resources to build a recognition system", with pointers to a dictionary, audio data, acoustic model etc. For the initial setup, please take a look at doc/tinydoc.txt. These scripts and programs have been tested for building Sphinx-2, Sphinx-3, and Sphinx-4 acoustic models. Additional information can be found in the web page above, and also at: http://www.speech.cs.cmu.edu/sphinxman/scriptman1.html Looking at doc/tinydoc.txt will only make you *think* you know what's going on. Installation Guide: ^^^^^^^^^^^^^^^^^^^ This sections contain installation guide for various platforms. All Platforms: ^^^^^^^^^^^^^^ You will need Perl to use the scripts provided. Linux usually comes with some version of Perl. If you do not have Perl installed, please check: http://www.perl.org where you can download it for free. For Windows, a popular version, ActivePerl, is available from ActiveState at: http://www.activestate.com/Products/ActivePerl/ For some advanced techniques (which are not enabled by default) you will need Python with NumPy and SciPy. Python can be obtained from: http://www.python.org/download/ Packages for NumPy and SciPy can be obtained from: http://scipy.org/Download Linux/Unix Installation: ^^^^^^^^^^^^^^^^^^^^^^^^ This distribution now uses GNU autoconf to find out basic information about your system, and should compile on most Unix and Unix-like systems, and certainly on Linux. To build, simply run ./configure make (Or whatever you call GNU Make). This should configure everything automatically. The code has been tested with gcc. Also, check the section title "All Platforms" above. Windows Installation: ^^^^^^^^^^^^^^^^^^^^^ To compile SphinxTrain in Visual C++ 6.0, 1, uncompress the file (e.g. using WinZip) and save it to the disk. 2, click SphinxTrain.dsw. 3, build all projects; each of them is a tool used by the training script. Step 3 can be done easily in VC6.0 by clicking the "Build" menu at the top bar, and selecting "Batch Build...". Make sure all projects are selected, preferably the "Release" version of each. You can also run with the "Debug" version, but this version is usually slower. If you are using cygwin, the installation procedure is very similar to the Unix installation. Also, check the section title "All Platforms" above. Acknowldegments ^^^^^^^^^^^^^^^ This work was built over a large number of years at CMU by most of the people in the Sphinx Group. Some code goes back to 1986. The most recent work in tidying this up for release includes the following, listed alphabetically (at least these are the people who are most likely able to help you). <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> <NAME> (<EMAIL>) <NAME> <file_sep>/SphinxTrain/src/programs/mk_s2sendump/feat.h /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * feat.h -- Cepstral features computation. * * HISTORY * * 18-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added sf, ef parameters to s2mfc_read(). * * 10-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added feat_cepsize(). * * 09-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Moved constant declarations to feat.c. * * 04-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #ifndef _LIBFEAT_FEAT_H_ #define _LIBFEAT_FEAT_H_ /* * Structure for describing a speech feature type (no. of streams and stream widths), * as well as the computation for converting the input speech (e.g., Sphinx-II format * MFC cepstra) into this type of feature vectors. */ typedef struct feat_s { char *name; /* Printable name for this feature type */ int32 cepsize; /* Size of input speech vector (typically, a cepstrum vector) */ int32 cepsize_used; /* No. of cepstrum vector dimensions actually used (0 onwards) */ int32 n_stream; /* #Feature streams; e.g., 4 in Sphinx-II */ int32 *stream_len; /* Vector length of each feature stream */ int32 window_size; /* #Extra frames around given input frame needed to compute corresponding output feature (so total = window_size*2 + 1) */ void (*compute_feat)(struct feat_s *fcb, float32 **input, float32 **feat); /* Function for converting window of input speech vector (input[-window_size..window_size]) to output feature vector (feat[stream][]). If NULL, no conversion available, the speech input must be feature vector itself. Return value: 0 if successful, -ve otherwise. */ } feat_t; /* Access macros */ #define feat_name(f) ((f)->name) #define feat_cepsize(f) ((f)->cepsize) #define feat_cepsize_used(f) ((f)->cepsize_used) #define feat_n_stream(f) ((f)->n_stream) #define feat_stream_len(f,i) ((f)->stream_len[i]) #define feat_window_size(f) ((f)->window_size) /* * Read feature vectors from the given file. Feature file format: * Line containing the single word: s3 * File header including any argument value pairs/line and other text (e.g., * 'chksum0 yes', 'version 1.0', as in other S3 format binary files) * Header ended by line containing the single word: endhdr * (int32) Byte-order magic number (0x11223344) * (int32) No. of frames in file (N) * (int32) No. of feature streams (S) * (int32 x S) Width or dimensionality of each feature stream (sum = L) * (float32) Feature vector data (NxL float32 items). * (uint32) Checksum (if present). * (Note that this routine does NOT verify the checksum.) * Return value: # frames read if successful, -1 if error. */ int32 feat_readfile (feat_t *fcb, /* In: Control block from feat_init() */ char *file, /* In: File to read */ int32 sf, /* In: Start/end frames (range) to be read from file; use 0, 0x7ffffff0 to read entire file */ int32 ef, float32 ***feat, /* Out: Data structure to be filled with read data; allocate using feat_array_alloc() */ int32 maxfr); /* In: #Frames allocated for feat above; error if attempt to read more than this amount. */ /* * Counterpart to feat_readfile. Feature data is assumed to be in a contiguous block * starting from feat[0][0][0]. (NOTE: No checksum is written.) * Return value: # frames read, including padding, if successful, -1 if error. */ int32 feat_writefile (feat_t *fcb, /* In: Control block from feat_init() */ char *file, /* In: File to write */ float32 ***feat, /* In: Feature data to be written */ int32 nfr); /* In: #Frames to be written */ /* * Read Sphinx-II format mfc file (s2mfc = Sphinx-II format MFC data). * Return value: #frames read, including padding, if successful, -1 if error (e.g., * mfc array too small). */ int32 s2mfc_read (char *file, /* In: Sphinx-II format MFC file to be read */ int32 sf, int32 ef, /* In: Start/end frames (range) to be read from file. If ef is -ve, read until EOF. */ int32 featpad, /* In: #Frames of extra MFC data needed to be padded at either end, to compute features */ float32 **mfc, /* Out: 2-D array to be filled with MFC data, including padding (featpad, above). */ int32 maxfr); /* In: #Frames of mfc array allocated; error if attempt to read more than this amount. */ /* * Allocate an array to hold several frames worth of feature vectors. The returned value * is the float32 ***data array, organized as follows: * data[0][0] = frame 0 stream 0 vector, data[0][1] = frame 0 stream 1 vector, ... * data[1][0] = frame 1 stream 0 vector, data[0][1] = frame 1 stream 1 vector, ... * data[2][0] = frame 2 stream 0 vector, data[0][1] = frame 2 stream 1 vector, ... * ... * NOTE: For I/O convenience, the entire data area is allocated as one contiguous block. * Return value: Pointer to the allocated space if successful, NULL if any error. */ float32 ***feat_array_alloc (feat_t *fcb, /* In: Descriptor from feat_init(), used to obtain #streams and stream sizes */ int32 nfr); /* In: #Frames for which to allocate */ /* * Like feat_array_alloc except that only a single frame is allocated. Hence, one * dimension less. */ float32 **feat_vector_alloc (feat_t *fcb); /* In: Descriptor from feat_init(), used to obtain #streams and stream sizes */ /* * Initialize feature module to use the selected type of feature stream. One-time only * initialization at the beginning of the program. Input type is a string defining the * kind of input->feature conversion desired: * "s2_4x": s2mfc->Sphinx-II 4-feature stream, * "s3_1x39": s2mfc->Sphinx-3 single feature stream, * "n1,n2,n3,...": Explicit feature vector layout spec. with comma-separated feature * stream lengths. In this case, the input data is already in the feature format * and there is no conversion necessary. * Return value: (feat_t *) descriptor if successful, NULL if error. Caller must not * directly modify the contents of the returned value. */ feat_t *feat_init (char *type); /* In: type of feature stream */ #endif <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/SwitchableMoveStratgy.java package edu.cmu.sphinx.tools.confdesigner; import org.netbeans.api.visual.action.ActionFactory; import org.netbeans.api.visual.action.MoveStrategy; import org.netbeans.api.visual.widget.Widget; import java.awt.*; /** * Implements a proxy which can be switch between grid-strategy and free-move strategy. * * @author <NAME> */ public class SwitchableMoveStratgy implements MoveStrategy { private MoveStrategy gridStrategy; private MoveStrategy freeMoveStrategy; private boolean useGridStrategy; public SwitchableMoveStratgy() { gridStrategy = ActionFactory.createSnapToGridMoveStrategy(20, 20); freeMoveStrategy = ActionFactory.createFreeMoveStrategy(); } public Point locationSuggested(Widget widget, Point point, Point point1) { if (useGridStrategy) { return gridStrategy.locationSuggested(widget, point, point1); } else { return freeMoveStrategy.locationSuggested(widget, point, point1); } } public boolean isUseGridStrategy() { return useGridStrategy; } public void setUseGridStrategy(boolean useGridStrategy) { this.useGridStrategy = useGridStrategy; } } <file_sep>/tools/confdesigner/build.xml <project name="confdesinger" default="makejar" basedir="."> <property name="prj.name" value="confdesigner"/> <property name="version" value="1.0b1"/> <property name="src.dir" location="${basedir}/src"/> <property name="classes.dir" location="${basedir}/classes"/> <property name="lib.dir" value="${basedir}/lib"/> <property name="dist.dir" value="${basedir}/dist"/> <property name="bin.dir" value="${basedir}/bin"/> <property name="key-alias" value="http://techfak.uni-bielefeld.de/~hbrandl"/> <property name="keystore.location" value="${prj.name}.keys"/> <!-- this should be avoided ASAP :-) --> <property name="keystore.password" value="<PASSWORD>"/> <path id="classpath"> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> </path> <target name="compile" description="compile all sources"> <mkdir dir="${classes.dir}"/> <javac srcdir="${src.dir}" destdir="${classes.dir}" source="1.5"> <classpath refid="classpath"/> </javac> </target> <target name="makejar" depends="compile" description="packages the ${prj.name}.jar"> <jar basedir="${classes.dir}" manifest="${basedir}/misc/confdesigner.Manifest" destfile="${basedir}/${prj.name}.jar"/> <!--<jar basedir="${bin.dir}" includes="config.sxl,config.props" update="true" destfile="${prj.name}.jar"/>--> </target> <target name="deploy" depends="cleanall, makejar, createKeyfile" description="deploys the app to the dist-dir"> <!-- clean old distribution --> <delete dir="${dist.dir}" failonerror="true"/> <mkdir dir="${dist.dir}"/> <mkdir dir="${dist.dir}/lib"/> <!-- pack classes into jarfile --> <copy file="${basedir}/${prj.name}.jar" todir="${dist.dir}/lib"/> <copy file="${basedir}/misc/${prj.name}.jnlp" todir="${dist.dir}/lib"/> <!-- copy all needed jars to the deploy directory --> <copy todir="${dist.dir}/lib"> <fileset dir="${lib.dir}"> <include name="**/*.jar"/> </fileset> </copy> <!-- sign all jar to make browsers to ease webstart deployment --> <signjar alias="${key-alias}" keystore="${keystore.location}" storepass="${keystore.password}" lazy="true"> <path> <fileset dir="${dist.dir}/lib" includes="**/*.jar"/> </path> </signjar> <!-- zip sources and buildfile and copy them to the dist-dir --> <fileset dir="." id="allsrc"> <include name="src/**"/> </fileset> <zip destfile="${prj.name}-src_${version}.zip" basedir="."> <include name="build.xml"/> <include name="license.terms.xml"/> <include name="README"/> <fileset refid="allsrc"/> </zip> <!--<copy todir="${dist.dir}">--> <!--<fileset dir="${basedir}">--> <!--<include name="bin/*"/>--> <!--</fileset>--> <!--</copy>--> <!-- restore executable flags --> <!--<chmod file="${dist.dir}/bin/*.sh" perm="ugo+x"/>--> <!--now put all into a binary distribution --> <zip destfile="${prj.name}-bin_${version}.zip" basedir="."> <include name="build.xml"/> <include name="license.terms.xml"/> <include name="README"/> <include name="${dist.dir}/**"/> </zip> </target> <target name="createKeyfile"> <genkey alias="${key-alias}" keystore="${keystore.location}" storepass="${keystore.password}" validity="3650" dname="CN=<NAME>, OU=Applied Computer Science Group, O=Uni Bielefeld, C=DE"/> </target> <target name="cleanall" description="remove all generated files"> <delete failonerror="false" dir="${dist.dir}"/> <delete file="${basedir}/${prj.name}.jar"/> <delete dir="${classes.dir}" failonerror="false"/> </target> </project><file_sep>/SphinxTrain/src/libs/libs2io/s2_read_seno.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_read_seno.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_read_seno.h> #include <s3/s2_read_map.h> #include <s3/s2_param.h> #include <s3/model_inventory.h> #include <s3/common.h> #include <s3/s2io.h> #include <s3/s3.h> #include <math.h> #include <s2/log.h> #include <sys_compat/file.h> #include <stdio.h> static int read_seno_cluster(int32 **seno_cluster, const char *seno_dir, const char *base_name, const char **ext, uint32 n_weights) { unsigned int f; int n_read; char seno_filename[MAXPATHLEN]; E_INFO("reading mixing weights for %s\n", base_name); for (f = 0; f < S2_N_FEATURE; f++) { sprintf(seno_filename, "%s/%s.%s", seno_dir, base_name, ext[f]); areadint(seno_filename, &seno_cluster[f], &n_read); if (n_read != n_weights) { E_FATAL("expected %d weights in %s but got %d\n", n_weights, seno_filename, n_read); } } return S3_SUCCESS; } static void exp_norm_floor_mixw(float32 ***out, /* the mixture weight matrix for all shared states */ float32 weight_floor, /* smoothing floor for mixture weights */ int32 **in, /* mixture weights for states in a given CI phone */ uint32 ci_id, /* the CI phone associated with the input weights */ uint32 ci_only, /* Do CI initialization of non-CI mixture weights */ uint32 *cluster_offset, /* mixture weight array offsets */ uint32 *state_of) /* the model state associated with each senone. Used only * for CI initialization of CD weights. */ { uint32 cd_n_seno; /* # of context dependent senones */ uint32 s_out_org; /* the first weight id under this CI_ID in the output matrix */ uint32 s_out_next; /* the first weight id of the next ci in the output matrix */ uint32 s_out_ci_begin; /* the first CI weight of this CI_ID in the output matrix */ uint32 s_out_ci_next; /* the next CI weight after the last CI weight for this CI_ID */ uint32 s_in_ci_org; /* the first weight id of the ci weights in the input matrix */ uint32 f; /* a feature stream id */ uint32 s_in; /* a weight id in the input matrix */ uint32 s_out; /* a weight id in the output matrix */ uint32 cw; /* a codeword index */ s_out_org = cluster_offset[ci_id]; s_out_next = cluster_offset[ci_id+1]; if (!ci_only) cd_n_seno = s_out_next - s_out_org; else cd_n_seno = 0; s_in_ci_org = cd_n_seno; s_out_ci_begin = ci_id * (S2_N_STATE-1); s_out_ci_next = s_out_ci_begin + (S2_N_STATE-1); E_INFO("converting log(weights) to weights\n"); for (f = 0; f < S2_N_FEATURE; f++) { for (s_out = s_out_ci_begin, s_in = s_in_ci_org; s_out < s_out_ci_next; s_out++, s_in++) { printf("%d %d :\n", f, s_in); for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = EXP(in[f][s_in*S2_N_CODEWORD + cw]); printf("%f %.4e ", out[s_out][f][cw], EXP(in[f][s_in*S2_N_CODEWORD + cw])); } printf("\n"); vector_normalize(out[s_out][f], S2_N_CODEWORD); vector_floor(out[s_out][f], S2_N_CODEWORD, weight_floor); vector_normalize(out[s_out][f], S2_N_CODEWORD); } if (ci_only) { /* clone the CD mixture weights from the CI ones */ for (s_out = s_out_org; s_out < s_out_next; s_out++) { /* figure out which CI weights we need */ s_in = s_out_ci_begin + state_of[s_out]; for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = out[s_in][f][cw]; } } } else { for (s_out = s_out_org, s_in = 0; s_in < cd_n_seno; s_in++, s_out++) { for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = EXP(in[f][s_in * S2_N_CODEWORD + cw]); } vector_normalize(out[s_out][f], S2_N_CODEWORD); vector_floor(out[s_out][f], S2_N_CODEWORD, weight_floor); vector_normalize(out[s_out][f], S2_N_CODEWORD); } } } } static void exp_mixw(float32 ***out, /* the mixture weight matrix for all shared states */ int32 **in, /* mixture weights for states in a given CI phone */ uint32 ci_id, /* the CI phone associated with the input weights */ uint32 ci_only, /* Do CI initialization of non-CI mixture weights */ uint32 *cluster_offset,/* mixture weight array offsets */ uint32 *state_of) /* the model state associated with each senone. Used only * for CI initialization of CD weights. */ { uint32 cd_n_seno; /* # of context dependent senones */ uint32 s_out_org; /* the first weight id under this CI_ID in the output matrix */ uint32 s_out_next; /* the first weight id of the next ci in the output matrix */ uint32 s_out_ci_begin; /* the first CI weight of this CI_ID in the output matrix */ uint32 s_out_ci_next; /* the next CI weight after the last CI weight for this CI_ID */ uint32 s_in_ci_org; /* the first weight id of the ci weights in the input matrix */ uint32 f; /* a feature stream id */ uint32 s_in; /* a weight id in the input matrix */ uint32 s_out; /* a weight id in the output matrix */ uint32 cw; /* a codeword index */ s_out_org = cluster_offset[ci_id]; s_out_next = cluster_offset[ci_id+1]; if (!ci_only) cd_n_seno = s_out_next - s_out_org; else cd_n_seno = 0; s_in_ci_org = cd_n_seno; s_out_ci_begin = ci_id * (S2_N_STATE-1); s_out_ci_next = s_out_ci_begin + (S2_N_STATE-1); E_INFO("converting log(weights) to weights\n"); for (f = 0; f < S2_N_FEATURE; f++) { for (s_out = s_out_ci_begin, s_in = s_in_ci_org; s_out < s_out_ci_next; s_out++, s_in++) { printf("CI %d %u <- %u :\n", f, s_out, s_in); for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = EXP(in[f][s_in*S2_N_CODEWORD + cw]); } } if (ci_only) { /* clone the CD mixture weights from the CI ones */ for (s_out = s_out_org; s_out < s_out_next; s_out++) { /* figure out which CI weights we need */ s_in = s_out_ci_begin + state_of[s_out]; for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = out[s_in][f][cw]; } } } else { for (s_out = s_out_org, s_in = 0; s_in < cd_n_seno; s_in++, s_out++) { printf("CD %d %u <- %u :\n", f, s_out, s_in); for (cw = 0; cw < S2_N_CODEWORD; cw++) { out[s_out][f][cw] = EXP(in[f][s_in * S2_N_CODEWORD + cw]); } } } } } float32 *** s2_read_seno_3(acmod_set_t *acmod_set, /* the phone set of the model inventory */ uint32 *cluster_offset, /* number of senones before each base phone cluster */ const char *seno_dir, /* the directory containing the .ccode, .d2code, etc. files */ uint32 **in_smap, /* An initial global state sharing map */ float32 weight_floor, /* the least probability of the weights prior to renormalization */ uint32 *state_of) /* the model state id's for each shared state */ { float ***out; uint32 i, f; uint32 n_ci; int32 **in_seno; uint32 n_states; uint32 n_base_states; uint32 n_base_weights; const char **seno_filename_ext; uint32 ci_initial_weights; seno_filename_ext = ckd_calloc(S2_N_FEATURE, sizeof(char *)); seno_filename_ext[0] = cmd_ln_access("-cepsenoext"); seno_filename_ext[1] = cmd_ln_access("-dcepsenoext"); seno_filename_ext[2] = cmd_ln_access("-powsenoext"); seno_filename_ext[3] = cmd_ln_access("-2dcepsenoext"); n_ci = acmod_set_n_ci(acmod_set); n_states = cluster_offset[n_ci]; out = (float32 ***)ckd_calloc_3d(n_states, S2_N_FEATURE, S2_N_CODEWORD, sizeof(float32)); E_INFO("%dK in mixture weights\n", n_states * S2_N_CODEWORD * S2_N_FEATURE / 1024); E_INFO("%ldK in array overhead\n", ((n_states * S2_N_FEATURE * sizeof(float *)) + (S2_N_FEATURE * sizeof(float **))) / 1024); if (in_smap == NULL) { E_INFO("initializing mixing weights with prior CI weights\n"); ci_initial_weights = TRUE; } else { ci_initial_weights = FALSE; } n_base_weights = (S2_N_STATE-1) * S2_N_CODEWORD; in_seno = ckd_calloc(S2_N_FEATURE, sizeof(int32 *)); for (i = 0; i < n_ci; i++) { if (!ci_initial_weights) { n_base_states = cluster_offset[i+1] - cluster_offset[i]; /* diff of cluster offsets just accounts for shared triphone states, not ci phone states. Add ci state count */ n_base_states += S2_N_STATE-1; n_base_weights = n_base_states * S2_N_CODEWORD; } read_seno_cluster(in_seno, seno_dir, acmod_set_id2name(acmod_set, i), seno_filename_ext, n_base_weights); exp_mixw(out, in_seno, i, ci_initial_weights, cluster_offset, state_of); for (f = 0; f < S2_N_FEATURE; f++) { ckd_free(in_seno[f]); } } ckd_free(in_seno); return out; } float32 *** s2_read_seno_2(acmod_set_t *acmod_set, /* the phone set of the model inventory */ uint32 *cluster_offset, /* number of senones before each base phone cluster */ const char *seno_dir, /* the directory containing the .ccode, .d2code, etc. files */ const char *init_seno_map_filename, /* An initial senone mapping */ float32 weight_floor, /* the least probability of the weights prior to renormalization */ uint32 *state_of) /* the model state id's for each shared state */ { float32 ***out; uint32 i, f; uint32 n_ci; uint32 *in_cluster_size; int32 **in_seno; uint32 n_states; uint32 n_base_states; uint32 n_base_weights; const char **seno_filename_ext; uint32 **in_smap; uint32 ci_initial_weights; in_smap = NULL; in_cluster_size = NULL; seno_filename_ext = ckd_calloc(S2_N_FEATURE, sizeof(char *)); seno_filename_ext[0] = cmd_ln_access("-cepsenoext"); seno_filename_ext[1] = cmd_ln_access("-dcepsenoext"); seno_filename_ext[2] = cmd_ln_access("-powsenoext"); seno_filename_ext[3] = cmd_ln_access("-2dcepsenoext"); n_ci = acmod_set_n_ci(acmod_set); n_states = cluster_offset[n_ci]; out = (float32 ***)ckd_calloc_3d(n_states, S2_N_FEATURE, S2_N_CODEWORD, sizeof(float32)); E_INFO("%dK in mixture weights\n", n_states * S2_N_CODEWORD * S2_N_FEATURE / 1024); E_INFO("%ldK in array overhead\n", ((n_states * S2_N_FEATURE * sizeof(float *)) + (S2_N_FEATURE * sizeof(float **))) / 1024); if (init_seno_map_filename != NULL) { in_cluster_size = ckd_calloc(n_ci+1, sizeof(uint32)); in_smap = (uint32 **)ckd_calloc_2d(acmod_set_n_acmod(acmod_set), S2_N_STATE-1, sizeof(uint32)); s2_read_seno_mapping_file(in_smap, in_cluster_size, init_seno_map_filename, acmod_set); ci_initial_weights = FALSE; } else { E_INFO("initializing mixing weights with prior CI weights\n"); fflush(stderr); ci_initial_weights = TRUE; } n_base_weights = (S2_N_STATE-1) * S2_N_CODEWORD; in_seno = ckd_calloc(S2_N_FEATURE, sizeof(int32 *)); for (i = 0; i < n_ci; i++) { if (!ci_initial_weights) { n_base_states = cluster_offset[i+1] - cluster_offset[i]; /* diff of cluster offsets just accounts for shared triphone states, not ci phone states. Add ci state count */ n_base_states += S2_N_STATE-1; n_base_weights = n_base_states * S2_N_CODEWORD; } read_seno_cluster(in_seno, seno_dir, acmod_set_id2name(acmod_set, i), seno_filename_ext, n_base_weights); exp_norm_floor_mixw(out, weight_floor, in_seno, i, ci_initial_weights, cluster_offset, state_of); for (f = 0; f < S2_N_FEATURE; f++) { ckd_free(in_seno[f]); } } ckd_free(in_seno); if (in_cluster_size != NULL) ckd_free(in_cluster_size); if (in_smap != NULL) ckd_free_2d((void **)in_smap); return out; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.11 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.10 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.9 1995/12/15 18:37:07 eht * Added some type cases for memory alloc/free * * Revision 1.8 1995/10/17 14:03:23 eht * Changed to port to Windows NT * * Revision 1.7 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.6 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.5 1995/10/09 15:08:24 eht * changed ckd_alloc interface to remove need for __FILE__, __LINE__ * arguments * * Revision 1.4 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.3 1995/08/15 13:45:33 eht * Made the diagnostic output less verbose * * Revision 1.2 1995/08/09 20:32:05 eht * No normalization of counts. * * Revision 1.1 1995/05/22 19:19:38 eht * Initial revision * * */ <file_sep>/web/script/update_sf.sh #!/bin/bash # Make the user id configurable by the use of an environmental # variable SF_USER. Set it to current user, if not defined. if test x$SF_USER == x; then SF_USER=`whoami`,cmusphinx; fi TMP=build$$ mkdir $TMP pushd $TMP > /dev/null svn export https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/web > /dev/null #pushd web/cgi-bin > /dev/null #svn log -v https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx > svn_history #gzip -9f svn_history #rsync -e ssh -auv --progress * $SF_USER@web.sourceforge.net:/home/groups/c/cm/cmusphinx/cgi-bin/ > /dev/null #popd > /dev/null pushd web/htdocs/html > /dev/null rsync -e ssh -auv --delete . $<EMAIL>:/home/groups/c/cm/cmusphinx/htdocs/html > /dev/null rsync -e ssh -lptgoDuv * www.speech.cs.cmu.edu:/usr1/httpd/html/sphinx > /dev/null popd > /dev/null for module in cmuclmtk sphinx2 sphinx3 sphinxbase SphinxTrain; do ( svn export https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/$module/doc $module > /dev/null cd $module > /dev/null rsync -e ssh -auv --delete . $<EMAIL>:/home/groups/c/cm/cmusphinx/htdocs/doc/$module > /dev/null ) done popd > /dev/null /bin/rm -rf $TMP # Just in case, change group ownership and permissions #ssh $SF_<EMAIL>@<EMAIL>.net chgrp -R cmusphinx /home/groups/c/cm/cmusphinx/ > /dev/null 2>&1 #ssh $<EMAIL> chmod g+w -R cmusphinx /home/groups/c/cm/cmusphinx/ > /dev/null 2>&1 # revision 1.7 2006/08/02 15:30:54 egouvea # Disabled section about sphinx-4. # revision 1.6 2006/07/13 22:05:20 egouvea # Made path absolute # revision 1.5 2006/05/26 21:26:17 egouvea # Copies all files in current dir ('*') rather than only the dir ('.') # revision 1.4 2005/11/10 21:58:39 egouvea # Make the rsync not recursive for the fife location # revision 1.3 2005/11/07 17:14:46 egouvea # Updated update script # revision 1.2 2005/09/19 16:15:24 egouvea # Sidebar now uses <ul> added notice saying people should contact the authors directly for external links script deletes files that are different # revision 1.1 2005/06/17 18:27:50 egouvea # Added file to update the sf.net site <file_sep>/archive_s3/s3.2/src/cmn.c /* * cmn.c -- Various forms of cepstral mean normalization * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 28-Apr-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed the name norm_mean() to cmn(). * * 19-Jun-1996 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed to compute CMN over ALL dimensions of cep instead of 1..12. * * 04-Nov-1995 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include "cmn.h" void cmn (float32 **mfc, int32 varnorm, int32 n_frame, int32 veclen) { static float32 *mean = NULL; static float32 *var = NULL; float32 *mfcp; float32 t; int32 i, f; assert ((n_frame > 0) && (veclen > 0)); if (mean == NULL) mean = (float32 *) ckd_calloc (veclen, sizeof (float32)); /* Find mean cep vector for this utterance */ for (i = 0; i < veclen; i++) mean[i] = 0.0; for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mean[i] += mfcp[i]; } for (i = 0; i < veclen; i++) mean[i] /= n_frame; if (! varnorm) { /* Subtract mean from each cep vector */ for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mfcp[i] -= mean[i]; } } else { /* Scale cep vectors to have unit variance along each dimension, and subtract means */ if (var == NULL) var = (float32 *) ckd_calloc (veclen, sizeof (float32)); for (i = 0; i < veclen; i++) var[i] = 0.0; for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) { t = mfcp[i] - mean[i]; var[i] += t * t; } } for (i = 0; i < veclen; i++) var[i] = sqrt ((float64) n_frame / var[i]); /* Inverse Std. Dev */ for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mfcp[i] = (mfcp[i] - mean[i]) * var[i]; } } } <file_sep>/archive_s3/s3.2/src/libutil/bitvec.h /* * bitvec.h -- Bit vector type. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 13-Sep-1999 <NAME> (<EMAIL>) at Carnegie Mellon * Added bitvec_uint32size(). * * 05-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon * Added bitvec_count_set(). * * 17-Jul-97 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #ifndef _LIBUTIL_BITVEC_H_ #define _LIBUTIL_BITVEC_H_ #include "prim_type.h" #include "ckd_alloc.h" typedef uint32 *bitvec_t; /* * NOTE: The following definitions haven't been designed for arbitrary usage!! */ /* No. of uint32 words allocated to represent a bitvector of the given size n */ #define bitvec_uint32size(n) (((n)+31)>>5) #define bitvec_alloc(n) ((bitvec_t) ckd_calloc (((n)+31)>>5, sizeof(uint32))) #define bitvec_free(v) ckd_free((char *)(v)) #define bitvec_set(v,b) (v[(b)>>5] |= (1 << ((b) & 0x001f))) #define bitvec_clear(v,b) (v[(b)>>5] &= ~(1 << ((b) & 0x001f))) #define bitvec_clear_all(v,n) memset(v, 0, (((n)+31)>>5)*sizeof(uint32)) #define bitvec_is_set(v,b) (v[(b)>>5] & (1 << ((b) & 0x001f))) #define bitvec_is_clear(v,b) (! (bitvec_is_set(v,b))) /* * Return the number of bits set in the given bit-vector. */ int32 bitvec_count_set (bitvec_t vec, /* In: Bit vector to search */ int32 len); /* In: Lenght of above bit vector */ #endif <file_sep>/tools/riddler/properties/weinbergs.properties admin.user=admin admin.password.file=c:/docume~1/weinbergs/passwd admin.host=localhost admin.port=4848 http.host=localhost http.port=8080 appserver.instance.name=server module=riddler-ejb appname=${module} build.base.dir=c:/temp/build build.classes.dir=${build.base.dir}/classes build.generated.dir=${build.base.dir}/generated assemble.dir=${build.base.dir}/archive <file_sep>/pocketsphinx/src/libpocketsphinx/tokentree.c /* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @name tokentree.h * @brief Token-passing search algorithm * @author <NAME> <<EMAIL>> */ #include <ckd_alloc.h> #include "tokentree.h" tokentree_t * tokentree_init(void) { tokentree_t *ttree = ckd_calloc(1, sizeof(*ttree)); ttree->token_alloc = listelem_alloc_init(sizeof(token_t)); ttree->leaves = heap_new(); return ttree; } tokentree_t * tokentree_retain(tokentree_t *tree) { if (tree == NULL) return tree; --tree->refcount; return tree; } int tokentree_free(tokentree_t *tree) { if (tree == NULL) return 0; if (--tree->refcount > 0) return tree->refcount; listelem_alloc_free(tree->token_alloc); heap_destroy(tree->leaves); ckd_free(tree); return 0; } token_t * tokentree_add(tokentree_t *tree, int32 pathcost, int32 arcid, token_t *prev) { token_t *token = listelem_malloc(tree->token_alloc); token->pathcost = pathcost; token->arcid = arcid; token->prev = prev; if (prev != NULL) { heap_remove(tree->leaves, prev); } heap_insert(tree->leaves, token, pathcost); return token; } int tokentree_prune(tokentree_t *tree, int32 maxcost) { heap_t *newheap = heap_new(); void *data; int32 val; while (heap_pop(tree->leaves, &data, &val)) { if (val < maxcost) heap_insert(newheap, data, val); } heap_destroy(tree->leaves); tree->leaves = newheap; return 0; } int tokentree_prune_topn(tokentree_t *tree, int32 n) { heap_t *newheap = heap_new(); void *data; int32 val, i; i = 0; while (heap_pop(tree->leaves, &data, &val)) { if (i == n) break; heap_insert(newheap, data, val); ++i; } heap_destroy(tree->leaves); tree->leaves = newheap; return 0; } int tokentree_clear(tokentree_t *tree) { listelem_alloc_free(tree->token_alloc); heap_destroy(tree->leaves); tree->token_alloc = listelem_alloc_init(sizeof(token_t)); tree->leaves = heap_new(); return 0; } <file_sep>/CLP/include/common_lattice.h //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- // 05/31/2001 changed MAX_VOC_SIZE to a bigger val (200000) #ifndef _common_lattice_h #define _common_lattice_h #include <map> #include <ext/hash_map> #include <vector> #include <ext/slist> #include <list> #include <string> using namespace std; using namespace __gnu_cxx; typedef unsigned LinkId; typedef unsigned NodeId; typedef unsigned WordId; typedef vector<unsigned> IdsVector; typedef vector<IdsVector> IdsMatrix; typedef vector<double> DblVector; typedef vector<DblVector> DblMatrix; typedef string Word; typedef pair<int,double> IntDbl; typedef pair<int,int> IntInt; typedef list<LinkId> IdsList; typedef IdsList::iterator IdsListIt; typedef IdsList::const_iterator IdsListConstIt; struct ess { bool operator() (const IntInt& a, const IntInt& b) const{ return (a.first < b.first || (a.first == b.first && a.second < b.second)); } }; struct compW { bool operator() (const IntDbl& a, const IntDbl& b) const{ return (a.second > b.second || (a.second == b.second && a.first < b.first)); } }; typedef map<IntInt, double, ess> IntIntDblMap; typedef IntIntDblMap::iterator IntIntDblMapIt; typedef map<IntInt, int, ess> IntIntIntMap; typedef IntIntIntMap::iterator IntIntIntMapIt; typedef slist<IntDbl> IntDblList; typedef IntDblList::iterator IntDblListIt; typedef IntDblList::const_iterator IntDblListConstIt; typedef map<Word,int> WordIntMap; typedef WordIntMap::iterator WordIntMapIt; typedef map<int,double> IntDblMap; typedef IntDblMap::const_iterator IntDblMapConstIt; typedef IntDblMap::iterator IntDblMapIt; typedef map<int,int> IntIntMap; typedef IntIntMap::iterator IntIntMapIt; typedef vector<Word> WordVector; typedef vector<int> IntVector; typedef vector<IntDbl> IntDblVector; const Word START_WD = "!SENT_START"; const Word END_WD = "!SENT_END"; const Word EPS = "!NULL"; const WordId MAX_NO_WORDS = 512; // in a sentence const WordId MAX_NO_WORDS_LAT = 5000; // in a lattice const unsigned MAX_LINE = 1000; // max no of chars on a line const float MAX_TIME = 1000; // max end time hypothesized for a word (secs) const unsigned MAX_VOC_SIZE = 200000; // max no of words in the vocabulary const unsigned MAX_NO_FIELDS_NODE = 6; const unsigned MIN_NO_FIELDS_NODE = 1; const unsigned MAX_NO_FIELDS_LINK = 10; const unsigned MIN_NO_FIELDS_LINK = 3; const unsigned MAX_NO_FIELDS_INFO_SLF = 20; const unsigned MIN_NO_FIELDS_INFO_SLF = 4; const unsigned MAX_NO_FIELDS_FSM = 5; const unsigned MIN_NO_FIELDS_FSM = 1; const unsigned DEFAULT_NO_PRONS = 2; const string BLANK = " \t"; #endif <file_sep>/SphinxTrain/src/programs/tiestate/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 <NAME> University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[]= "Description : \n\ Create a model definition file with tied state from model definition file without tied states. "; const char examplestr[]= "Example: \n\ tiestate -imoddeffn imdef -omoddeffn omdef -treedir trees -psetfn questions \n\ \n\ This is an example of the input and output format, Find more details at, \n\ http://www.speech.cs.cmu.edu/sphinxman"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-imoddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Untied-state model definition file"}, { "-omoddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied-state model definition file"}, { "-treedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "SPHINX-III tree directory containing pruned trees"}, { "-psetfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Phone set definiton file" }, { "-allphones", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Use a single tree for each state of all phones"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2005/06/13 22:18:23 dhdfu * Add -allphones arguments to decision tree and state tying code. Allows senones to be shared across multiple base phones (though they are currently still restricted to the same state). This can improve implicit pronunciation modeling in some cases, such as grapheme-based models, though it usually has little effect. Building the big trees can take a very long time. * * Revision 1.6 2005/04/07 21:23:40 egouvea * Improved the documentation, making it easier to find pointers, fixed the setup script, and fixed some of the doxygen comments * * Revision 1.5 2004/11/29 01:43:52 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.4 2004/11/29 01:11:37 egouvea * Fixed license terms in some new files. * * Revision 1.3 2004/11/29 00:49:28 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.2 2004/08/09 20:59:48 arthchan2003 * help and example of tiestate * * Revision 1.1 2004/06/17 19:39:51 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/python/cmusphinx/lattice_error.py #!/usr/bin/env python import sys import os import lattice from itertools import izip ctl, ref, latdir = sys.argv[1:] ctl = open(ctl) ref = open(ref) wordcount = 0 errcount = 0 for c,r in izip(ctl, ref): c = c.strip() r = r.split() del r[-1] if len(r) == 0 or r[0] != '<s>': r.insert(0, '<s>') if r[-1] != '</s>': r.append('</s>') r = filter(lambda x: not lattice.is_filler(x), r) l = lattice.Dag() try: l.sphinx2dag(os.path.join(latdir, c + ".lat.gz")) except IOError: try: l.sphinx2dag(os.path.join(latdir, c + ".lat")) except IOError: l.htk2dag(os.path.join(latdir, c + ".slf")) err, bt = l.minimum_error(r) maxlen = [max([len(y) for y in x]) for x in bt] print " ".join(["%*s" % (m, x[0]) for m, x in izip(maxlen, bt)]) print " ".join(["%*s" % (m, x[1]) for m, x in izip(maxlen, bt)]) print "Error: %.2f%%" % (float(err) / len(r) * 100) print wordcount += len(r) errcount += err print "TOTAL Error: %.2f%%" % (float(errcount) / wordcount * 100) <file_sep>/SphinxTrain/src/libs/libs2io/s2_write_hmm.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_write_tmat.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* SPHINX-III header files */ #include <s3/s2_write_hmm.h> #include <s3/s2_param.h> #include <s3/cmd_ln.h> #include <s3/vector.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> /* Header files imported from SPHINX-II */ #include <s2/log.h> #include <s2/magic.h> #include <s2/byteorder.h> /* SPHINX-III system portability */ #include <sys_compat/file.h> /* System-wide header files */ #include <assert.h> #include <stdio.h> static int fwrite_long(FILE *fp, int32 i) { SWAPL(&i); if (fwrite (&i, sizeof(int32), 1, fp) != 1) return S3_ERROR; else return S3_SUCCESS; } static int write_transition(int32 from, int32 to, int32 prob, int32 opdf_index, FILE *fp) { fwrite_long (fp, from); fwrite_long (fp, to); fwrite_long (fp, prob); fwrite_long (fp, opdf_index); return S3_SUCCESS; } static int write_sdm(float32 **tmat, FILE *fp) { int32 n_arc; fwrite_long (fp, TIED_DIST); /* what type of file it is (trans only) */ /* might also be BIG_HMM */ fwrite_long (fp, S2_N_CODEWORD); /* number of codewords??? */ fwrite_long (fp, S2_N_STATE-1); /* n_omatrix */ /* * Output pdfs would go here, but instead go in *.{ccode,xcode,...} */ fwrite_long (fp, S2_N_STATE); /* n_states */ fwrite_long (fp, 1); /* n_initial (states) */ fwrite_long (fp, 0); /* list of initial states {0} */ fwrite_long (fp, 1); /* n_final */ fwrite_long (fp, (S2_N_STATE-1)); /* list of final states {S2_N_STATE-1} */ n_arc = 14; fwrite_long (fp, n_arc); /* number of arcs */ /* * Dump these in the same order as s2 did. */ write_transition (0, 0, LOG(tmat[0][0]), 0, fp); write_transition (0, 1, LOG(tmat[0][1]), 0, fp); write_transition (1, 1, LOG(tmat[1][1]), 1, fp); write_transition (1, 2, LOG(tmat[1][2]), 1, fp); write_transition (2, 2, LOG(tmat[2][2]), 2, fp); write_transition (2, 3, LOG(tmat[2][3]), 2, fp); write_transition (3, 3, LOG(tmat[3][3]), 3, fp); write_transition (3, 4, LOG(tmat[3][4]), 3, fp); write_transition (4, 4, LOG(tmat[4][4]), 4, fp); write_transition (4, 5, LOG(tmat[4][5]), 4, fp); write_transition (0, 2, LOG(tmat[0][2]), 0, fp); write_transition (1, 3, LOG(tmat[1][3]), 1, fp); write_transition (2, 4, LOG(tmat[2][4]), 2, fp); write_transition (3, 5, LOG(tmat[3][5]), 3, fp); return S3_SUCCESS; } static int write_dhmm(float32 **tmat, float32 ***mixw, FILE *fp) { int32 n_arc; uint32 i, j, k; int32 tmp; fwrite_long (fp, COUNT_F); /* what type of file it is (trans only) */ /* might also be BIG_HMM */ fwrite_long (fp, S2_N_CODEWORD); /* number of codewords??? */ fwrite_long (fp, S2_N_STATE-1); /* n_omatrix */ /* * Output pdfs */ for (j = 0; j < 4; j++) { for (i = 0; i < S2_N_STATE-1; i++) { for (k = 0; k < S2_N_CODEWORD; k++) { tmp = LOG(mixw[i][j][k]); fwrite_long(fp, tmp); } } } fwrite_long (fp, S2_N_STATE); /* n_states */ fwrite_long (fp, 1); /* n_initial (states) */ fwrite_long (fp, 0); /* list of initial states {0} */ fwrite_long (fp, 1); /* n_final */ fwrite_long (fp, (S2_N_STATE-1)); /* list of final states {S2_N_STATE-1} */ n_arc = 14; fwrite_long (fp, n_arc); /* number of arcs */ /* * Dump these in the same order as s2 did. */ write_transition (0, 0, LOG(tmat[0][0]), 0, fp); write_transition (0, 1, LOG(tmat[0][1]), 0, fp); write_transition (1, 1, LOG(tmat[1][1]), 1, fp); write_transition (1, 2, LOG(tmat[1][2]), 1, fp); write_transition (2, 2, LOG(tmat[2][2]), 2, fp); write_transition (2, 3, LOG(tmat[2][3]), 2, fp); write_transition (3, 3, LOG(tmat[3][3]), 3, fp); write_transition (3, 4, LOG(tmat[3][4]), 3, fp); write_transition (4, 4, LOG(tmat[4][4]), 4, fp); write_transition (4, 5, LOG(tmat[4][5]), 4, fp); /* skip arcs */ write_transition (0, 2, LOG(tmat[0][2]), 0, fp); write_transition (1, 3, LOG(tmat[1][3]), 1, fp); write_transition (2, 4, LOG(tmat[2][4]), 2, fp); write_transition (3, 5, LOG(tmat[3][5]), 3, fp); return S3_SUCCESS; } static int put_dhmm(float32 **tmat, float32 ***mixw, const char *dir, const char *name) { const char *hmm_ext; char fn[MAXPATHLEN]; FILE *fp; hmm_ext = cmd_ln_access("-hmmext"); sprintf(fn, "%s/%s.%s", dir, name, hmm_ext); fp = fopen(fn, "wb"); if (fp == NULL) { E_ERROR_SYSTEM("can't open %s for writing", fn); return S3_ERROR; } if (write_dhmm(tmat, mixw, fp) != S3_SUCCESS) return S3_ERROR; fclose(fp); return S3_SUCCESS; } static int put_sdm(float32 **tmat, const char *in_dir_name, const char *ci_name) { const char *hmm_ext; char ci_hmm_filename[MAXPATHLEN]; FILE *fp; hmm_ext = cmd_ln_access("-hmmext"); sprintf(ci_hmm_filename, "%s/%s.%s", in_dir_name, ci_name, hmm_ext); fp = fopen(ci_hmm_filename, "wb"); if (fp == NULL) { fflush(stdout); fprintf(stderr, "%s(%d): can't open %s for reading to extract tmat\n", __FILE__, __LINE__, ci_hmm_filename); fflush(stderr); return S3_ERROR; } if (write_sdm(tmat, fp) != S3_SUCCESS) return S3_ERROR; fclose(fp); return S3_SUCCESS; } #if 0 static void print_tmat(FILE *fp, float32 **tmat, int n_state) { uint32 i, j; for (i = 0; i < n_state-1; i++) { for (j = 0; j < n_state; j++) { fprintf(fp, "(%u %u) == %f\n", i, j, tmat[i][j]); } } } #endif int s2_write_dhmm(float32 ***tmat, float32 ***mixw, model_def_t *mdef, const char *dir) { acmod_set_t *acmod_set; model_def_entry_t *defn; uint32 b, n_state, i, j, err; uint32 n_acmod; float32 ***omixw = NULL; err = 0; acmod_set = mdef->acmod_set; n_acmod = acmod_set_n_acmod(acmod_set); for (i = 0; i < n_acmod; i++) { defn = &mdef->defn[i]; b = (uint32)acmod_set_base_phone(acmod_set, (acmod_id_t)i); if (omixw) ckd_free((void *)omixw); n_state = defn->n_state; omixw = (float32 ***)ckd_calloc(n_state, sizeof(float32 **)); for (j = 0; j < n_state-1; j++) { omixw[j] = mixw[defn->state[j]]; } if (put_dhmm(tmat[b], omixw, dir, acmod_set_id2s2name(acmod_set, (acmod_id_t)i)) != S3_SUCCESS) err = 1; } if (omixw) ckd_free((void *)omixw); if (!err) { return S3_SUCCESS; } else { return S3_ERROR; } } int s2_write_hmm(float32 ***tmat, acmod_set_t *acmod_set, const char *out_dir_name) { uint32 n_ci; uint32 i; int err; n_ci = acmod_set_n_ci(acmod_set); E_INFO("Writing %d tied CI transition matrices to %s\n", n_ci, out_dir_name); err = 0; for (i = 0; i < n_ci; i++) { if (put_sdm(tmat[i], out_dir_name, acmod_set_id2name(acmod_set, i)) != S3_SUCCESS) err = 1; #ifdef S2_WRITE_HMM_VERBOSE if (!err) { print_tmat(stdout, tmat[i], S2_N_STATE); fflush(stdout); } #endif } if (!err) { return S3_SUCCESS; } else { return S3_ERROR; } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/03/01 00:47:44 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.7 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.6 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.5 1995/10/17 14:03:23 eht * Changed to port to Windows NT * * Revision 1.4 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.3 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.1 1995/09/07 19:26:19 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/misc/nbest-reorder.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <s3.h> #include <libutil/libutil.h> #include <libfbs/misc.h> static void usagemsg (char *pgm) { E_FATAL("Usage: %s ctlfile nbestdir rescoredir matchfile langwt wordinspen\n", pgm); } main (int32 argc, char *argv[]) { char *ctlfile, *nbestdir, *rescoredir, *matchfile, *lwarg, *wiparg, *lp; float32 lw, wip; FILE *ctlfp, *rfp, *mfp; char ctlspec[1024], uttid[1024], file[1024], line[1024]; int32 sf, ef, nhyp, ascr, tscr, best, bestid; hyp_t **hyplist, *h; int32 i; if (argc != 7) usagemsg (argv[0]); ctlfile = argv[1]; nbestdir = argv[2]; rescoredir = argv[3]; matchfile = argv[4]; lwarg = argv[5]; wiparg = argv[6]; if ((sscanf (lwarg, "%f", &lw) != 1) || (sscanf (wiparg, "%f", &wip) != 1)) usagemsg (argv[0]); ctlfp = ctlfile_open (ctlfile); if ((mfp = fopen (matchfile, "w")) == NULL) { E_ERROR("fopen(%s,w) failed; using stdout\n", matchfile); mfp = stdout; } nhyp = 0; rfp = NULL; while (ctlfile_next (ctlfp, ctlspec, &sf, &ef, uttid) == 0) { fflush (mfp); if (nhyp > 0) nbestlist_free (hyplist, nhyp); if (rfp) fclose (rfp); if ((nhyp = nbestfile_load (nbestdir, uttid, &hyplist)) <= 0) { E_ERROR ("Nbest load failed; cannot rescore %s\n", uttid); fprintf (mfp, "%s T 0 A 0 L 0 (null)\n", uttid); continue; } sprintf (file, "%s/%s.alpha", rescoredir, uttid); if ((rfp = fopen (file, "r")) == NULL) { E_ERROR ("%s: Cannot load alpha score file %s\n", uttid, file); fprintf (mfp, "%s T 0 A 0 L 0 (null)\n", uttid); continue; } /* Skip initial comments */ while (((lp = fgets (line, sizeof(line), rfp)) != NULL) && (line[0] == '#')); best = (int32) 0x80000000; for (i = 0; i < nhyp; i++) { if (! lp) { E_ERROR ("%s: Premature EOF(%s)\n", uttid, file); break; } if (sscanf (line, "%d", &ascr) != 1) { E_ERROR ("%s: Bad alpha score line: %s\n", uttid, line); break; } tscr = ascr + hyplist[i]->lscr * lw; if (tscr > best) { best = tscr; bestid = i; } lp = fgets (line, sizeof(line), rfp); } if (i < nhyp) fprintf (mfp, "%s T 0 A 0 L 0 (null)\n", uttid); else { E_INFO ("%s: best hyp %d\n", uttid, bestid); fprintf (mfp, "%s T %d A %d L %d", uttid, best, (int32) (best - hyplist[bestid]->lscr * lw), (int32) (hyplist[bestid]->lscr * lw)); for (h = hyplist[bestid]; h; h = h->next) fprintf (mfp, " %d %s", h->sf, h->word); fprintf (mfp, "\n"); } } ctlfile_close (ctlfp); fclose (mfp); } <file_sep>/SphinxTrain/src/libs/libcep_feat/live_norm.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: live_norm.c * * Description: * CMN for a live system. This file defines the following public * functions: * * mean_norm_init(int32 vlen) * Initialize subsystem to normalize feature vectors of * length VLEN. * * mean_norm_acc_sub(float *vec) * Add coefficents to running total and subtract the current * estimated mean from VEC. Increments the number of input * frames. * * mean_norm_update() * Computes a new mean from the accumulated coefficient totals and * the number of input frames seen since the last update. * The new mean is averaged with the prior value for the mean to * obtain the estimated mean for the next utterance. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$";*/ #include <s3/live_norm.h> #include <s3/prim_type.h> #include <s3/s3.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> static int veclen; /* the feature vector length */ static float *cur_mean = NULL; /* the mean subtracted from input frames */ static float *sum = NULL; /* the sum over input frames */ static int nframe; /* the total number of input frames */ static int initialize = TRUE; /* whether initialization is required */ void mean_norm_init() { cur_mean = (float *) calloc(veclen, sizeof(float)); sum = (float *) calloc(veclen, sizeof(float)); nframe = 0; printf("mean_norm_init: zero mean\n"); } void mean_norm_set_veclen(uint32 vlen) { veclen = vlen; } void mean_norm_acc_sub(float32 *vec) { int32 i; if (initialize) { mean_norm_init(); initialize = FALSE; } for (i = 1; i < veclen; i++) { sum[i] += vec[i]; vec[i] -= cur_mean[i]; } ++nframe; } void mean_norm_update() { int32 i; if (nframe == 0) { E_WARN("Attempted to update mean without new frames\n"); return; } printf("mean_norm_update: from < "); for (i = 1; i < veclen; i++) printf("%5.2f ", cur_mean[i]); printf(">\n"); for (i = 1; i < veclen; i++) { sum[i] /= nframe; cur_mean[i] = (cur_mean[i] + sum[i]) / 2; sum[i] = 0; } nframe = 0; printf("mean_norm_update: to < "); for (i = 1; i < veclen; i++) printf("%5.2f ", cur_mean[i]); printf(">\n"); } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/09 00:56:17 egouvea * Make sure variables are initialized in cmn live (option 'prior' of cmn). * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.3 1995/10/17 13:05:04 eht * Cleaned up code a bit so that it is more ANSI compliant * * Revision 1.2 1995/10/10 12:36:12 eht * Changed to use <s3/prim_type.h> * * Revision 1.1 1995/06/02 20:57:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/tests/ti46/Makefile # ==================================================================== # # Sphinx III # # ==================================================================== TOP=`(cd ../../..; pwd)` DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = # LIVEDECSRCS = # MAINSRCS = # OTHERSRCS = main.c # LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile LIBNAME= tests BINDIR = $(TOP)/bin/$(MACHINE) ti46: rm -f gmake-ti46.results $(BINDIR)/s3decode-anytopo ARGS.ti46 > gmake-ti46.results $(BINDIR)/align -ref ti46.ref -hyp ti46.match > ti46.align <file_sep>/archive_s3/s3.2/src/svqtest.c /* * svqtest.c -- SubVQ module test * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 12-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "subvq.h" #include "feat.h" #include "logs3.h" #include "corpus.h" #include "s3types.h" typedef struct { feat_t *fcb; mgau_model_t *mgau; subvq_t *svq; int32 svqbeam; int32 nsen; int32 *sen_active; float32 ***feat; int32 *senscr; char *cepdir; ptmr_t tm; } kb_t; static arg_t arg[] = { { "-hmmdir", REQARG_STRING, NULL, "HMM directory" }, { "-ctl", ARG_STRING, NULL, "Control file" }, { "-ctloffset", ARG_INT32, "0", "Offset into control file" }, { "-ctlcount", ARG_INT32, "1000000000", "No. of control file entries to process" }, { "-cepdir", ARG_STRING, ".", "Cepstrum directory prefix (for entries in ctl file)" }, { "-svqbeam", ARG_FLOAT64, "3.0e-3", "Beam selecting best components within each mixture Gaussian [0(widest)..1(narrowest)]" }, { "-nsen", ARG_INT32, "-1", "No. of active senones (0, -1(all) or approx. 50%)" }, { NULL, ARG_INT32, NULL, NULL } }; static void process_utt (void *data, char *uttfile, int32 sf, int32 ef, char *uttid) { kb_t *kb; int32 utt_nfr, ns, ng; int32 f, i, j, r; kb = (kb_t *) data; utt_nfr = feat_s2mfc2feat (kb->fcb, uttfile, kb->cepdir, sf, ef, kb->feat, S3_MAX_FRAMES); ptmr_reset (&(kb->tm)); ptmr_start (&(kb->tm)); ns = 0; ng = 0; for (f = 0; f < utt_nfr; f++) { /* Determine active senones */ if (kb->nsen == 0) memset (kb->sen_active, 0, mgau_n_mgau(kb->mgau) * sizeof(int32)); else if (kb->nsen >= mgau_n_mgau(kb->mgau)) { for (i = 0; i < mgau_n_mgau(kb->mgau); i++) kb->sen_active[i] = 1; } else { /* Randomly select about 50% of senones */ for (i = 0; i < mgau_n_mgau(kb->mgau); i += 32) { r = random(); for (j = 0; j < 32; j++) kb->sen_active[i+j] = ((r & (1 << j)) != 0); } } subvq_frame_eval (kb->svq, kb->mgau, kb->svqbeam, kb->feat[f][0], kb->sen_active, kb->senscr); ns += kb->mgau->frm_sen_eval; ng += kb->mgau->frm_gau_eval; if ((f % 100) == 0) { printf ("."); fflush (stdout); } } printf ("\n"); ptmr_stop (&(kb->tm)); E_INFO("%5d frames, %4d sen, %5d gau/fr, %4.1f xCPU, %4.1f xClk\n", utt_nfr, ns / utt_nfr, ng / utt_nfr, (kb->tm.t_cpu * 100.0) / utt_nfr, (kb->tm.t_elapsed * 100.0) / utt_nfr); } main (int32 argc, char *argv[]) { kb_t kb; char mean[8192], var[8192], mixw[8192], svq[8192]; cmd_ln_parse (arg, argc, argv); logs3_init (1.0003); kb.fcb = feat_init ("s3_1x39", "current", "no", "none"); sprintf (mean, "%s/mean", cmd_ln_str("-hmmdir")); sprintf (var, "%s/var", cmd_ln_str("-hmmdir")); sprintf (mixw, "%s/mixw", cmd_ln_str("-hmmdir")); sprintf (svq, "%s/subvq", cmd_ln_str("-hmmdir")); if ((kb.mgau = mgau_init (mean, var, 0.0001 /* varfloor */, mixw, 0.0000001, TRUE)) == NULL) E_FATAL("mgau_init() failed\n"); if ((kb.svq = subvq_init (svq, 0.0001 /* varfloor */, -1, kb.mgau)) == NULL) E_FATAL("subvq_init() failed\n"); kb.cepdir = cmd_ln_str("-cepdir"); if ((kb.feat = feat_array_alloc (kb.fcb, S3_MAX_FRAMES)) == NULL) E_FATAL("feat_array_alloc() failed\n"); kb.senscr = (int32 *) ckd_calloc (mgau_n_mgau(kb.mgau), sizeof(int32)); kb.svqbeam = logs3 (cmd_ln_float64("-svqbeam")); kb.nsen = cmd_ln_int32 ("-nsen"); if ((kb.nsen >= mgau_n_mgau(kb.mgau)) || (kb.nsen < 0)) kb.nsen = mgau_n_mgau(kb.mgau); kb.sen_active = (int32 *) ckd_calloc (mgau_n_mgau(kb.mgau) + 32, sizeof(int32)); E_INFO("logs3(svqbeam)= %d\n", kb.svqbeam); ctl_process (cmd_ln_str("-ctl"), cmd_ln_int32("-ctloffset"), cmd_ln_int32("-ctlcount"), process_utt, (void *)(&kb)); } <file_sep>/archive_s3/s3.2/src/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include $(S3DIR)/Makefile.defines VPATH = .:.. # Decoder DECOBJS = agc.o \ ascr.o \ beam.o \ bio.o \ cmn.o \ cont_mgau.o \ corpus.o \ dict.o \ dict2pid.o \ feat.o \ fillpen.o \ hmm.o \ kbcore.o \ lextree.o \ lm.o \ logs3.o \ main.o \ mdef.o \ subvq.o \ tmat.o \ vector.o \ vithist.o \ wid.o install: (cd $(UTILDIR); $(MAKE) install) mkdir -p $(S3BINDIR) $(MACHINE) (cd $(MACHINE); $(MAKE) $(MFLAGS) -f ../Makefile decode) (cd $(MACHINE); $(MAKE) $(MFLAGS) -f ../Makefile gausubvq) (cd $(MACHINE); $(MAKE) $(MFLAGS) -f ../Makefile lmtest) cp $(MACHINE)/decode $(S3BINDIR) cp $(MACHINE)/gausubvq $(S3BINDIR) cp $(MACHINE)/lmtest $(S3BINDIR) decode: $(DECOBJS) $(CC) $(CFLAGS) -o $@ $(DECOBJS) -lutil -lm # Acoustic model Sub-vector quantizer GAUSUBVQOBJS = gausubvq.o \ cont_mgau.o \ subvq.o \ vector.o \ bio.o \ logs3.o # Build sub-vector quantized acoustic model for faster Gaussian density evaluation gausubvq: $(GAUSUBVQOBJS) $(CC) $(CFLAGS) -o $@ $(GAUSUBVQOBJS) -lutil -lm # Acoustic model Sub-vector quantizer LMTESTOBJS = lmtest.o \ lm.o \ logs3.o # Build sub-vector quantized acoustic model for faster Gaussian density evaluation lmtest: $(LMTESTOBJS) $(CC) $(CFLAGS) -o $@ $(LMTESTOBJS) -lutil -lm clean: (cd $(UTILDIR); $(MAKE) clean) rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# (cd $(MACHINE); rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~) <file_sep>/cmuclmtk/src/libs/ac_lmfunc_impl.h /* ==================================================================== * Copyright (c) 1999-2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _AC_LMFUNC_IMPL_H_ #define _AC_LMFUNC_IMPL_H_ #include "ac_hash.h" #include "toolkit.h" #include "general.h" #include "pc_general.h" int text2wfreq_impl(FILE* infp, FILE* outfp, int init_nwords, int verbosity); int wfreq2vocab_impl(FILE* ifp, FILE* ofp, int cutoff, int vocab_size, int num_recs, int verbosity); int read_vocab(char* vocab, int verbosity, struct idngram_hash_table* vocabulary, int M ); int read_txt2ngram_buffer(FILE* infp, struct idngram_hash_table *vocabulary, int32 verbosity, wordid_t *buffer, int buffer_size, unsigned int n, char* temp_file_root, char* temp_file_ext, FILE* temp_file ); int compare_ngrams(const void *ngram1, const void *ngram2 ); int get_word( FILE *fp , char *word ); #endif <file_sep>/archive_s3/s3.0/pgm/treedec/lextree.c /* * lextree.c -- Maintaining the lexical tree. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 15-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "lextree.h" static void lextree_dump (FILE *fp, glist_t root, dict_t *dict, mdef_t *mdef, int32 ind) { gnode_t *gn; lextree_node_t *node; char phonestr[128]; int32 i; for (gn = root; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); if (mdef_phone_str(mdef, node->hmm.pid, phonestr) < 0) E_FATAL("mdef_phone_str(%d) failed\n", node->hmm.pid); for (i = 0; i < ind; i++) fprintf (fp, "\t"); fprintf (fp, "%s", phonestr); if (LEXTREE_NODEID_VALID(node->id)) fprintf (fp, "[%s.%d]", dict_wordstr(dict, LEXTREE_NODEID2WID(node->id)), LEXTREE_NODEID2PPOS(node->id)); fprintf (fp, "\n"); fflush (fp); lextree_dump (fp, node->children, dict, mdef, ind+1); } } /* * NOTE: This version uses only the SILENCE phone context for the beginning and end of each word. */ glist_t lextree_build (dict_t *dict, mdef_t *mdef, bitvec_t active, int32 flatdepth) { glist_t root, subtree; gnode_t *gn; int32 w, p, l; s3cipid_t sil, lc, rc, ci; s3pid_t pid; lextree_node_t *node, *parent; hmm_t *hmm; int32 *n_node; int32 pos, maxpronlen; assert (mdef && dict); assert (flatdepth >= 0); sil = mdef->sil; if (NOT_CIPID(sil)) { E_ERROR("No silence phone in mdef\n"); return NULL; } if (NOT_WID(dict->startwid) || NOT_WID(dict->finishwid)) { E_ERROR("START or FINISH word(%s or %s) missing from dict\n", START_WORD, FINISH_WORD); return NULL; } maxpronlen = 0; for (w = 0; w < dict_size(dict); w++) { if (maxpronlen < dict_pronlen(dict, w)) maxpronlen = dict_pronlen(dict, w); } n_node = (int32 *) ckd_calloc (maxpronlen+1, sizeof(int32)); if (flatdepth > maxpronlen) flatdepth = maxpronlen; root = NULL; for (w = 0; w < dict_size(dict); w++) { /* Skip START and FINISH words; they are just dummies at the beginning/end of utt */ if ((dict_basewid(dict, w) == dict->startwid) || (dict_basewid(dict, w) == dict->finishwid)) continue; /* Skip words marked as inactive */ if (active && bitvec_is_clear (active, w)) continue; l = dict_pronlen(dict,w) - 1; if (l > flatdepth) l = flatdepth; ci = dict_pron (dict, w, 0); lc = sil; /* Silence left context for the beginning of the word */ /* * Tree portion; shared prefix portion of pronunciation. The last phone of the word * must not be in the shared tree. */ for (p = 0, subtree = root, parent = NULL; p < l; p++) { rc = dict_pron (dict, w, p+1); pos = (p == 0) ? WORD_POSN_BEGIN : WORD_POSN_INTERNAL; pid = mdef_phone_id_nearest (mdef, ci, lc, rc, pos); if (NOT_PID(pid)) E_FATAL("mdef_phone_id(%s,%s,%s,%d) failed\n", mdef_ciphone_str(mdef, ci), mdef_ciphone_str(mdef, lc), mdef_ciphone_str(mdef, rc), pos); /* Look for an HMM in subtree list matching the current pid */ for (gn = subtree; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); if ((node->hmm.pid == pid) && LEXTREE_NODEID_INVALID(node->id)) break; } if (! gn) { /* Didn't find pid; create one and add to parent's children list */ node = (lextree_node_t *) mymalloc (sizeof(lextree_node_t)); if (! parent) root = glist_add_ptr(root, (void *)node); else parent->children = glist_add_ptr(parent->children, (void *)node); node->hmm.pid = pid; node->hmm.state = (hmm_state_t *) ckd_calloc (mdef->n_emit_state, sizeof(hmm_state_t)); node->id = LEXTREE_NODEID_NONE; node->children = NULL; n_node[p]++; } parent = node; subtree = node->children; lc = ci; ci = rc; } /* Flat portion; new nodes created for the rest of the pronunciation */ l = dict_pronlen(dict,w) - 1; if ((w >= LEXTREE_NODEID_MAXWID) || (l >= LEXTREE_NODEID_MAXPPOS)) E_FATAL("Panic! Cannot encode wid > %d, ppos > %d in lextree node-id\n", LEXTREE_NODEID_MAXWID-1, LEXTREE_NODEID_MAXPPOS-1); for (; p <= l; p++) { if (p < l) { rc = dict_pron (dict, w, p+1); pos = (p == 0) ? WORD_POSN_BEGIN : WORD_POSN_INTERNAL; } else { rc = sil; pos = (p == 0) ? WORD_POSN_SINGLE : WORD_POSN_END; } pid = mdef_phone_id_nearest (mdef, ci, lc, rc, pos); if (NOT_PID(pid)) E_FATAL("mdef_phone_id(%s,%s,%s,%d) failed\n", mdef_ciphone_str(mdef, ci), mdef_ciphone_str(mdef, lc), mdef_ciphone_str(mdef, rc), pos); node = (lextree_node_t *) mymalloc (sizeof(lextree_node_t)); if (! parent) root = glist_add_ptr(root, (void *)node); else parent->children = glist_add_ptr(parent->children, (void *)node); node->hmm.pid = pid; node->hmm.state = (hmm_state_t *) ckd_calloc (mdef->n_emit_state, sizeof(hmm_state_t)); node->id = LEXTREE_NODEID (w, l-p); node->children = NULL; n_node[p]++; parent = node; subtree = node->children; lc = ci; ci = rc; } } printf ("Tree nodes/depth: "); for (p = 0; p <= maxpronlen; p++) printf (" %d(%d)", n_node[p], p); printf ("\n"); fflush (stdout); ckd_free (n_node); return root; } /* * Set all the senones in the lextree to the active state in the given bitvec. */ static void lextree_set_senactive (kb_t *kb) { gnode_t *gn; lextree_node_t *node; mdef_t *mdef; bitvec_t active; mdef = kb->mdef; active = kb->am->sen_active; bitvec_clear_all (active, kb->am->sen->n_sen); for (gn = kb->lextree_active; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); senone_set_active (active, mdef->phone[node->hmm.pid].state, mdef->n_emit_state); } kb->n_sen_eval += bitvec_count_set (active, kb->am->sen->n_sen); } /* * Reset the entire lextree (i.e., HMMs in it) to the inactive state. */ static void lextree_clear (mdef_t *mdef, glist_t subtree) /* In/Out: Subtree to be recursively reset */ { gnode_t *gn; lextree_node_t *node; for (gn = subtree; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); hmm_clear (mdef, &(node->hmm)); lextree_clear (mdef, node->children); } } /* * Evaluate active HMMs in lextree. Consider only HMM-internal transitions; i.e., * not cross-HMM transitions in lextree. * Return value: The resulting best HMM state score. */ static int32 lextree_hmm_eval (kb_t *kb, int32 frm) /* In: Current frame */ { int32 bestscore, hmmscore; gnode_t *gn; lextree_node_t *node; int32 n; /* Step the active HMMs through this frame */ bestscore = MAX_NEG_INT32; for (gn = kb->lextree_active, n = 0; gn; gn = gnode_next(gn), n++) { node = (lextree_node_t *) gnode_ptr(gn); assert (node->hmm.active == frm); /* Internal states first */ hmmscore = hmm_vit_eval (kb->mdef, kb->tmat, &(node->hmm), kb->am->senscr); if (bestscore < hmmscore) bestscore = hmmscore; /* Exit state. (Assume that exit state score must be <= best internal score.) */ hmm_vit_eval_exit (kb->mdef, kb->tmat, &(node->hmm)); } kb->n_hmm_eval += n; return bestscore; } /* * Find the best Viterbi history and LM score for the given word. The candidate histories are * all those that ended at the given frame. Return value: LM score for the given word. */ static int32 besthist_lscr(kb_t *kb, /* In: Models, search data structures */ s3wid_t wid, /* In: Word whose LM score is sought */ int32 frm, /* In: Frame at which the immediate predecessors (i.e., candidate histories) of wid ended */ vithist_t **outhist) /* Out: Updated Viterbi history for word */ { int32 lmwid, l1, l2, bestscore, score, bestlscr, lscr; gnode_t *gn; vithist_t *hist, *lmhist, *besthist; int32 n; lmwid = kb->dict2lmwid[wid]; assert (IS_LMWID(lmwid)); bestscore = MAX_NEG_INT32; for (gn = kb->vithist[frm], n = kb->wordmax; gn && (n > 0); gn = gnode_next(gn), --n) { /* Find two-word history and get LM score */ hist = (vithist_t *) gnode_ptr(gn); lmhist = hist->lmhist; assert (lmhist); l2 = kb->dict2lmwid[lmhist->id]; lmhist = lmhist->hist ? lmhist->hist->lmhist : NULL; l1 = lmhist ? kb->dict2lmwid[lmhist->id] : BAD_LMWID; lscr = lm_tg_score (kb->lm, l1, l2, lmwid); score = hist->scr + lscr; if (bestscore < score) { bestscore = score; bestlscr = lscr; besthist = hist; } } *outhist = besthist; return (bestlscr); } /* * Determine which nodes remain active for next frame. Also, evaluate cross-HMM transitions in * lextree, and activate successors as needed. Four possible cases to be handled: * 1. tree -> tree (i.e., not yet entered the flat structure). * Viterbi transition from exit state of source to entry state of dest. HMM. * 2. tree -> flat. * Vit. trans. as in 1, but also compute and include LM score for current word. * (LM score may be accumulated right away, or spread over remaining HMMs for this word.) * 3. flat -> flat (remaining within flat part of lextree). * Vit. trans. as in 1, but if LM score spread over entire flatlex. * 4. flat -> empty (exiting word); enter into Viterbi history structure. * Filler word exits have to be handled separately. For a given segmentation, only the one best * filler word needs to be maintained (assuming filler words are indistinguishable as phonetic * context providers; but then we're not using cross-word phonetic context anyway). Also, filler * exits have to be replicated for all possible histories. * * Replace the active list for the current frame (kb->lextree_active) with that for the next, as * a side-effect. */ static void lextree_hmm_trans (kb_t *kb, int32 frm, /* Current frame */ int32 bestscore) /* Of all HMM states just evaluated */ { int32 th, wth, ppos, sf, lscr, origscore, newscore; gnode_t *gn, *gn2; lextree_node_t *node, *node2; hmm_t *hmm, *hmm2; glist_t next_active; s3wid_t wid; vithist_t *newhist; glist_t filler_exit; /* Pruning thresholds */ th = bestscore + kb->beam; wth = bestscore + kb->wordbeam; assert (wth >= th); /* Lextree nodes active next frame */ next_active = NULL; /* List of filler nodes exiting this frame; for special handling of filler exits */ filler_exit = NULL; for (gn = kb->lextree_active; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); hmm = &(node->hmm); if (hmm->bestscore < th) { if (hmm->active <= frm) /* Not activated for next frame */ hmm_clear (kb->mdef, hmm); continue; } /* Activate for next frame if not already so */ if (hmm->active <= frm) { hmm->active = frm+1; next_active = glist_add_ptr (next_active, (void *)node); } if (hmm->out.score < th) /* Exit score not good enough */ continue; if (LEXTREE_NODEID_INVALID(node->id)) { /* tree -> tree/flat */ assert (node->children); for (gn2 = node->children; gn2; gn2 = gnode_next(gn2)) { node2 = (lextree_node_t *) gnode_ptr(gn2); hmm2 = &(node2->hmm); if (LEXTREE_NODEID_VALID(node2->id)) { /* tree -> flat; need LM score */ wid = LEXTREE_NODEID2WID(node2->id); /* Get LM score and spread over remaining phones */ if (NOT_LMWID(kb->dict2lmwid[wid])) { assert (dict_filler_word(kb->dict, wid)); lscr = fillpen(kb->fillpen, wid) / (LEXTREE_NODEID2PPOS(node2->id) + 1); newhist = hmm->out.hist; newscore = hmm->out.score; } else { lscr = besthist_lscr (kb, wid, hmm->out.hist->frm, &newhist) / (LEXTREE_NODEID2PPOS(node2->id) + 1); newscore = hmm->out.score + (newhist->scr - hmm->out.hist->scr); } if (hmm_vit_trans_comp (newscore + lscr, newhist, lscr, hmm2, frm+1)) next_active = glist_add_ptr(next_active, (void *)node2); } else { /* still within tree -> tree */ if (hmm_vit_trans (hmm, hmm2, frm+1)) next_active = glist_add_ptr(next_active, (void *)node2); } } } else { gn2 = node->children; if (gn2) { /* flat -> flat transition */ assert (! gnode_next(gn2)); /* Can only have one child in lexflat */ node2 = (lextree_node_t *) gnode_ptr(gn2); hmm2 = &(node2->hmm); if (hmm_vit_trans_comp (hmm->out.score + hmm->out.data, /* Include LM score */ hmm->out.hist, hmm->out.data, hmm2, frm+1)) { next_active = glist_add_ptr(next_active, (void *)node2); } } else if (hmm->out.score >= wth) { /* Word end; note in Viterbi history */ wid = LEXTREE_NODEID2WID(node->id); ppos = LEXTREE_NODEID2PPOS(node->id); assert (IS_WID(wid) && (ppos == 0)); /* Do not note first exit of this word instance */ sf = hmm->out.hist->frm + 1; if (kb->wd_last_sf[wid] < sf) kb->wd_last_sf[wid] = sf; else { if (IS_LMWID(kb->dict2lmwid[wid])) { kb->vithist[frm] = vithist_append (kb->vithist[frm], wid, frm, hmm->out.score, hmm->out.hist, NULL); } else { /* Filler word */ /* Check if another filler with same segmentation already found */ for (gn2 = filler_exit; gn2; gn2 = gnode_next(gn2)) { node2 = (lextree_node_t *) gnode_ptr(gn2); hmm2 = &(node2->hmm); if (hmm->out.hist->frm == hmm2->out.hist->frm) { assert (hmm->out.hist == hmm2->out.hist); if (hmm->out.score > hmm2->out.score) gnode_ptr(gn2) = (void *)node; break; } } if (! gn2) /* No existing filler with same segmentation */ filler_exit = glist_add_ptr (filler_exit, (void *)node); /* Filler word exits handled after all candidates have been sorted out */ } } } } } /* * Viterbi history entries for filler word exits. Each filler word is replicated for all * possible predecessors (i.e., predecessors with same end time). */ for (gn = filler_exit; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); hmm = &(node->hmm); assert (LEXTREE_NODEID_VALID(node->id)); wid = LEXTREE_NODEID2WID(node->id); /* Score with which the current (best) predecessor ended */ origscore = hmm->out.hist->scr; for (gn2 = kb->vithist[hmm->out.hist->frm]; gn2; gn2 = gnode_next(gn2)) { newhist = (vithist_t *) gnode_ptr(gn2); newscore = hmm->out.score + (newhist->scr - origscore); if (newscore >= wth) kb->vithist[frm] = vithist_append (kb->vithist[frm], wid, frm, newscore, newhist, newhist->lmhist); } } glist_free (filler_exit); glist_free (kb->lextree_active); kb->lextree_active = next_active; } /* * Transition from all word exits that just occurred to all the lextree root nodes. * Update the active list (kb->lextree_active) for the next frame as a side-effect. * NOTE: Assumes that the history nodes have been sorted, best score first. */ static void lextree_root_trans (kb_t *kb, int32 frm) /* In: Frame at which words just exited */ { vithist_t *hist, *best; gnode_t *gn; lextree_node_t *node; hmm_t *hmm; s3wid_t wid; int32 lscr; best = gnode_ptr(kb->vithist[frm]); /* The first is the best */ for (gn = kb->lextree_root; gn; gn = gnode_next(gn)) { node = (lextree_node_t *) gnode_ptr(gn); hmm = &(node->hmm); if (LEXTREE_NODEID_INVALID(node->id)) { /* Tree internal node */ if (hmm_vit_trans_comp (best->scr, best, 0, hmm, frm+1)) kb->lextree_active = glist_add_ptr (kb->lextree_active, (void *)node); } else { /* Flatlex node; need to include LM score */ wid = LEXTREE_NODEID2WID(node->id); if (NOT_LMWID(kb->dict2lmwid[wid])) { assert (dict_filler_word (kb->dict, wid)); lscr = fillpen (kb->fillpen, wid); hist = best; } else { lscr = besthist_lscr (kb, wid, frm, &hist); } /* Spread the LM score over the phones */ lscr /= (LEXTREE_NODEID2PPOS(node->id) + 1); if (hmm_vit_trans_comp (hist->scr + lscr, hist, lscr, hmm, frm+1)) kb->lextree_active = glist_add_ptr (kb->lextree_active, (void *)node); } } } void lextree_vit_start (kb_t *kb, char *uttid) { int32 w; lextree_clear(kb->mdef, kb->lextree_root); /* Initialize the Viterbi history with the start word; pretent we're at frame -1 */ assert (kb->vithist[-1] == NULL); kb->vithist[-1] = vithist_append (NULL, kb->dict->startwid, -1, 0, NULL, NULL); /* Start new search with this history; pretend we're at frame -1 */ assert (kb->lextree_active == NULL); lextree_root_trans (kb, -1); kb->n_sen_eval = 0; lextree_set_senactive (kb); /* Clear the most recent start time for any given word */ for (w = 0; w < dict_size(kb->dict); w++) kb->wd_last_sf[w] = -1; kb->n_hmm_eval = 0; } int32 lextree_vit_frame (kb_t *kb, int32 frm, char *uttid) { int32 bestscore; glist_t newlist; /* Evaluate active HMMs */ bestscore = lextree_hmm_eval (kb, frm); /* Check for underflow/overflow problems (Hack!!) */ if ((bestscore <= LOGPROB_ZERO) || (bestscore + kb->beam <= LOGPROB_ZERO)) { E_ERROR("%s: Best HMM score(%d)/pruning threshold(%d) underflow @fr %d; raise logbase\n", uttid, bestscore, bestscore + kb->beam, frm); glist_free (kb->lextree_active); kb->lextree_active = NULL; return MAX_NEG_INT32; } if (bestscore > 0) E_WARN("%s: Best HMM score >0(%d) @fr %d; overflow??\n", uttid, bestscore, frm); /* Cross-HMM transitions within tree, and word exits */ lextree_hmm_trans (kb, frm, bestscore); /* Sort the words just exited in descending order of score */ if (kb->vithist[frm]) { if ((newlist = vithist_sort (kb->vithist[frm])) == NULL) E_FATAL("%s: vithist_sort failed @fr %d\n", uttid, frm); glist_free (kb->vithist[frm]); kb->vithist[frm] = newlist; /* Transitions to lextree root nodes from words just exited */ lextree_root_trans (kb, frm); } lextree_set_senactive (kb); return bestscore; } vithist_t *lextree_vit_end (kb_t *kb, int32 frm, char *uttid) { int32 f, lscr; vithist_t *hist; f = frm-1; if (! kb->vithist[f]) { /* * No words exited in the utterance final frame; find the most recent entries. * (Alternatively, one could force entries in the final frame.) */ for (f = frm-2; (f >= 0) && (! kb->vithist[f]); --f); if (f < 0) { E_ERROR("%s: Empty Viterbi history\n", uttid); return NULL; } E_ERROR("%s: No Viterbi history in final frame; using frame %d\n", uttid, f); } /* Find the best possible transition to the utterance FINISH WORD */ lscr = besthist_lscr (kb, kb->dict->finishwid, f, &hist); /* Create dummy FINISH_WORD node in Viterbi history */ assert (kb->vithist[frm] == NULL); kb->vithist[frm] = vithist_append (NULL, kb->dict->finishwid, frm, hist->scr + lscr, hist, NULL); hist = gnode_ptr(kb->vithist[frm]); return hist; } #if _LEXTREE_TEST_ static void usagemsg(char *pgm) { E_INFO("Usage: %s mdef dict fillerdict flatdepth\n", pgm); exit(0); } main (int32 argc, char *argv[]) { dict_t *dict; mdef_t *mdef; int32 flatdepth; glist_t root; if (argc != 5) usagemsg(argv[0]); if ((sscanf (argv[4], "%d", &flatdepth) != 1) || (flatdepth < 0)) usagemsg(argv[0]); mdef = mdef_init (argv[1]); dict = dict_init (mdef, argv[2], argv[3], 0); E_INFO("Building lextree\n"); root = lextree_build (dict, mdef, NULL, flatdepth); if (! root) E_FATAL("lextree_build() failed\n"); else lextree_dump (stdout, root, dict, mdef, 0); } #endif <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/conftree/VirtModuleTree.java package edu.cmu.sphinx.tools.confdesigner.conftree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /** * Not implemented yet. Later on we'll implement this tree in order to show up all available virtual modules * * @author <NAME> */ public class VirtModuleTree extends ConfigurableTree { public void rebuildTree() { setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); categories.clear(); } } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/actions/NewBackgroundLabelAction.java package edu.cmu.sphinx.tools.confdesigner.actions; import edu.cmu.sphinx.tools.confdesigner.ConfigScene; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; /** * Creates a new resizable background label area within the current screen. * * @author <NAME> */ public class NewBackgroundLabelAction extends AbstractAction { private ConfigScene scene; private Point lastLocation; public NewBackgroundLabelAction(ConfigScene scene) { this.scene = scene; putValue(NAME, "Add Background Label Here"); scene.getView().addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { lastLocation = e.getPoint(); } }); } public void actionPerformed(ActionEvent e) { // create a new background node assert lastLocation != null; scene.addBckndLabel("Unnamed", lastLocation, null, null); } } <file_sep>/SphinxTrain/python/Makefile # ==================================================================== # Copyright (c) 2006 <NAME>. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Python modules # # ==================================================================== TOP=.. DIRNAME=python BUILD_DIRS= ALL_DIRS= MODULES = \ setup.py \ sphinx/arpalm.py \ sphinx/feat/s2_4x.py \ sphinx/feat/__init__.py \ sphinx/feat/_1s_c_d_dd.py \ sphinx/__init__.py \ sphinx/mfcc.py \ sphinx/mllt.py \ sphinx/s2mfc.py \ sphinx/s3file.py \ sphinx/s3gau.py \ sphinx/s3gaucnt.py \ sphinx/s3lda.py \ sphinx/s3mdef.py \ sphinx/s3mixw.py \ sphinx/s3model.py \ sphinx/s3tmat.py FILES = Makefile $(MODULES) ALL = compile include $(TOP)/config/common_make_rules LOCAL_CLEAN = *.pyc compile: python setup.py build <file_sep>/archive_s3/s3/src/libfbs/mllr.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * mllr.c -- Application of MLLR regression matrices to codebook means * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-Dec-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added reading of MLLR classes in transformation file. Currently must * be 1. * * 26-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Started (copied from <NAME>ikh's implementation). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libutil/libutil.h> #include <s3.h> #include "mllr.h" int32 mllr_read_regmat (const char *regmatfile, float32 ****A, float32 ***B, int32 *streamlen, int32 n_stream) { int32 i, j, k, n; FILE *fp; float32 ***lA, **lB; if ((fp = fopen(regmatfile, "r")) == NULL) { E_ERROR ("fopen(%s,r) failed\n", regmatfile); return -1; } else E_INFO ("Reading MLLR transformation file %s\n", regmatfile); lA = (float32 ***) ckd_calloc (n_stream, sizeof (float32 **)); lB = (float32 **) ckd_calloc (n_stream, sizeof (float32 *)); for (i = 0; i < n_stream; ++i) { lA[i] = (float32 **) ckd_calloc_2d (streamlen[i], streamlen[i], sizeof(float32)); lB[i] = (float32 *) ckd_calloc (streamlen[i], sizeof(float32)); } /* Read #MLLR-classes; must be 1 for now (<EMAIL>, 12-Dec-1996) */ if ((fscanf (fp, "%d", &n) != 1) || (n != 1)) goto readerror; if ((fscanf (fp, "%d", &n) != 1) || (n != n_stream)) goto readerror; for (i = 0; i < n_stream; ++i) { if ((fscanf(fp, "%d", &n) != 1) || (streamlen[i] != n)) goto readerror; for (j = 0; j < streamlen[i]; j++) { for (k = 0; k < streamlen[i]; ++k) { if (fscanf(fp, "%f ", &lA[i][j][k]) != 1) goto readerror; } } for (j = 0; j < streamlen[i]; j++) { if (fscanf(fp, "%f ", &lB[i][j]) != 1) goto readerror; } } *A = lA; *B = lB; fclose(fp); return 0; readerror: E_ERROR("Error reading MLLR file %s\n", regmatfile); for (i = 0; i < n_stream; i++) { ckd_free_2d ((void **)lA[i]); ckd_free (lB[i]); } ckd_free (lA); ckd_free (lB); fclose (fp); *A = NULL; *B = NULL; return -1; } int32 mllr_free_regmat (float32 ***A, float32 **B, int32 *streamlen, int32 n_stream) { int32 i; for (i = 0; i < n_stream; i++) { ckd_free_2d ((void **) A[i]); ckd_free (B[i]); } ckd_free (A); ckd_free (B); return 0; } int32 mllr_norm_mgau (float32 ***mean, int32 n_density, float32 ***A, float32 **B, int32 *streamlen, int32 n_stream) { int32 s, d, l, m; float64 *temp; /* Transform codebook for each stream s */ for (s = 0; s < n_stream; s++) { temp = (float64 *) ckd_calloc (streamlen[s], sizeof(float64)); /* Transform each density d in selected codebook */ for (d = 0; d < n_density; d++) { for (l = 0; l < streamlen[s]; l++) { temp[l] = 0.0; for (m = 0; m < streamlen[s]; m++) { temp[l] += A[s][l][m] * mean[s][d][m]; } temp[l] += B[s][l]; } for (l = 0; l < streamlen[s]; l++) { mean[s][d][l] = (float32) temp[l]; } } ckd_free (temp); } return 0; } <file_sep>/archive_s3/s3.2/src/ascr.h /* * ascr.h -- Acoustic (senone) scores * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 19-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_ASCR_H_ #define _S3_ASCR_H_ #include <libutil/libutil.h> /* * Structure to hold senone scores (ordinary and composite), in one frame. */ typedef struct { int32 *sen; /* Senone scores in current frame */ int32 *comsen; /* Composite senone scores in current frame */ } ascr_t; /* * Create an ascr_t structure for the given number of senones (ordinary and composite). * Return value: Ptr to created structure if successful, NULL otherwise. */ ascr_t *ascr_init (int32 n_sen, /* In: #Ordinary senones */ int32 n_comsen); /* In: #Composite senones */ #endif <file_sep>/CLP/include/Lattice.h //------------------------------------------------------------------------------------------- // Copyright (c) nov 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _Lattice_h #define _Lattice_h #include "common.h" #include "Prob.h" #include "Prons.h" #include "common_lattice.h" #include "Link.h" #include "Node.h" #include "LatticeInfo.h" #include <string> #include <map> #include <vector> using namespace std; class Lattice { public: Lattice(const LatticeInfo& info, const Prons& P); LnProb insertion_penalty() {return info.Wdpenalty();} LnProb lm_scale() {return info.LMscale();} LnProb pr_scale() {return info.PRscale();} LnProb Total_prob() {return total_prob;} string Type() const {return info.type;} bool has_time_info() { return time_info;} void set_no_time_info(){ time_info = false;} int no_nodes() {assert(info.No_nodes() == nodes.size()); return nodes.size();} int no_links() {assert(info.No_links() == links.size()); return links.size();} // returns the number of word types in the lattice int no_words(); // get a node knowing its index const Node& node(NodeId id) const{ assert(id < nodes.size()); return nodes[id];} Node& node(NodeId id) { assert(id < nodes.size()); return nodes[id];} // get a link knowing its index const Link& link(LinkId id) const{ assert(id < links.size()); return links[id];} Link& link(LinkId id) { assert(id < links.size()); return links[id];} //scale the links void scale_link_scores(const float scale); // add pronunciation probabilities void add_prons(const Prons& P, const float PRweight); // add/substract word insertion penalty void add_WIP(const float WIP); // compute links probabilities as a combination of LM, AC and PM scores void compute_link_scores(const float lmscale, const float prscale, const float WIP, const float allscale); // see if the nodes ids are in increasing order as a function of time bool check_nodes(); // check if the ending nodes of the links are in increasing order as a function of time // this warranties that the links are in topological order bool check_links(); // if the lattice doesn't have pronunciation probs (field r=...), put uniform probabilities; P contains the number of prons for each word unsigned put_uniform_pron_prob(const Prons& P); // sort the links based on their posterior probs; we need this if we want to keep x% of the links and discard the others (-t option) void mark_pruned_percentage(const float thresh); void mark_pruned_score(const float thresh); void do_ForwardBackward(); // when there is no time info, mark each node with the length of the longest path from the initial node to it; // use this information for initializing the clusters and constraining the merging void put_max_dist(const Prons& P); friend ostream& operator << (ostream& os, const Lattice& lat); bool less_nodes(NodeId id1, NodeId id2, unsigned MAX_DIST); private: LatticeInfo info; /* the information in the header */ vector<Node> nodes; /* vector[0..info.no_nodes-1] of nodes */ vector<Link> links; /* vector[0..info.no_links-1] of links */ LnProb total_prob; /* the sum of the posteriors of all the paths in the lattice */ bool time_info; /* 1 if the lattice has time information */ // find the children of all the nodes void fill_outgoing_links(); // sort the links in topological order; needed for the Forward-Backward step void do_TopSort(); // visit the graph in the depth-first manner void DFS_visit(int nodeid, IdsList& l, vector<int>& color); }; #endif <file_sep>/archive_s3/s3.2/src/gautest.c /* * gautest.c -- Gaussian density tests * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 05-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "cont_mgau.h" #include "feat.h" #include "corpus.h" #include "logs3.h" #include "s3types.h" typedef struct { mgau_model_t *g; feat_t *fcb; float32 ***feat; char *cepdir; FILE *logfp; } kb_t; static int32 comp[] = { 24, 25, 0, 12, 1, 13, -1, }; static void process_utt (void *data, char *uttfile, int32 sf, int32 ef, char *uttid) { kb_t *kb; int32 nf, bs, BS, BM; static int32 *score = NULL; float64 d; int32 f, s, c, i; kb = (kb_t *) data; if (! score) score = (int32 *) ckd_calloc (mgau_max_comp (kb->g), sizeof(int32)); nf = feat_s2mfc2feat (kb->fcb, uttfile, kb->cepdir, sf, ef, kb->feat, S3_MAX_FRAMES); for (f = 0; f < nf; f++) { BS = MAX_NEG_INT32; BM = 0; for (s = 0; s < mgau_n_mgau(kb->g); s++) { if (mgau_n_comp (kb->g, s) > 0) { bs = mgau_comp_eval (kb->g, s, kb->feat[f][0], score); if (BS < bs) { BS = bs; BM = s; } } } for (s = 0; s < mgau_n_mgau(kb->g); s++) { if (mgau_n_comp (kb->g, s) <= 0) continue; bs = mgau_comp_eval (kb->g, s, kb->feat[f][0], score); fprintf (kb->logfp, "%6d (f), %5d (m), %5d (BM), %11d (BS), %11d (bs), %11d (bs-BS)\n", f, s, BM, BS, bs, bs-BS); for (c = 0; c < mgau_n_comp (kb->g, s); c++) { fprintf (kb->logfp, "\t%3d %11d", c, score[c]-bs); for (i = 0; comp[i] >= 0; i++) { d = kb->feat[f][0][comp[i]] - kb->g->mgau[s].mean[c][comp[i]]; if (d < 0) d = -d; fprintf (kb->logfp, " %7.3f", d); } fprintf (kb->logfp, "\n"); } fprintf (kb->logfp, "\n"); } } } static void usagemsg (char *pgm) { E_INFO("Usage: %s hmmdir cepdir ctlfile\n", pgm); exit(0); } main (int32 argc, char *argv[]) { char mean[8192], var[8192], mixw[8192]; char *hmmdir, *ctlfile; float32 logbase; kb_t kb; if (argc != 4) usagemsg (argv[0]); logbase = (float32)1.0003; logs3_init (logbase); hmmdir = argv[1]; sprintf (mean, "%s/mean", hmmdir); sprintf (var, "%s/var", hmmdir); sprintf (mixw, "%s/mixw", hmmdir); kb.g = mgau_init (mean, var, 0.0001 /* varfloor */, mixw, 0.0000001, TRUE); kb.fcb = feat_init ("s3_1x39", "current", "no", "max"); kb.feat = feat_array_alloc(kb.fcb, S3_MAX_FRAMES); kb.cepdir = argv[2]; kb.logfp = stdout; ctlfile = argv[3]; ctl_process (ctlfile, 0, 10000000, process_utt, (void *)(&kb)); } <file_sep>/pocketsphinx/src/libpocketsphinx/vithist.h /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 1999-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * vithist.h -- Viterbi history * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * $Log$ * Revision 1.1 2006/04/05 20:27:30 dhdfu * A Great Reorganzation of header files and executables * * Revision 1.12 2006/02/23 16:56:13 arthchan2003 * Merged from the branch SPHINX3_5_2_RCI_IRII_BRANCH * 1, Split latticehist_t from flat_fwd.c to here. * 2, Introduced vithist_entry_cp. This is much better than the direct * copy we have been using. (Which could cause memory problem easily) * * Revision 1.11.4.9 2006/01/16 18:11:39 arthchan2003 * 1, Important Bug fixes, a local pointer is used when realloc is needed. This causes invalid writing of the memory, 2, Acoustic scores of the last segment in IBM lattice generation couldn't be found in the past. Now, this could be handled by the optional acoustic scores in the node of lattice. Application code is not yet checked-in * * Revision 1.11.4.8 2005/11/17 06:46:02 arthchan2003 * 3 changes. 1, Code was added for full triphone implementation, not yet working. 2, Senone scale is removed from vithist table. This was a bug introduced during some fixes in CALO. * * Revision 1.11.4.7 2005/10/17 04:58:30 arthchan2003 * vithist.c is the true source of memory leaks in the past for full cwtp expansion. There are two changes made to avoid this happen, 1, instead of using ve->rc_info as the indicator whether something should be done, used a flag bFullExpand to control it. 2, avoid doing direct C-struct copy (like *ve = *tve), it becomes the reason of why memory are leaked and why the code goes wrong. * * Revision 1.11.4.6 2005/10/07 20:05:05 arthchan2003 * When rescoring in full triphone expansion, the code should use the score for the word end with corret right context. * * Revision 1.11.4.5 2005/09/26 06:37:33 arthchan2003 * Before anyone get hurt, quickly change back to using SINGLE_RC_HISTORY. * * Revision 1.11.4.4 2005/09/25 19:23:55 arthchan2003 * 1, Added arguments for turning on/off LTS rules. 2, Added arguments for turning on/off composite triphones. 3, Moved dict2pid deallocation back to dict2pid. 4, Tidying up the clean up code. * * Revision 1.11.4.3 2005/09/11 03:00:15 arthchan2003 * All lattice-related functions are not incorporated into vithist. So-called "lattice" is essentially the predecessor of vithist_t and fsg_history_t. Later when vithist_t support by right context score and history. It should replace both of them. * * Revision 1.11.4.2 2005/07/26 02:20:39 arthchan2003 * merged hyp_t with srch_hyp_t. * * Revision 1.11.4.1 2005/07/04 07:25:22 arthchan2003 * Added vithist_entry_display and vh_lmstate_display in vithist. * * Revision 1.11 2005/06/22 02:47:35 arthchan2003 * 1, Added reporting flag for vithist_init. 2, Added a flag to allow using words other than silence to be the last word for backtracing. 3, Fixed doxygen documentation. 4, Add keyword. * * Revision 1.10 2005/06/16 04:59:10 archan * Sphinx3 to s3.generic, a gentle-refactored version of Dave's change in senone scale. * * Revision 1.9 2005/06/13 04:02:59 archan * Fixed most doxygen-style documentation under libs3decoder. * * Revision 1.8 2005/05/26 00:46:59 archan * Added functionalities that such that <sil> will not be inserted at the end of the utterance. * * Revision 1.7 2005/04/25 23:53:35 archan * 1, Some minor modification of vithist_t, vithist_rescore can now support optional LM rescoring, vithist also has its own reporting routine. A new argument -lmrescore is also added in decode and livepretend. This can switch on and off the rescoring procedure. 2, I am reaching the final difficulty of mode 5 implementation. That is, to implement an algorithm which dynamically decide which tree copies should be entered. However, stuffs like score propagation in the leave nodes and non-leaves nodes are already done. 3, As briefly mentioned in 2, implementation of rescoring , which used to happened at leave nodes are now separated. The current implementation is not the most clever one. Wish I have time to change it before check-in to the canonical. * * Revision 1.6 2005/04/21 23:50:26 archan * Some more refactoring on the how reporting of structures inside kbcore_t is done, it is now 50% nice. Also added class-based LM test case into test-decode.sh.in. At this moment, everything in search mode 5 is already done. It is time to test the idea whether the search can really be used. * * Revision 1.5 2005/04/20 03:46:30 archan * factor dag header writer into vithist.[ch], do the corresponding change for lm_t * * Revision 1.4 2005/03/30 01:22:47 archan * Fixed mistakes in last updates. Add * * * 20.Apr.2001 RAH (<EMAIL>, <EMAIL>) * Added vithist_free() to free allocated memory * * 30-Sep-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added vithist_entry_t.ascr. * * 13-Aug-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added maxwpf handling. * * 24-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_VITHIST_H_ #define _S3_VITHIST_H_ #include <stdio.h> #include <ngram_model.h> #include <cmd_ln.h> #include <logmath.h> #include <glist.h> #include "s3types.h" #include "fillpen.h" #include "s3dict.h" #include "dict2pid.h" /** \file vithist.h * * \brief Viterbi history structures. Mainly vithist_t, also its * slightly older brother latticehist_t. They are respectively used by * decode (mode 4 and 5) and decode_anytopo (mode 3). The curent * arrangement is temporary. */ #ifdef __cplusplus extern "C" { #endif #if 0 } /* Fool Emacs into not indenting things. */ #endif /** * LM state. Depending on type of LM (word-ngram, class-ngram, FSG, etc.), the contents * of LM state will vary. Accommodate them with a union. For now, only trigram LM in it. * (Not completely thought out; some of this might have to change later.) */ typedef union vh_lmstate_u { struct { /** * LANGUAGE MODEL word IDs. lwid[0] is the current word, * lwid[1] is the previous word. */ int32 lwid[2]; } lm3g; } vh_lmstate_t; typedef struct backpointer_s { int32 score; int32 pred; } backpointer_t; /** * Viterbi history entry. */ typedef struct { backpointer_t path; /**< Predecessor word and best path score including it */ vh_lmstate_t lmstate; /**< LM state */ s3wid_t wid; /**< <em>dictionary</em> word ID; exact word that just exited */ s3frmid_t sf, ef; /**< Start and end frames for this entry */ int32 ascr; /**< Acoustic score for this node */ int32 lscr; /**< LM score for this node, given its Viterbi history */ int16 type; /**< >=0: regular n-gram word; <0: filler word entry */ int16 valid; /**< Whether it should be a valid history for LM rescoring */ backpointer_t *rc; /**< Individual score/history for different right contexts */ int32 n_rc; /**< Number of right contexts */ } vithist_entry_t; /** Return the word ID of an entry */ #define vithist_entry_wid(ve) ((ve)->wid) /** Return the starting frame of an entry */ #define vithist_entry_sf(ve) ((ve)->sf) /** Return the ending frame of an entry */ #define vithist_entry_ef(ve) ((ve)->ef) /** Return the acoustic score of an entry */ #define vithist_entry_ascr(ve) ((ve)->ascr) /** Return the language score of an entry */ #define vithist_entry_lscr(ve) ((ve)->lscr) /** Return the total score of an entry */ #define vithist_entry_score(ve) ((ve)->path.score) #define vithist_entry_pred(ve) ((ve)->path.pred) #define vithist_entry_valid(ve) ((ve)->valid) /** * \struct vh_lms2vh_t * In each frame, there are several word exits. There can be several exit instances of the * same word, corresponding to different LM histories. Generally, each exit is associated * with an LM state. We only need to retain the best entry for each LM state. The following * structure is for this purpose. * For all exits in the current frame, all n-word histories (assuming an N-gram LM) ending in * a given word are arranged in a tree, with the most recent history word at the root. The * leaves of the tree point to the (current best) vithist entry with that history in the * current frame. */ typedef struct { /**< Mapping from LM state to vithist entry */ int32 state; /**< (Part of) the state information */ int32 vhid; /**< Associated vithist ID (only for leaf nodes) */ vithist_entry_t *ve; /**< Entry ptr corresponding to vhid (only for leaf nodes) */ glist_t children; /**< Children of this node in the LM state tree; data.ptr of type (vh_lms2vh_t *) */ } vh_lms2vh_t; /** * \struct vithist_t * Memory management of Viterbi history entries done in blocks. Initially, one block of * VITHIST_BLKSIZE entries allocated. If exhausted, another block allocated, and so on. * So we can have several discontiguous blocks allocated. Entries are identified by a * global, running sequence no. */ typedef struct { vithist_entry_t **entry; /**< entry[i][j]= j-th entry in the i-th block allocated */ int32 *frame_start; /**< For each frame, the first vithist ID in that frame; (the last is just before the first of the next frame) */ int32 n_entry; /**< Total #entries used (generates global seq no. or ID) */ int32 n_frm; /**< No. of frames processed so far in this utterance */ int32 n_ci; /**< No. of CI phones */ int32 bghist; /**< If TRUE (bigram-mode) only one entry/word/frame; otherwise multiple entries allowed, one per distinct LM state */ int32 wbeam; /**< Pruning beamwidth */ int32 *bestscore; /**< Best word exit score in each frame */ int32 *bestvh; /**< Vithist entry ID with the best exit score in each frame */ vh_lms2vh_t **lms2vh_root; /**< lms2vh[w]= Root of LM states ending in w in current frame */ glist_t lwidlist; /**< List of LM word IDs with entries in lms2vh_root */ } vithist_t; #define VITHIST_BLKSIZE 16384 /* (1 << 14) */ #define VITHIST_MAXBLKS 256 #define VITHIST_ID2BLK(i) ((i) >> 14) #define VITHIST_ID2BLKOFFSET(i) ((i) & 0x00003fff) /* 14 LSB */ /** Access macros; not meant for arbitrary use */ /** Return a pointer to the entry with the given ID. */ #define vithist_id2entry(vh,id) ((vh)->entry[VITHIST_ID2BLK(id)] + VITHIST_ID2BLKOFFSET(id)) /** Return the number of entry in the Viterbi history */ #define vithist_n_entry(vh) ((vh)->n_entry) /** Return the best score of the Viterbi history */ #define vithist_bestscore(vh) ((vh)->bestscore) /** Return the best viterbi history entry ID of the Viterbi history */ #define vithist_bestvh(vh) ((vh)->bestvh) /** Return lms2vh */ #define vithist_lms2vh_root(vh,w) ((vh)->lms2vh_root[w]) /** Return the language word ID list */ #define vithist_lwidlist(vh) ((vh)->lwidlist) /** Return the first entry for the frame f */ #define vithist_first_entry(vh,f) ((vh)->frame_start[f]) /** Return the last entry for the frame f */ #define vithist_last_entry(vh,f) ((vh)->frame_start[f+1] - 1) /** * One-time intialization: Allocate and return an initially empty * vithist module * @return An initialized vithist_t */ vithist_t *vithist_init(int32 lm_nword, /**< Number of words in <em>language model</em> */ int32 n_ci, /**< Number of CI phones */ int32 wbeam, /**< Word exit beam width */ int32 bghist, /**< If only bigram history is used */ int32 report /**< Whether to report the progress */ ); /** * Invoked at the beginning of each utterance; vithist initialized with a root <s> entry. * @return Vithist ID of the root <s> entry. */ int32 vithist_utt_begin(vithist_t *vh, /**< In: a Viterbi history data structure */ int32 wid, /**< In: <em>dictionary</em> ID of start word */ int32 lwid /**< In: <em>language model</em> ID of start word */ ); /** * Invoked at the end of each utterance; append a final </s> entry that results in the best * path score (i.e., LM including LM transition to </s>). * Return the ID of the appended entry if successful, -ve if error (empty utterance). */ int32 vithist_utt_end(vithist_t *vh, /**< In: a Viterbi history data structure*/ ngram_model_t *lm, s3dict_t *dict, dict2pid_t *dict2pid, fillpen_t *fp ); /** * Invoked at the end of each block of a live decode. * Returns viterbi histories of partial decodes */ int32 vithist_partialutt_end(vithist_t *vh, /**< In: a Viterbi history data structure*/ ngram_model_t *lm, s3dict_t *dict ); /* Invoked at the end of each utterance to clear up and deallocate space */ void vithist_utt_reset(vithist_t *vh /**< In: a Viterbi history data structure*/ ); /** * Viterbi backtrace. Return value: List of hyp_t pointer entries for the individual word * segments. Caller responsible for freeing the list. */ glist_t vithist_backtrace(vithist_t *vh, /**< In: a Viterbi history data structure*/ int32 id, /**< ID from which to begin backtrace */ s3dict_t *dict /**< a dictionary for look up the ci phone of a word*/ ); /** * Add an entry to the Viterbi history table without rescoring. Any * entry having the same LM state will be replaced with the one given. */ void vithist_enter(vithist_t * vh, /**< The history table */ s3dict_t *dict, /**< Dictionary */ dict2pid_t *dict2pid, /**< Context table mapping thing */ vithist_entry_t * tve, /**< an input vithist element */ int32 comp_rc /**< a compressed rc. If it is the actual rc, it won't work. FIXME: WHAT DOES THIS MEAN?!!?!? */ ); /** * Like vithist_enter, but LM-rescore this word exit wrt all histories that ended at the * same time as the given, tentative pred. Create a new vithist entry for each predecessor * (but, of course, only the best for each distinct LM state will be retained; see above). * * ARCHAN: Precisely speaking, it is a full trigram rescoring. */ void vithist_rescore(vithist_t *vh, /**< In: a Viterbi history data structure*/ ngram_model_t *lm, /**< In: Language model */ s3dict_t *dict, /**< In: Dictionary */ dict2pid_t *dict2pid,/**< Context table mapping thing */ fillpen_t *fp, /**< In: Filler penalty list */ s3wid_t wid, /**< In: a <em>dictionary</em> word ID */ int32 ef, /**< In: End frame for this word instance */ int32 score, /**< In: Does not include LM score for this entry */ int32 pred, /**< In: Tentative predecessor */ int32 type, /**< In: Type of lexical tree */ int32 rc /**< In: The compressed rc. So if you use the actual rc, it doesn't work. */ ); /** Invoked at the end of each frame */ void vithist_frame_windup(vithist_t *vh, /**< In/Out: Vithist module to be updated */ int32 frm, /**< In: Frame in which being invoked */ FILE *fp, /**< In: If not NULL, dump vithist entries this frame to the file (for debugging) */ ngram_model_t *lm, /**< In: Language model */ s3dict_t *dict /**< In: Dictionary */ ); /** * Mark up to maxwpf best words, and variants within beam of best frame score as valid, * and the remaining as invalid. */ void vithist_prune(vithist_t *vh, /**< In: a Viterbi history data structure*/ s3dict_t *dict, /**< In: Dictionary, for distinguishing filler words */ int32 frm, /**< In: Frame in which being invoked */ int32 maxwpf, /**< In: Max unique words per frame to be kept valid */ int32 maxhist, /**< In: Max histories to maintain per frame */ int32 beam /**< In: Entry score must be >= frame bestscore+beam */ ); /** * Dump the Viterbi history data to the given file (for debugging/diagnostics). */ void vithist_dump(vithist_t *vh, /**< In: a Viterbi history data structure */ int32 frm, /**< In: If >= 0, print only entries made in this frame, otherwise print all entries */ ngram_model_t *lm, /**< In: Language model */ s3dict_t *dict, /**< In: Dictionary */ FILE *fp /**< Out: File to be written */ ); #if 0 /** * Build a word graph (DAG) from Viterbi history. */ dag_t *vithist_dag_build(vithist_t * vh, glist_t hyp, s3dict_t * dict, int32 endid, cmd_ln_t *config, logmath_t *logmath); #endif /** * Free a Viterbi history data structure */ void vithist_free(vithist_t *vh /**< In: a Viterbi history data structure */ ); /** * Report a Viterbi history architecture */ void vithist_report(vithist_t *vh /**< In: a Viterbi history data structure */ ); /** * Display the lmstate of an entry. */ void vh_lmstate_display(vh_lmstate_t *vhl, /**< In: An lmstate data structure */ s3dict_t *dict /**< In: If specified, the word string of lm IDs would also be translated */ ); /** * Display the vithist_entry structure. */ void vithist_entry_display(vithist_entry_t *ve, /**< In: An entry of vithist */ s3dict_t* dict /**< In: If specified, the word string of lm IDs would also be translated */ ); #if 0 { /* Stop indent from complaining */ #endif #ifdef __cplusplus } #endif #endif <file_sep>/archive_s3/s3.0/pgm/misc/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../Makefile.defines VPATH = .:.. AUXOBJ = ../../libmain/$(MACHINE)/mdef.o ../../libmain/$(MACHINE)/dict.o ../../libmain/$(MACHINE)/misc.o MDEFOBJ = ../../../src/libmain/$(MACHINE)/mdef.o lat2nodes : lat2nodes.o $(CC) $(S3DEBUG) $(CFLAGS) -o lat2nodes lat2nodes.o $(AUXOBJ) -lutil -lm cepwinvar : cepwinvar.o $(CC) $(S3DEBUG) $(CFLAGS) -o cepwinvar cepwinvar.o $(AUXOBJ) -lfeat -lio -lutil -lm cepdx : cepdx.o $(CC) $(S3DEBUG) $(CFLAGS) -o cepdx cepdx.o $(AUXOBJ) -lfeat -lio -lutil -lm mfc : mfc.o $(CC) $(S3DEBUG) $(CFLAGS) -o mfc mfc.o $(AUXOBJ) -lio -lutil -lm proncount : proncount.o $(CC) $(S3DEBUG) $(CFLAGS) -o proncount proncount.o $(AUXOBJ) -lutil -lm pron : pron.o $(CC) $(S3DEBUG) $(CFLAGS) -o pron pron.o $(AUXOBJ) -lutil -lm erreg : erreg.o $(CC) $(S3DEBUG) $(CFLAGS) -o erreg erreg.o $(AUXOBJ) -lutil -lm test : test.o $(CC) $(S3DEBUG) $(CFLAGS) -o test test.o $(AUXOBJ) -lfeat -lio -lutil -lm testvq : testvq.o $(CC) $(S3DEBUG) $(CFLAGS) -o testvq testvq.o $(AUXOBJ) -lutil -lm testvq-int32 : testvq-int32.o $(CC) $(S3DEBUG) $(CFLAGS) -o testvq-int32 testvq-int32.o $(AUXOBJ) -lutil -lm cepdist-var: cepdist-var.o $(CC) $(S3DEBUG) $(CFLAGS) -o cepdist-var cepdist-var.o $(AUXOBJ) -lfeat -lio -lutil -lm cepdist: cepdist.o $(CC) $(S3DEBUG) $(CFLAGS) -o cepdist cepdist.o $(AUXOBJ) -lfeat -lio -lutil -lm dpalign: dag.o dp.o dpalign.o line2wid.o $(CC) $(CFLAGS) -o dpalign dpalign.o dp.o dag.o line2wid.o $(AUXOBJ) -lutil allpalign: allpalign.o dag.o dp.o $(CC) $(CFLAGS) -o allpalign allpalign.o dp.o dag.o $(AUXOBJ) -lutil pronerr: pronerr.o line2wid.o $(CC) $(CFLAGS) -o pronerr pronerr.o line2wid.o $(AUXOBJ) -lutil pronerralign: pronerralign.o dp.o dag.o $(CC) $(CFLAGS) -o pronerralign pronerralign.o dp.o dag.o $(AUXOBJ) -lutil segnbesterr: segnbesterr.o dp.o dag.o line2wid.o $(CC) $(CFLAGS) -o segnbesterr segnbesterr.o dp.o dag.o line2wid.o $(AUXOBJ) -lutil nbesterr: nbesterr.o dp.o dag.o line2wid.o $(CC) $(CFLAGS) -o nbesterr nbesterr.o dp.o dag.o line2wid.o $(AUXOBJ) -lutil v8seg2ascii: v8seg2ascii.o $(CC) $(CFLAGS) -o v8seg2ascii v8seg2ascii.o $(MDEFOBJ) -lio -lutil cepdist-allp: cepdist-allp.o $(CC) $(CFLAGS) -o cepdist-allp cepdist-allp.o $(AUXOBJ) -lfeat -lio -lutil newlc: newlc.o $(CC) $(CFLAGS) -o newlc newlc.o -lutil lc: lc.o $(CC) $(CFLAGS) -o lc lc.o -lutil newrc: newrc.o $(CC) $(CFLAGS) -o newrc newrc.o -lutil rc: rc.o $(CC) $(CFLAGS) -o rc rc.o -lutil clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/archive_s3/s3/src/libs3decoder/new_fe.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _NEW_FE_H_ #define _NEW_FE_H_ #define int32 int #define int16 short typedef struct{ float SAMPLING_RATE; int32 FRAME_RATE; float WINDOW_LENGTH; int32 FB_TYPE; int32 NUM_CEPSTRA; int32 NUM_FILTERS; int32 FFT_SIZE; float LOWER_FILT_FREQ; float UPPER_FILT_FREQ; float PRE_EMPHASIS_ALPHA; char *wavfile; char *cepfile; char *ctlfile; char *wavdir; char *cepdir; char *wavext; char *cepext; int32 input_format; int32 is_batch; int32 is_single; int32 blocksize; int32 verbose; } param_t; typedef struct{ float sampling_rate; int32 num_cepstra; int32 num_filters; int32 fft_size; float lower_filt_freq; float upper_filt_freq; float **filter_coeffs; float **mel_cosine; float *left_apex; int32 *width; }melfb_t; typedef struct{ float SAMPLING_RATE; int32 FRAME_RATE; int32 FRAME_SHIFT; float WINDOW_LENGTH; int32 FRAME_SIZE; int32 FFT_SIZE; int32 FB_TYPE; int32 NUM_CEPSTRA; float PRE_EMPHASIS_ALPHA; int16 *OVERFLOW_SAMPS; int32 NUM_OVERFLOW_SAMPS; melfb_t *MEL_FB; int32 START_FLAG; int16 PRIOR; double *HAMMING_WINDOW; } fe_t; #define MEL_SCALE 1 #define LOG_LINEAR 2 /* Default values */ #define DEFAULT_SAMPLING_RATE 16000.0 #define DEFAULT_FRAME_RATE 100 #define DEFAULT_FRAME_SHIFT 160 #define DEFAULT_WINDOW_LENGTH 0.025625 #define DEFAULT_FFT_SIZE 512 #define DEFAULT_FB_TYPE MEL_SCALE #define DEFAULT_NUM_CEPSTRA 13 #define DEFAULT_NUM_FILTERS 40 #define DEFAULT_LOWER_FILT_FREQ 133.33334 #define DEFAULT_UPPER_FILT_FREQ 6855.4976 #define DEFAULT_PRE_EMPHASIS_ALPHA 0.97 #define DEFAULT_START_FLAG 0 #define BB_SAMPLING_RATE 16000 #define DEFAULT_BB_FRAME_SHIFT 160 #define DEFAULT_BB_NUM_FILTERS 40 #define DEFAULT_BB_LOWER_FILT_FREQ 133.33334 #define DEFAULT_BB_UPPER_FILT_FREQ 6855.4976 #define NB_SAMPLING_RATE 8000 #define DEFAULT_NB_FRAME_SHIFT 80 #define DEFAULT_NB_NUM_FILTERS 31 #define DEFAULT_NB_LOWER_FILT_FREQ 200 #define DEFAULT_NB_UPPER_FILT_FREQ 3500 #define DEFAULT_BLOCKSIZE 200000 /* Functions */ fe_t *fe_init(param_t *P); int32 fe_start_utt(fe_t *FE); int32 fe_end_utt(fe_t *FE, float *cepvector); int32 fe_close(fe_t *FE); int32 fe_process_utt(fe_t *FE, int16 *spch, int32 nsamps, float ***cep_block); int32 fe_process(fe_t *FE, int16 *spch, int32 nsamps, float ***cep_block); #endif <file_sep>/jsgfparser/main.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2007 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <hash_table.h> #include <err.h> #include <string.h> #include "jsgf.h" static int write_fsg(jsgf_t *grammar, const char *name) { glist_t rules; int32 nrules; gnode_t *gn; rules = hash_table_tolist(grammar->rules, &nrules); for (gn = rules; gn; gn = gnode_next(gn)) { hash_entry_t *he = gnode_ptr(gn); jsgf_rule_t *rule = hash_entry_val(he); if ((name == NULL && rule->public) || (name && 0 == strncmp(rule->name + 1, name, strlen(rule->name) - 2))) { jsgf_write_fsg(grammar, rule, stdout); break; } } glist_free(rules); return 0; } int main(int argc, char *argv[]) { int yyrv; jsgf_t *jsgf; jsgf = jsgf_parse_file(argc > 1 ? argv[1] : NULL, NULL); if (jsgf == NULL) { return 1; } write_fsg(jsgf, argc > 2 ? argv[2] : NULL); return yyrv; } <file_sep>/pocketsphinx/src/libpocketsphinx/fsg2_search.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file fsg2_search.h * @brief Rewritten FSG search * @author <NAME> <<EMAIL>> */ #include <strfuncs.h> #include "fsg2_search.h" static ps_searchfuncs_t fsg2_funcs = { /* name: */ "fsg2", /* start: */ fsg2_search_start, /* step: */ fsg2_search_step, /* finish: */ fsg2_search_finish, /* reinit: */ fsg2_search_reinit, /* free: */ fsg2_search_free, /* lattice: */ NULL, /* hyp: */ fsg2_search_hyp, /* prob: */ NULL, /* seg_iter: */ NULL }; ps_search_t * fsg2_search_init(cmd_ln_t *config, acmod_t *acmod, dict_t *dict, dict2pid_t *d2p) { fsg2_search_t *fs; char const *path; fs = ckd_calloc(1, sizeof(*fs)); ps_search_init(ps_search_base(fs), &fsg2_funcs, config, acmod, dict, d2p); /* Initialize HMM context. */ fs->hmmctx = hmm_context_init(bin_mdef_n_emit_state(acmod->mdef), acmod->tmat->tp, NULL, acmod->mdef->sseq); if (fs->hmmctx == NULL) { ps_search_free(ps_search_base(fs)); return NULL; } /* Load an FSG if one was specified in config */ if ((path = cmd_ln_str_r(config, "-fsg"))) { if ((fs->fsg = fsg_model_readfile(path, acmod->lmath, cmd_ln_float32_r(config, "-lw"))) == NULL) goto error_out; if (fsg2_search_reinit(ps_search_base(fs), ps_search_dict(fs), ps_search_dict2pid(fs)) < 0) goto error_out; } /* Or load a JSGF grammar */ else if ((path = cmd_ln_str_r(config, "-jsgf"))) { jsgf_rule_t *rule; char const *toprule; if ((fs->jsgf = jsgf_parse_file(path, NULL)) == NULL) goto error_out; rule = NULL; /* Take the -toprule if specified. */ if ((toprule = cmd_ln_str_r(config, "-toprule"))) { char *anglerule; anglerule = string_join("<", toprule, ">", NULL); rule = jsgf_get_rule(fs->jsgf, anglerule); ckd_free(anglerule); if (rule == NULL) { E_ERROR("Start rule %s not found\n", toprule); goto error_out; } } /* Otherwise, take the first public rule. */ else { jsgf_rule_iter_t *itor; for (itor = jsgf_rule_iter(fs->jsgf); itor; itor = jsgf_rule_iter_next(itor)) { rule = jsgf_rule_iter_rule(itor); if (jsgf_rule_public(rule)) break; } if (rule == NULL) { E_ERROR("No public rules found in %s\n", path); goto error_out; } } fs->fsg = jsgf_build_fsg(fs->jsgf, rule, acmod->lmath, cmd_ln_float32_r(config, "-lw")); if (fsg2_search_reinit(ps_search_base(fs), ps_search_dict(fs), ps_search_dict2pid(fs)) < 0) goto error_out; } return ps_search_base(fs); error_out: fsg2_search_free(ps_search_base(fs)); return NULL; } void fsg2_search_free(ps_search_t *search) { fsg2_search_t *fs = (fsg2_search_t *)search; ps_search_deinit(search); glextree_free(fs->lextree); tokentree_free(fs->toktree); hmm_context_free(fs->hmmctx); if (fs->vocab) hash_table_free(fs->vocab); fsg_model_free(fs->fsg); jsgf_grammar_free(fs->jsgf); ckd_free(fs); } static int fsg2_search_wfilter(glextree_t *tree, int32 wid, void *udata) { fsg2_search_t *fs = (fsg2_search_t *)udata; int32 wid2; if (hash_table_lookup_int32(fs->vocab, dict_basestr(ps_search_dict(fs), wid), &wid2) < 0) return FALSE; return TRUE; } int fsg2_search_reinit(ps_search_t *s, dict_t *dict, dict2pid_t *d2p) { fsg2_search_t *fs = (fsg2_search_t *)s; int i; /* Build active vocabulary. */ if (fs->vocab) hash_table_free(fs->vocab); fs->vocab = hash_table_new(fsg_model_n_word(fs->fsg), HASH_CASE_YES); for (i = 0; i < fsg_model_n_word(fs->fsg); ++i) (void)hash_table_enter_int32(fs->vocab, fsg_model_word_str(fs->fsg, i), i); /* (re-)Initialize lexicon tree. */ fs->lextree = glextree_build(fs->hmmctx, dict, d2p, fsg2_search_wfilter, (void *)fs); /* Initialize token tree. */ tokentree_free(fs->toktree); fs->toktree = tokentree_init(); s->dict = dict; s->d2p = d2p; return 0; } int fsg2_search_start(ps_search_t *s) { fsg2_search_t *fs = (fsg2_search_t *)s; /* Reset HMMs and tokens. */ glextree_clear(fs->lextree); tokentree_clear(fs->toktree); /* Reset score renormalization information. */ /* Follow epsilon transitions out of start state to populate * initial active state list. */ return 0; } int fsg2_search_step(ps_search_t *search, int frame_idx) { return 0; } int fsg2_search_finish(ps_search_t *search) { return 0; } char const * fsg2_search_hyp(ps_search_t *search, int32 *out_score) { return "go forward ten meters"; } <file_sep>/SphinxTrain/python/cmusphinx/test_s3dict.py #!/usr/bin/env python import s3dict import unittest import os import sys class TestS3Dict(unittest.TestCase): def setUp(self): self.basedir = os.path.dirname(__file__) def testRead(self): foodict = s3dict.open(os.path.join(self.basedir, "foo.dict")) self.assert_('AH' in foodict.phoneset) self.assertEquals(foodict.get_phones('A'), ['AH']) self.assertEquals(foodict.get_alt_phones('A', 2), ['EY']) self.assertEquals(foodict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) try: foo = foodict.get_phones('QRXG') print foo except KeyError: pass # Expected fail else: self.fail() try: foo = foodict.get_alt_phones('A',3) except IndexError: pass # Expected fail else: self.fail() try: foo = foodict.get_alt_phones('!@#$!@',3) except KeyError: pass # Expected fail else: self.fail() self.assertEquals(foodict['A'], ['AH']) self.assertEquals(foodict['A',2], ['EY']) self.assertEquals(foodict['A(2)'], ['EY']) self.assertEquals(foodict['ZSWANG'], ['S', 'W', 'AE', 'NG']) def testCreate(self): mydict = s3dict.S3Dict() mydict.set_phones('A', ['AH']) mydict.add_alt_phones('A', ['EY']) mydict.set_phones('ZSWANG', ['S', 'W', 'AE', 'NG']) mydict.set_alt_phones('A', 2, ['EY']) try: mydict.set_alt_phones('A', 5, ['AX']) except IndexError: pass # Expected fail else: self.fail() self.assertEquals(mydict.get_phones('A'), ['AH']) self.assertEquals(mydict.get_alt_phones('A', 2), ['EY']) self.assertEquals(mydict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) mydict.set_alt_phones('A', 2, ['AA']) self.assertEquals(mydict.get_alt_phones('A', 2), ['AA']) self.assert_('ZSWANG' in mydict) mydict.del_phones('ZSWANG') self.assert_('ZSWANG' not in mydict) self.assert_('NG' not in mydict.phoneset) def testUnion(self): foodict = s3dict.open(os.path.join(self.basedir, "foo.dict")) bardict = s3dict.open(os.path.join(self.basedir, "bar.dict")) bazdict = s3dict.union(foodict, bardict) self.assertEquals(foodict['ACTUALLY'], bazdict['ACTUALLY']) self.assert_('ABANDONED' in bazdict) self.assert_('ZONES' in bazdict) self.assert_('ZSWANG' in bazdict) if __name__ == '__main__': unittest.main() <file_sep>/archive_s3/s3.0/Makefile # # Copyright (c) 1997 Carnegie Mellon University. ALL RIGHTS RESERVED. # # HISTORY # # 23-Nov-97 <NAME> (<EMAIL>) at Carnegie Mellon University. # Created. # # Before building: # setenv MACHINE alpha (or sun4, hp700_ux, linux, etc. as appropriate) # # Create the following directories if not already existing: # lib/$(MACHINE), # bin/$(MACHINE), # src/libio/$(MACHINE), # src/libfeat/$(MACHINE), # src/libmisc/$(MACHINE), # src/libmain/$(MACHINE), # This Makefile isn't foolproof; it may not ELIMINATE the need for manually # determining dependencies, especially on updates to libraries and header files. # When in doubt, make the necessary -clean targets first before the -install ones. # (The -clean targets basically remove backup copies, *.o, *.a files.) MAKE = make # Machine-specific flags for "make" # alpha_MKFLAGS = alpha_osf1_MKFLAGS = $(alpha_MKFLAGS) linux_MKFLAGS = -I.. sun4_MKFLAGS = # MKFLAGS = ${${MACHINE}_MKFLAGS} # Libraries (Note that src/libutil is a symbolic link to an s3-independent libutil): # and is not maintained here. lib-install: (cd src/libio/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) (cd src/libfeat/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) (cd src/libmisc/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) (cd src/libmain/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) lib-clean: (cd src/libio/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) (cd src/libfeat/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) (cd src/libmisc/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) (cd src/libmain/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) lib-src-clean: (cd src/libio; $(MAKE) clean) (cd src/libfeat; $(MAKE) clean) (cd src/libmisc; $(MAKE) clean) (cd src/libmain; $(MAKE) clean) # Applications: # Time alignment (aka forced alignment) # timealign-install: lib-install (cd pgm/timealign/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) timealign-clean: (cd pgm/timealign/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) timealign-src-clean: (cd pgm/timealign; $(MAKE) clean) # Hyp extraction from multiple hypotheses files. # hypext-install: lib-install (cd pgm/hypext/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile install) hypext-clean: (cd pgm/hypext/$(MACHINE); $(MAKE) $(MKFLAGS) -f ../Makefile clean) hypext-src-clean: (cd pgm/hypext; $(MAKE) clean) # All: install: timealign-install \ hypext-install clean: timealign-clean \ hypext-clean \ lib-clean src-clean: timealign-src-clean \ hypext-src-clean \ lib-src-clean <file_sep>/archive_s3/s3.0/pgm/misc/cepwinvar.c /* * cepwinvar.c -- Variance of a sliding window on a cepstrum stream. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 15-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libfeat/libfeat.h> #include <s3.h> static char *cepdir; static int32 cepsize; static char uttid[4096]; static float32 *var; /* Feature dimension variances */ typedef struct { char p[16]; int32 sf, nf; } pseg_t; static pseg_t *pseg; static int32 n_pseg; static void load_pseg (char *line) { char *lp, wd[1024]; int32 k, len, sf, nf; n_pseg = 0; lp = line; while ((k = sscanf (lp, "%s %d %d%n", wd, &sf, &nf, &len)) == 3) { lp += len; strcpy (pseg[n_pseg].p, wd); pseg[n_pseg].sf = sf; pseg[n_pseg].nf = nf; n_pseg++; } assert (k == 1); assert (wd[0] == '('); k = strlen(wd); assert (wd[k-1] == ')'); wd[k-1] = '\0'; strcpy (uttid, wd+1); } static int32 frm2pseg (int32 fr) { int32 i; for (i = 0; i < n_pseg; i++) if ((pseg[i].sf <= fr) && (pseg[i].sf + pseg[i].nf > fr)) return i; return -1; } static float64 eucl_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = f1[i] - f2[i]; dist += d*d; } return sqrt(dist); } static float64 maha_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = (f1[i] - f2[i]); dist += d*d / var[i]; } return sqrt(dist); } static void compute_var (float32 **mfc, int32 nfr, int32 cepsize) { float32 *sum, *mean; int32 i, j; sum = (float32 *) ckd_calloc (cepsize, sizeof(float32)); mean = (float32 *) ckd_calloc (cepsize, sizeof(float32)); for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += mfc[i][j]; } for (i = 0; i < cepsize; i++) mean[i] = sum[i]/(float64)nfr; for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += (mfc[i][j] - mean[j]) * (mfc[i][j] - mean[j]); } for (i = 0; i < cepsize; i++) var[i] = sum[i]/(float64)nfr; #if 0 /* Hack!! Scale variances */ for (i = 0; i < cepsize; i++) printf (" %.3f", var[i]); printf ("\n"); for (i = 0; i < cepsize; i++) var[i] *= (1.0 + (float64)(i*cepsize*0.5)/(float64)cepsize); for (i = 0; i < cepsize; i++) printf (" %.3f", var[i]); printf ("\n"); #endif ckd_free (sum); ckd_free (mean); } static void cepwinvar (float32 **mfc, int32 nfr, int32 cepsize) { int32 f, i, w, p; float64 logd, prevd[3]; prevd[0] = 0.0; prevd[1] = 0.0; prevd[2] = 0.0; for (f = 3; f < nfr-3; f++) { if ((p = frm2pseg (f)) < 0) E_FATAL("frm2pseg(%d) returned -1\n", f); printf ("%5d %10s ", f, pseg[p].p); for (w = 1; w <= 3; w++) { compute_var (mfc+f-w, w+w+1, cepsize); logd = 0.0; for (i = 0; i < cepsize; i++) logd += log(var[i]); printf (" %8.2f %8.2f", logd, logd - prevd[w-1]); prevd[w-1] = logd; } printf ("\n"); fflush (stdout); } } static void process_psegfile (char *cepdir) { char cepfile[4096], line[16384]; int32 nfr; float32 **mfc; while (fgets (line, sizeof(line), stdin) != NULL) { load_pseg (line); sprintf (cepfile, "%s/%s.mfc", cepdir, uttid); if ((nfr = s2mfc_read (cepfile, 0, (int32)0x70000000, 0, &mfc)) <= 0) E_FATAL("MFC file read (%s) failed\n", cepfile); E_INFO("%d frames, %d phone segments\n", nfr, n_pseg); cepwinvar (mfc, nfr, cepsize); } } main (int32 argc, char *argv[]) { char *psegfile; int32 i; if (argc != 2) E_FATAL("Usage: %s cepdir < psegfile\n", argv[0]); cepdir = argv[1]; feat_init ("s3_1x39"); cepsize = feat_cepsize (); var = (float32 *) ckd_calloc (cepsize, sizeof(float32)); pseg = (pseg_t *) ckd_calloc (S3_MAX_FRAMES, sizeof(pseg_t)); process_psegfile (cepdir); exit(0); } <file_sep>/sphinx4/tests/frontend/FrontEndTest.java /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package tests.frontend; import edu.cmu.sphinx.frontend.Data; import edu.cmu.sphinx.frontend.util.StreamDataSource; import edu.cmu.sphinx.frontend.util.DataDumper; import edu.cmu.sphinx.util.props.ConfigurationManager; import java.io.FileInputStream; /** * Test program for the FrontEnd. */ public class FrontEndTest { public static void main(String[] argv) { if (argv.length < 3) { System.out.println ("Usage: java testClass <testName> " + "<configFile> <audiofilename>"); } try { String configFile = argv[1]; String audioFile = argv[2]; ConfigurationManager cm = new ConfigurationManager(configFile); StreamDataSource source = (StreamDataSource) cm.lookup ("streamDataSource"); source.setInputStream(new FileInputStream(audioFile), audioFile); DataDumper dumper = (DataDumper)cm.lookup("dataDumper"); Data data = null; do { data = dumper.getData(); } while (data != null); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/archive_s3/s3.2/src/hmm.c /* * hmm.c -- HMM Viterbi search. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 29-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Modified hmm_t.state to be a run-time array instead of a compile-time * one. Modified compile-time 3 and 5-state versions of hmm_vit_eval * into hmm_vit_eval_3st and hmm_vit_eval_5st, to allow run-time selection. * Removed hmm_init(). * * 11-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Bugfix in computing HMM exit state score. * * 08-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added HMM_SKIPARCS compile-time option and hmm_init(). * * 20-Sep-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Bugfix in hmm_eval: If state1->state2 transition took place, * state1 history didn't get propagated to state2. * Also, included tp[][] in HMM evaluation. * * 10-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started, based on an earlier version. */ #include "hmm.h" void hmm_dump (hmm_t *hmm, int32 n_state, s3senid_t *senid, int32 *senscr, FILE *fp) { int32 i; fprintf (fp, " %11d ", hmm->in.score); for (i = 0; i < n_state; i++) fprintf (fp, " %11d", hmm->state[i].score); fprintf (fp, " %11d\n", hmm->out.score); fprintf (fp, " %11d ", hmm->in.history); for (i = 0; i < n_state; i++) fprintf (fp, " %11d", hmm->state[i].history); fprintf (fp, " %11d\n", hmm->out.history); if (senid) { fprintf (fp, " %-11s ", "senid"); for (i = 0; i < n_state; i++) fprintf (fp, " %11d", senid[i]); fprintf (fp, "\n"); if (senscr) { fprintf (fp, " %-11s ", "senscr"); for (i = 0; i < n_state; i++) fprintf (fp, " %11d", senscr[senid[i]]); fprintf (fp, "\n"); } } fflush (fp); } void hmm_clear (hmm_t *h, int32 n_state) { int32 i; h->in.score = S3_LOGPROB_ZERO; h->in.history = -1; for (i = 0; i < n_state; i++) { h->state[i].score = S3_LOGPROB_ZERO; h->state[i].history = -1; } h->out.score = S3_LOGPROB_ZERO; h->out.history = -1; h->bestscore = S3_LOGPROB_ZERO; } int32 hmm_vit_eval_5st (hmm_t *hmm, s3senid_t *senid, int32 *senscr) { int32 s0, s1, s2, s3, s4, best, *tp; tp = hmm->tp[0]; /* Hack!!, use the knowledge that the 2-D tp is a contiguous block */ /* 4 = max(2,3,4); */ s4 = hmm->state[4].score + tp[28]; s3 = hmm->state[3].score + tp[22]; s2 = hmm->state[2].score + tp[16]; if (s4 < s3) { if (s3 >= s2) { s4 = s3; hmm->state[4].history = hmm->state[3].history; } else { s4 = s2; hmm->state[4].history = hmm->state[2].history; } } else if (s4 < s2) { s4 = s2; hmm->state[4].history = hmm->state[2].history; } s4 += senscr[senid[4]]; hmm->state[4].score = s4; /* 3 = max(1,2,3); */ s3 = hmm->state[3].score + tp[21]; s2 = hmm->state[2].score + tp[15]; s1 = hmm->state[1].score + tp[ 9]; if (s3 < s2) { if (s2 >= s1) { s3 = s2; hmm->state[3].history = hmm->state[2].history; } else { s3 = s1; hmm->state[3].history = hmm->state[1].history; } } else if (s3 < s1) { s3 = s1; hmm->state[3].history = hmm->state[1].history; } s3 += senscr[senid[3]]; hmm->state[3].score = s3; best = (s4 > s3) ? s4 : s3; /* Exit state score */ s4 += tp[29]; s3 += tp[23]; if (s4 < s3) { hmm->out.score = s3; hmm->out.history = hmm->state[3].history; } else { hmm->out.score = s4; hmm->out.history = hmm->state[4].history; } /* 2 = max(0,1,2); */ s2 = hmm->state[2].score + tp[14]; s1 = hmm->state[1].score + tp[ 8]; s0 = hmm->state[0].score + tp[ 2]; if (s2 < s1) { if (s1 >= s0) { s2 = s1; hmm->state[2].history = hmm->state[1].history; } else { s2 = s0; hmm->state[2].history = hmm->state[0].history; } } else if (s2 < s0) { s2 = s0; hmm->state[2].history = hmm->state[0].history; } s2 += senscr[senid[2]]; hmm->state[2].score = s2; if (best < s2) best = s2; /* 1 = max(0,1); */ s1 = hmm->state[1].score + tp[ 7]; s0 = hmm->state[0].score + tp[ 1]; if (s1 < s0) { s1 = s0; hmm->state[1].history = hmm->state[0].history; } s1 += senscr[senid[1]]; hmm->state[1].score = s1; if (best < s1) best = s1; /* 0 = max(0,in); */ s0 = hmm->state[0].score + tp[ 0]; if (s0 < hmm->in.score) { s0 = hmm->in.score; hmm->state[0].history = hmm->in.history; } s0 += senscr[senid[0]]; hmm->state[0].score = s0; if (best < s0) best = s0; hmm->in.score = S3_LOGPROB_ZERO; /* Consumed */ hmm->bestscore = best; return best; } int32 hmm_vit_eval_3st (hmm_t *hmm, s3senid_t *senid, int32 *senscr) { int32 s0, s1, s2, best, *tp; tp = hmm->tp[0]; /* Hack!!, use the knowledge that the 2-D tp is a contiguous block */ /* 2 = max(0,1,2); */ s2 = hmm->state[2].score + tp[10]; s1 = hmm->state[1].score + tp[ 6]; s0 = hmm->state[0].score + tp[ 2]; if (s2 < s1) { if (s1 >= s0) { s2 = s1; hmm->state[2].history = hmm->state[1].history; } else { s2 = s0; hmm->state[2].history = hmm->state[0].history; } } else if (s2 < s0) { s2 = s0; hmm->state[2].history = hmm->state[0].history; } s2 += senscr[senid[2]]; hmm->state[2].score = s2; /* 1 = max(0,1); */ s1 = hmm->state[1].score + tp[ 5]; s0 = hmm->state[0].score + tp[ 1]; if (s1 < s0) { s1 = s0; hmm->state[1].history = hmm->state[0].history; } s1 += senscr[senid[1]]; hmm->state[1].score = s1; best = (s2 > s1) ? s2 : s1; /* Exit state score */ s2 += tp[11]; s1 += tp[ 7]; if (s2 < s1) { hmm->out.score = s1; hmm->out.history = hmm->state[1].history; } else { hmm->out.score = s2; hmm->out.history = hmm->state[2].history; } /* 0 = max(0,in); */ s0 = hmm->state[0].score + tp[ 0]; if (s0 < hmm->in.score) { s0 = hmm->in.score; hmm->state[0].history = hmm->in.history; } s0 += senscr[senid[0]]; hmm->state[0].score = s0; if (best < s0) best = s0; hmm->in.score = S3_LOGPROB_ZERO; /* Consumed */ hmm->bestscore = best; return best; } int32 hmm_dump_vit_eval (hmm_t *hmm, int32 n_state, s3senid_t *senid, int32 *senscr, FILE *fp) { int32 bs; if (fp) hmm_dump (hmm, n_state, senid, senscr, fp); if (n_state == 5) bs = hmm_vit_eval_5st (hmm, senid, senscr); else if (n_state == 3) bs = hmm_vit_eval_3st (hmm, senid, senscr); else E_FATAL("#States= %d unsupported\n", n_state); if (fp) hmm_dump (hmm, n_state, senid, senscr, fp); return bs; } <file_sep>/archive_s3/s3.2/src/mdeftest.c /* * mdeftest.c -- * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 30-Apr-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include "mdef.h" main (int32 argc, char *argv[]) { mdef_t *m; if ((argc != 2) && (argc != 3)) E_FATAL("Usage: %s mdeffile [dump]\n", argv[0]); m = mdef_init (argv[1]); if (argc == 3) mdef_dump (stdout, m); exit(0); } <file_sep>/CLP/src/Similarities.cc //------------------------------------------------------------------------------------------- // Similarities.cc //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #include "Similarities.h" inline int minim(int a, int b) { if (a<b) return a; else return b; } // ////////////////////////////////////////// double compute_phonetic_similarity(const string& A1, const string& B1) { static vector<vector<unsigned short> > D; int AL; int BL; LineSplitter A, B; A.Split(A1); B.Split(B1); AL = A.NoWords(); BL = B.NoWords(); D.resize(AL+1); // initialize both axes for (int i = 0; i <= AL; i++) { D[i].resize(BL+1); D[i][0] = i; } for (int i = 0; i <= BL; i++) { D[0][i] = i; } // dynamic programming for (int i = 1; i <= AL; i++) for (int j = 1; j <= BL; j++){ if (A[i-1] == B[j-1]){ D[i][j] = minim(minim(D[i-1][j]+1, D[i][j-1]+1),D[i-1][j-1]); } else D[i][j] = minim(minim(D[i-1][j]+1,D[i][j-1]+1),D[i-1][j-1]+1); } double result = D[AL][BL]; double final_result = 1 - result/(AL + BL); if (final_result == 0) final_result = 0.00001; return final_result; } // ////////////////////////////////////////////////////////////// double compute_word_similarity(const string& A, const string& B) { static vector<vector<unsigned short> > D; int AL = A.size(); int BL = B.size(); D.resize(AL+1); for (int i = 0; i <= AL; i++) { D[i].resize(BL+1); D[i][0] = i; } for (int i = 0; i <= BL; i++) { D[0][i] = i; } for (int i = 1; i <= AL; i++) for (int j = 1; j <= BL; j++){ if (A[i-1] == B[j-1]){ D[i][j] = minim(minim(D[i-1][j]+1, D[i][j-1]+1),D[i-1][j-1]); } else D[i][j] = minim(minim(D[i-1][j]+1,D[i][j-1]+1),D[i-1][j-1]+1); } double result = D[AL][BL]; double final_result = 1 - result/(AL + BL); if (final_result == 0) final_result = 0.00001; return final_result; } // ////////////////////////////////////////////////////////////// float compute_time_overlap(float p1, float p2, float q1, float q2){ float e; if (p1 <= q1){ if (p2 <= q1){ // p1 p2 q1 q2 e = 0; } else if (p2 <= q2){ // p1 q1 p2 q2 e = p2 - q1; } else{ // p1 q1 q2 p2 e = q2 - q1; } } else{ if (q2 <= p1){ //q1 q2 p1 p2 e = 0; } else if (q2 <= p2){ // q1 p1 q2 p2 e = q2 - p1; } else { // q1 p1 p2 q2 e = p2 - p1; } } return 2*e / ( p2-p1 + q2-q1); } // /////////////////////////////////////////////////////////////////////// // when there is no time info float compute_time_overlap_ph(float p1, float p2, float q1, float q2){ float e; if (p1 <= q1){ if (p2 <= q1){ // p1 p2 q1 q2 return p2-q1; } else if (p2 <= q2){ // p1 q1 p2 q2 e = p2 - q1; } else{ // p1 q1 q2 p2 e = q2 - q1; } } else{ if (q2 <= p1){ //q1 q2 p1 p2 return q2 - p1; } else if (q2 <= p2){ // q1 p1 q2 p2 e = q2 - p1; } else { // q1 p1 p2 q2 e = p2 - p1; } } return 2*e / ( p2-p1 + q2-q1); } <file_sep>/archive_s3/s3.0/pgm/timealign/wdnet.h /* * wdnet.h -- Wordnet for alignment * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 28-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _TIMEALIGN_WDNET_H_ #define _TIMEALIGN_WDNET_H_ #include <libutil/libutil.h> #include <libmain/dict.h> #include <libmain/wnet.h> /* * Build a graph word nodes for the given word transcript wd[]. Allow alternative * pronunciations for each word, compound forms of words, and optional intermediate * silence and filler noise words, as specified by the additional arguments. * However, a START_WORD is always inserted at the head, and a FINISH_WORD at the * end of the word net. * Return value: list of word nodes (wnode_t *). */ glist_t wdnet_build (dict_t *dict, /* In: Dictionary to convert words to IDs */ char **wd, /* In: Words in input transcript */ int32 nwd, /* In: No. of words in wd[] */ int32 noalt, /* In: If noalt, do not try alternative pronunciations, and do not try compound words */ int32 nosil, /* In: If nosil, do not insert optional SILENCE_WORD between words */ int32 nonoise, /* In: If nonoise, do not insert optional non-silence noise words between words */ wnode_t **start, /* Out: Return ptr to a START_WORD node inserted at the head of the wordnet */ wnode_t **end); /* Out: Return ptr to a FINISH_WORD node inserted at the tail of the wordnet */ /* * Free the given word net graph. */ void wdnet_free (glist_t wdnet); #endif <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/conftree/CategoryTree.java package edu.cmu.sphinx.tools.confdesigner.conftree; import edu.cmu.sphinx.util.props.*; import edu.cmu.sphinx.util.props.Configurable; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import java.util.*; /** * A component tree where the tree structure is defined by user-defined category annoations. Because the * <code>ConfCategory</code> allows multiple tagging, components might occur in several functional categories. * * @author <NAME> * @see ConfCategory */ public class CategoryTree extends ConfigurableTree { public void rebuildTree() { setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); categories.clear(); //add all s4-configurables to the tree DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot(); rootNode.removeAllChildren(); List<Class<? extends Configurable>> untaggedClasses = new ArrayList<Class<? extends Configurable>>(); for (Class<? extends Configurable> confClass : filteredConfigClasses) { Set<String> classCategories = collectCategories(confClass); if (classCategories.isEmpty()) { untaggedClasses.add(confClass); continue; } for (String category : classCategories) { if (!categories.containsKey(category)) { categories.put(category, new DefaultMutableTreeNode(category)); rootNode.add(categories.get(category)); } DefaultMutableTreeNode categoryNode = categories.get(category); categoryNode.add(new ConfigurableNode(confClass)); } } // add all untagged classes DefaultMutableTreeNode untagNode = new DefaultMutableTreeNode("untagged"); rootNode.add(untagNode); for (Class<? extends Configurable> untaggedClass : untaggedClasses) untagNode.add(new ConfigurableNode(untaggedClass)); // for (int i = 0; i < getRowCount(); i++) expandRow(0); } /** * Extract the ui-tags of a given classes, its parent-classes and all its implementing interfaces. * <p/> * Basically it iterates over all parent classes of the given <code>confClass</code> and all their implementing * interfaces in order to collect the category tags */ public static Set<String> collectCategories(Class confClass) { Set<String> catNames = new HashSet<String>(); ConfCategory cateogry = (ConfCategory) confClass.getAnnotation(ConfCategory.class); if (cateogry != null) catNames.addAll(Arrays.asList(cateogry.value())); Class<?> superClass = confClass.getSuperclass(); if (superClass != null) { catNames.addAll(collectCategories(superClass)); } for (Class curInterface : confClass.getInterfaces()) { cateogry = (ConfCategory) curInterface.getAnnotation(ConfCategory.class); if (cateogry != null) catNames.addAll(Arrays.asList(cateogry.value())); catNames.addAll(collectCategories(curInterface)); } return catNames; } } <file_sep>/sphinx2/src/examples/Makefile.am bin_PROGRAMS = adpow \ adrec \ cdcn_test \ cont_adseg \ cont_fileseg \ lm_fsg_test \ lm_fsg_test2 \ lm3g2dmp \ pdf32to8b \ raw2cep \ sphinx2_allphone \ sphinx2_batch \ sphinx2_continuous \ sphinx2_ptt \ sphinx2_server \ sphinx2_client EXTRA_DIST = README \ README.bin \ clicore.h \ srvcore.h adpow_SOURCES = adpow.c adrec_SOURCES = adrec.c cdcn_test_SOURCES = cdcn_test.c cont_adseg_SOURCES = cont_adseg.c cont_fileseg_SOURCES = cont_fileseg.c lm_fsg_test_SOURCES = lm_fsg_test.c lm_fsg_test2_SOURCES = lm_fsg_test2.c lm3g2dmp_SOURCES = lm3g2dmp.c raw2cep_SOURCES = raw2cep.c pdf32to8b_SOURCES = pdf32to8b.c sphinx2_allphone_SOURCES = allphone-test.c sphinx2_batch_SOURCES = batch.c sphinx2_continuous_SOURCES = tty-continuous.c sphinx2_ptt_SOURCES = tty-ptt.c sphinx2_server_SOURCES = server.c \ srvcore.c sphinx2_client_SOURCES = client.c \ clicore.c LDADD = $(top_builddir)/src/libsphinx2/libsphinx2.la \ $(top_builddir)/src/libsphinx2fe/libsphinx2fe.la \ $(top_builddir)/src/libsphinx2ad/libsphinx2ad.la \ -lm @ad_libs@ # add these for solaris # -L/usr/demo/SOUND/lib/ -laudio -lnsl -lsocket INCLUDES = -I$(top_srcdir)/include \ -I$(top_srcdir)/src/libsphinx2/include \ -I$(top_srcdir)/src/examples \ -I$(top_builddir)/include # add for solaris # -I/usr/demo/SOUND/include <file_sep>/CLP/src/Makefile.am bin_PROGRAMS = Consensus Consensus_print Consensus_SOURCES = Cluster.cc \ Clustering.cc \ common.cc \ Consensus.cc \ GetOpt.cc \ Lattice.cc \ LineSplitter.cc \ Prons.cc \ Similarities.cc Consensus_print_SOURCES = Cluster.cc \ Clustering_print.cc \ common.cc \ Consensus_print.cc \ GetOpt.cc \ Lattice.cc \ LineSplitter.cc \ Prons.cc \ Similarities.cc AM_CPPFLAGS = -I$(top_srcdir)/include <file_sep>/SphinxTrain/Makefile # ==================================================================== # Copyright (c) 2000 Carnegie Mellon University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 3. The names "Sphinx" and "Carnegie Mellon" must not be used to # endorse or promote products derived from this software without # prior written permission. To obtain permission, contact # <EMAIL>. # # 4. Redistributions of any form whatsoever must retain the following # acknowledgment: # "This product includes software developed by Carnegie # Mellon University (http://www.speech.cs.cmu.edu/)." # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Top Level Makefile for Sphinx Training tools # # ==================================================================== TOP=. DIRNAME=. BUILD_DIRS = include src python ALL_DIRS=config etc doc $(BUILD_DIRS) scripts_pl CONFIG=config.guess config.sub configure configure.in \ install-sh missing mkinstalldirs FILES = Makefile README.txt README.tracing COPYING $(CONFIG) DISTCLEAN_FILES = config/config config/system.mak \ config.cache config.status config.log ALL = # Try and see if config hasn't been created config_dummy := $(shell test -f config/config || ( echo '*** '; echo '*** Running configure to make default config file ***'; echo '*** '; ./configure; ) >&2) include $(TOP)/config/common_make_rules config/config: config/config.in config.status ./config.status configure: configure.in autoconf distclean: clean @ echo make distclean in top-level directory @ $(RM) $(DISTCLEAN_FILES) @ $(RM) -rf $(BINDIR) $(LIBDIR) backup: time-stamp @ $(RM) -f $(TOP)/FileList @ $(MAKE) file-list @ echo .time-stamp >>FileList @ sed 's/^\.\///' <FileList | sed 's/^/'$(PROJECT_PREFIX)'\//' >.file-list-all @ (cd ..; tar zcvf $(PROJECT_PREFIX)/$(PROJECT_PREFIX)-$(PROJECT_VERSION)-$(PROJECT_STATE).tar.gz `cat $(PROJECT_PREFIX)/.file-list-all`) @ $(RM) -f $(TOP)/.file-list-all @ ls -l $(PROJECT_PREFIX)-$(PROJECT_VERSION)-$(PROJECT_STATE).tar.gz tags: @ $(RM) -f $(TOP)/FileList @ $(MAKE) file-list etags `cat FileList | grep "\.[ch]$$"` time-stamp : @ echo $(PROJECT_NAME) >.time-stamp @ echo $(PROJECT_PREFIX) >>.time-stamp @ echo $(PROJECT_VERSION) >>.time-stamp @ echo $(PROJECT_DATE) >>.time-stamp @ echo $(PROJECT_STATE) >>.time-stamp @ echo $(LOGNAME) >>.time-stamp @ hostname >>.time-stamp @ date >>.time-stamp check: @ $(MAKE) -C test test # @ $(MAKE) --no-print-directory -C testsuite test .PHONY: test <file_sep>/archive_s3/s3.0/pgm/timealign/wdnet.c /* * wdnet.c -- Build wordnet for alignment * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 28-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include <libmain/wnet2pnet.h> #include "wdnet.h" static glist_t wdnet; /* List of nodes in the word graph */ static int32 n_wnode, n_wlink; static wnode_t *wnode_create (s3wid_t wid) { wnode_t *wn; wn = (wnode_t *) mymalloc (sizeof(wnode_t)); wn->wid = wid; wn->succ = NULL; wn->pred = NULL; wdnet = glist_add_ptr (wdnet, (void *) wn); n_wnode++; return wn; } static void link_wnodes (wnode_t *src, wnode_t *dst) { wlink_t *l; l = (wlink_t *) mymalloc (sizeof(wlink_t)); l->dst = dst; src->succ = glist_add_ptr (src->succ, (void *) l); l = (wlink_t *) mymalloc (sizeof(wlink_t)); l->dst = src; dst->pred = glist_add_ptr (dst->pred, (void *) l); n_wlink++; } static void fillernet_create (int32 nwd, s3wid_t *fwid, int32 n_fwid, glist_t *pred, glist_t *succ) { wnode_t **wn; int32 i, j, k; gnode_t *gn; wn = (wnode_t **) ckd_calloc (n_fwid, sizeof(wnode_t *)); for (i = 0; i < nwd-1; i++) { /* Allocate fillernet nodes */ for (j = 0; j < n_fwid; j++) wn[j] = wnode_create (fwid[j]); /* Fully connected fillernet */ for (j = 0; j < n_fwid; j++) for (k = 0; k < n_fwid; k++) link_wnodes (wn[j], wn[k]); /* Insert fillernet between words i and i+1 */ for (gn = pred[i+1]; gn; gn = gn->next) for (j = 0; j < n_fwid; j++) link_wnodes ((wnode_t *) gnode_ptr(gn), wn[j]); for (gn = succ[i]; gn; gn = gn->next) for (j = 0; j < n_fwid; j++) link_wnodes (wn[j], (wnode_t *) gnode_ptr(gn)); } ckd_free (wn); } glist_t wdnet_build (dict_t *dict, char **wd, int32 nwd, int32 noalt, int32 nosil, int32 nonoise, wnode_t **start, wnode_t **end) { s3wid_t *wid; /* IDs for wd[] + surrounding START and FINISH words */ glist_t *pred; /* pred[i] = list of nodes in the word net that are predecessors to the given word at position i */ glist_t *succ; /* succ[i] = list of nodes in the word net that are successors to the given word at position i */ s3wid_t *fwid; /* Optional fillers wids to be inserted, if any */ int32 n_fwid; /* #fillers */ int32 missing; s3wid_t w; int32 i, j; wnode_t *wn; gnode_t *gn; if (nwd == 0) { E_ERROR("Empty word sequence argument to wdseq2net()\n"); return NULL; } n_wnode = 0; n_wlink = 0; /* * We always add an initial START_WORD node and a final FINISH_WORD node, even though * they may not take part in the search (i.e., if nosil is TRUE). */ wid = (s3wid_t *) ckd_calloc (nwd+2, sizeof(s3wid_t)); wid[0] = dict_wordid (dict, START_WORD); wid[nwd+1] = dict_wordid (dict, FINISH_WORD); if (NOT_WID(wid[0]) || NOT_WID(wid[nwd+1])) E_FATAL("%s and/or %s not in dictionary\n", START_WORD, FINISH_WORD); missing = 0; for (i = 0; i < nwd; i++) { wid[i+1] = dict_wordid (dict, wd[i]); if (NOT_WID(wid[i+1])) { E_ERROR("%s not in dictionary\n", wd[i]); missing = 1; } else { if (! noalt) wid[i+1] = dict_basewid (dict, wid[i+1]); } } if (missing) { ckd_free (wid); return NULL; } nwd += 2; pred = (glist_t *) ckd_calloc (nwd, sizeof(glist_t)); succ = (glist_t *) ckd_calloc (nwd, sizeof(glist_t)); wdnet = NULL; /* Create and add START_WORD node to pred[1] (assume just 1 pronunciation for it) */ wn = wnode_create (wid[0]); pred[1] = glist_add_ptr (pred[1], wn); *start = wn; /* Add each word (except START_WORD and FINISH_WORD) to net */ for (i = 1; i < nwd-1; i++) { if (! noalt) { /* Add every alternative pronunciation for wid[i] to net */ for (w = wid[i]; IS_WID(w); w = dict_nextalt(dict, w)) { /* Add w to net */ wn = wnode_create (w); pred[i+1] = glist_add_ptr (pred[i+1], wn); succ[i-1] = glist_add_ptr (succ[i-1], wn); for (gn = pred[i]; gn; gn = gn->next) link_wnodes ((wnode_t *) gnode_ptr(gn), wn); } } else { /* Add wid[i] to net */ wn = wnode_create (wid[i]); pred[i+1] = glist_add_ptr (pred[i+1], wn); succ[i-1] = glist_add_ptr (succ[i-1], wn); for (gn = pred[i]; gn; gn = gn->next) link_wnodes ((wnode_t *) gnode_ptr(gn), wn); } } /* Add FINISH_WORD node to succ[nwd-2] (assume just 1 pronunciation for it) */ wn = wnode_create (wid[nwd-1]); succ[nwd-2] = glist_add_ptr (succ[nwd-2], wn); for (gn = pred[nwd-1]; gn; gn = gn->next) link_wnodes ((wnode_t *) gnode_ptr(gn), wn); *end = wn; /* Add compound words, if any and if allowed */ if (! noalt) { for (i = 1; i < nwd-2; i++) { for (j = i+1; j < nwd-1; j++) { /* See if wid[i]..wid[j] is a compound word in the dictionary */ for (w = dict_wids2compwid (dict, wid+i, j-i+1); IS_WID(w); w = dict_nextalt(dict, w)) { /* Insert compound word w in word net */ wn = wnode_create (w); pred[j+1] = glist_add_ptr (pred[j+1], wn); succ[i-1] = glist_add_ptr (succ[i-1], wn); for (gn = pred[i]; gn; gn = gn->next) link_wnodes ((wnode_t *) gnode_ptr(gn), wn); for (gn = succ[j]; gn; gn = gn->next) link_wnodes (wn, (wnode_t *) gnode_ptr(gn)); } } } } /* Add the optional filler words to the wordnet, if any and if allowed */ i = dict_filler_start (dict); j = dict_filler_end (dict); n_fwid = 0; fwid = NULL; if (i <= j) { /* First build the list of filler words */ fwid = (s3wid_t *) ckd_calloc (j-i+1, sizeof(s3wid_t)); for (; i <= j; i++) { if (dict_filler_word (dict, i)) { /* To exclude START and FINISH words */ w = dict_basewid (dict, i); if (w == dict_silwid(dict)) { if (! nosil) fwid[n_fwid++] = i; } else { if (! nonoise) fwid[n_fwid++] = i; } } } } if (n_fwid > 0) fillernet_create (nwd, fwid, n_fwid, pred, succ); ckd_free (wid); if (fwid) ckd_free (fwid); for (i = 0; i < nwd; i++) { glist_free (pred[i]); glist_free (succ[i]); } ckd_free(pred); ckd_free(succ); E_INFO("%d wnodes, %d wlinks\n", n_wnode, n_wlink); return wdnet; } static void wlink_free (void *data) { wnode_t *wn; wn = (wnode_t *) data; glist_myfree (wn->succ, sizeof(wlink_t)); glist_myfree (wn->pred, sizeof(wlink_t)); } void wdnet_free (glist_t wdnet) { glist_apply_ptr (wdnet, wlink_free); glist_myfree (wdnet, sizeof(wnode_t)); } #if (_WDNET_TEST_) static dict_t *tmpdict; static void wdnet_dump_wnode (void *data) { wnode_t *wn; wn = (wnode_t *)data; printf ("%s\n", dict_wordstr(tmpdict, wn->wid)); } static void wdnet_dump_wlink (void *data) { wnode_t *wn; gnode_t *gn; wlink_t *wl; wdnet_dump_wnode (data); wn = (wnode_t *) data; for (gn = wn->succ; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); printf ("\t\t -> "); wdnet_dump_wnode (wl->dst); } } static void wdnet_dump (dict_t *d, glist_t wdnet) { tmpdict = d; E_INFO("wnodes:\n"); glist_apply_ptr (wdnet, wdnet_dump_wnode); E_INFO("wlinks:\n"); glist_apply_ptr (wdnet, wdnet_dump_wlink); } main (int32 argc, char *argv[]) { mdef_t *m; dict_t *d; char line[16384]; char *wp[4096]; int32 nwd; glist_t wnet; wnode_t *wstart, *wend; int32 noalt, nosil, nonoise; int32 n; glist_t pnet; pnode_t *pstart, *pend; if (argc != 4) E_FATAL("Usage: %s mdef dict fillerdict\n"); m = mdef_init (argv[1]); d = dict_init (m, argv[2], argv[3], '_'); wnet = NULL; for (;;) { printf ("noalt, nosil, nonoise, utt> "); fgets (line, sizeof(line), stdin); if (sscanf (line, "%d %d %d%n", &noalt, &nosil, &nonoise, &n) != 3) { E_ERROR("Bad line: %s\n", line); continue; } nwd = str2words (line+n, wp, 4095); if (wnet) wdnet_free (wnet); wnet = wdnet_build (d, wp, nwd, noalt, nosil, nonoise, &wstart, &wend); if (wnet) { wdnet_dump (d, wnet); pnet = wnet2pnet (m, d, wnet, wstart, wend, &pstart, &pend); pnet_dump (m, d, pnet); pnet_free (pnet); } } if (wnet) wdnet_free (wnet); } #endif <file_sep>/SphinxTrain/include/s3/dtree.h /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: dtree.h * * Description: * * Author: * *********************************************************************/ #ifndef DTREE_H #define DTREE_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/dtree.h> #include <s3/pset_io.h> #include <s3/prim_type.h> #include <s3/acmod_set.h> #include <s3/btree.h> #include <s3/quest.h> #define NO_CLUST (0xffffffff) typedef struct dtree_node_str { uint32 node_id; uint32 clust; /* If simple tree, which cluster (0 or 1) does this leaf node belong to. If complex tree and a leaf node, clust is the tied state id of the node */ uint32 *id; /* id's of triphones represented by this node */ uint32 n_id; /* # of triphones represented */ float32 ***mixw_occ; /* ADDITION FOR CONTINUOUS_TREES, 19 May 98 */ float32 ***means; float32 ***vars; /* END ADDITION FOR CONTINUOUS_TREES */ float32 occ; /* # of time state is observed */ float64 wt_ent; /* weighted entropy of this node */ void *q; /* best question for this node */ float64 wt_ent_dec; /* Weighted entropy decrease of doing split */ struct dtree_node_str *p; /* parent node */ struct dtree_node_str *y; /* yes child node */ struct dtree_node_str *n; /* no child node */ } dtree_node_t; #define IS_LEAF(nd) ((((nd)->y == NULL) && ((nd)->n == NULL))) #define IS_TWIG(nd) (!IS_LEAF(nd) && IS_LEAF((nd)->y) && IS_LEAF((nd)->n)) typedef struct dtree_s { dtree_node_t *node; uint32 n_node; } dtree_t; uint32 cnt_node(dtree_node_t *node); uint32 reindex(dtree_node_t *node, uint32 *next_id); uint32 cnt_leaf(dtree_node_t *node); uint32 label_leaves(dtree_node_t *node, uint32 *id); dtree_node_t * get_node(dtree_node_t *node, uint32 id); uint32 tied_state(dtree_node_t *node, acmod_id_t b, acmod_id_t l, acmod_id_t r, word_posn_t wp, pset_t *pset); uint32 cnt_twig(dtree_node_t *node); void print_node(FILE *fp, dtree_node_t *node, pset_t *pset); void print_node_comp(FILE *fp, dtree_node_t *node, pset_t *pset); void print_final_tree(FILE *fp, dtree_node_t *node, pset_t *pset); void print_final_tree_davinci(FILE *fp, dtree_node_t *node, pset_t *pset); dtree_t * read_final_tree(FILE *fp, pset_t *pset, uint32 n_pset); void free_tree(dtree_t *tr); void print_tree(FILE *fp, char *label, dtree_node_t *node, pset_t *pset, uint32 lvl); void print_tree_comp(FILE *fp, char *label, dtree_node_t *node, pset_t *pset, uint32 lvl); int mk_node(dtree_node_t *node, uint32 node_id, uint32 *id, uint32 n_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 18 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, float32 mwfloor); float64 set_best_quest(dtree_node_t *node, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 20 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, float32 mwfloor); dtree_t * mk_tree(float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 20 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, uint32 max_split, uint32 min_split, float32 split_thr, float32 mwfloor); dtree_t * mk_tree_comp(float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 18 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, uint32 split_min_comp, uint32 split_max_comp, float32 split_thr_comp, float32 mwfloor); void cluster_leaves(dtree_t *tr, /* ADDITION FOR CONTINUOUS_TREES */ uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ float64 *wt_ent_dec, uint32 *out_n_a, uint32 *out_n_b, pset_t *pset, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, float32 mwfloor); void split_node_comp(dtree_t *tr, uint32 node_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, float32 mwfloor); void split_node(dtree_t *tr, uint32 node_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, float32 mwfloor); int split_node_nobest(dtree_t *tr, uint32 node_id, float32 ****mixw, uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 **dfeat, uint32 n_dfeat); comp_quest_t * mk_comp_quest(float64 *wt_ent_dec, float32 ****mixw, /* ADDITIONS FOR CONTINUOUS_TREES, 19 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, float32 mwfloor); int ins_twigs(dtree_node_t *node, uint32 phnid, uint32 state, float32 *twig_heap, uint32 *twig_hkey, uint32 *phnidlst, uint32 *statelst, uint32 *nidlst, uint32 *free_key); uint32 prune_subtrees(dtree_node_t *node); uint32 prune_lowcnt(dtree_node_t *node, float32 cnt_thr); /* ADDITION FOR CONTINUOUS_TREES */ uint32 leaf_mean_vars(dtree_node_t *node, pset_t *pset, float32 ****means, float32 ****vars, uint32 *node_id, uint32 n_state, uint32 n_stream, uint32 *veclen, uint32 off); /* END ADDITION FOR CONTINUOUS_TREES */ #ifdef __cplusplus } #endif #endif /* DTREE_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.4 97/07/23 10:48:42 eht * Added get_node() function * * Revision 1.3 97/07/17 14:29:02 eht * Added prune_lowcnt() function for pruning low occupancy count tree nodes. * * Revision 1.2 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.1 97/07/07 10:53:27 eht * Initial revision * * */ <file_sep>/archive_s3/s3.2/src/beam.h /* * beam.h -- Various forms of pruning beam * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 19-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_BEAM_H_ #define _S3_BEAM_H_ #include <libutil/libutil.h> /* * Structure containing various beamwidth parameters. All logs3 values; -infinite is widest, * 0 is narrowest. */ typedef struct { int32 subvq; /* For selecting active mixture components based on subvq scores */ int32 hmm; /* For selecting active HMMs, relative to best */ int32 ptrans; /* For determining which HMMs transition to their successors */ int32 word; /* For selecting words exited, relative to best HMM score */ } beam_t; /* * Create and initialize a beam_t structure, with the given parameters, converting them * from prob space to logs3 space. Return value: ptr to created structure if successful, * NULL otherwise. */ beam_t *beam_init (float64 svq, float64 hmm, float64 ptr, float64 wd); #endif <file_sep>/tools/riddler/java/edu/cmu/sphinx/tools/riddler/persist/Dictionary.java /** * Copyright 1999-2007 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * <p/> * User: <NAME> * Date: Jan 20, 2007 * Time: 12:23:53 PM */ package edu.cmu.sphinx.tools.riddler.persist; import javax.persistence.*; import java.util.ArrayList; import java.util.List; /** * A Dictionary's unique identifier. A Dictionary consists of Pronunciation records. * @see Pronunciation * @author <NAME> */ @Entity @NamedQuery(name = "findDictionariesByMetadatum", query = "SELECT d FROM Dictionary d, " + "IN (d.metadata) m " + "WHERE m.theKey = :key AND m.theValue = :value") public class Dictionary implements StringIdentified { @Id @GeneratedValue(strategy = GenerationType.TABLE) private String id; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "dictionary") private List<Pronunciation> prons = new ArrayList<Pronunciation>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Metadatum> metadata = new ArrayList<Metadatum>(); public Dictionary(List<Pronunciation> prons, List<Metadatum> metadata) { this.prons = prons; this.metadata = metadata; } public Dictionary() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<Pronunciation> getProns() { return prons; } public void setProns(List<Pronunciation> prons) { this.prons = prons; } public List<Metadatum> getMetadata() { return metadata; } public void setMetadata(List<Metadatum> metadata) { this.metadata = metadata; } public String toString() { return "Dictionary " + super.toString() + " with ID " + id + " and metadata " + metadata; } } <file_sep>/SphinxTrain/src/programs/mk_flat/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Traceability: * * Description: * * Author: * $Author$ *********************************************************************/ #include <s3/cmd_ln.h> #include <s3/s3.h> #include <sys_compat/misc.h> #include "parse_cmd_ln.h" #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[]= "Description:\n\ (Copied from Rita's web page) \n\ In flat-initialization, all mixture weights are set to be equal for \n\ all states, and all state transition probabilities are set to be \n\ equal. Unlike in continuous models, the means and variances of the \n\ codebook Gaussians are not given global values, since they are already \n\ estimated from the data in the vector quantization step. To \n\ flat-initialize the mixture weights, each component of each \n\ mixture-weight distribution of each feature stream is set to be a \n\ number equal to 1/N, where N is the codebook size. The mixture_weights \n\ and transition_matrices are initialized using the executable mk_flat "; const char examplestr[]= "Example:\n\ \n\ mk_flat -moddeffn CFS3.ci.mdef -topo CFS3.topology -mixwfn mixture_weights \n\ -tmatfn transition_matrices -nstream 1 -ndensity 1 "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A SPHINX-III model definition file name" }, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "An output SPHINX-III mixing weight file name" }, { "-topo", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A template model topology matrix file" }, { "-tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "An output SPHINX-III transition matrix file name" }, { "-nstream", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "4", "Number of independent observation streams" }, { "-ndensity", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "256", "Number of densities per mixture density" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/11/29 01:43:47 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.6 2004/11/29 00:49:23 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.5 2004/08/08 04:30:56 arthchan2003 * mk_flat help and example * * Revision 1.4 2004/07/21 18:30:35 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 95/06/02 20:31:23 eht * Initial revision * * */ <file_sep>/tools/audiocollector/build/build.xml <?xml version="1.0" encoding="UTF-8"?> <project basedir="." default="all" name="AudioCollector"> <!-- Load the environment --> <property environment="env"/> <condition property="javadoc_level" value="${access}"> <isset property="access"/> </condition> <condition property="javadoc_level" value="public"> <not> <isset property="access"/> </not> </condition> <!-- ********************************************************** --> <!-- * * --> <!-- * Where to find things... * --> <!-- * * --> <!-- ********************************************************** --> <property name="version" value="0.1"/> <path id="libs"> <fileset dir="../../common/lib" includes="**/sphinx4.jar,**/batch.jar,**/javolution.jar,**/forms_rt.jar,**/plugin.jar"/> <fileset file="${env.JAVA_HOME}/jre/lib/javaws.jar"/> </path> <property name="exploded_dir" value="./exploded"/> <property name="common_lib_dir" value="../../common/lib"/> <property name="src_dir" value="../src/java/"/> <property name="alt_src_dir" value="../../common/src/java/"/> <property name="src_path" value="${src_dir};${alt_src_dir}"/> <property name="build_dir" value="."/> <property name="classes_dir" value="${build_dir}/classes"/> <property name="lib_dir" value="."/> <property name="javadoc_dir" value="javadoc"/> <property name="javadoc_check_dir" value="${build_dir}/javadoc_check"/> <property name="javadoc_zip" value="javadoc.zip"/> <!-- ********************************************************** --> <!-- * * --> <!-- * Determine which sources should be compiled depending * --> <!-- * on the availability of lib/jsapi.jar. This creates a * --> <!-- * property called "patternset_to_compile" and sets its * --> <!-- * val to either "all_files" or "no_jsapi", which refers * --> <!-- * to the name of a patternset. The value of * --> <!-- * srcs_to_compile will be used in the javac target as a * --> <!-- * patternset refid. * --> <!-- * * --> <!-- ********************************************************** --> <patternset id="all_files" includes="edu/**,com/**" /> <patternset id="edu" includes="edu/**" excludes="com/**" /> <target name="set_patternset_to_compile"> <property name="patternset_to_compile" value="all_files"/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Determine which sources should be documented using * --> <!-- * javadoc depending on the availability of * --> <!-- * lib/jsapi.jar. This creates a property called * --> <!-- * "patternset_to_doc" and sets its val to either * --> <!-- * "all" or "no_jsapi", which refers to the name of a * --> <!-- * patternset. * --> <!-- * * --> <!-- ********************************************************** --> <target name="set_patternset_to_doc"> <property name="patternset_to_doc" value="edu"/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Builds srcs, jars, demos * --> <!-- * * --> <!-- ********************************************************** --> <target name="all" description="Build everything"> <antcall target="build_war"/> <echo message="Build complete."/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Builds just the srcs. * --> <!-- * * --> <!-- ********************************************************** --> <target name="compile_src" depends="set_patternset_to_compile" description="Build just the 1.5 srcs"> <mkdir dir="${classes_dir}"/> <javac debug="true" source="1.5" sourcepath="${src_path}" srcdir="${src_dir}" deprecation="true" destdir="${classes_dir}"> <patternset refid="${patternset_to_compile}"/> <classpath refid="libs"/> </javac> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Generates the jar files * --> <!-- * * --> <!-- ********************************************************** --> <target name="jars" depends="datacollection-client_jar,datacollection-server_jar,corpus_jar,copy_lib_jars" description="Builds all the jar files"/> <!-- audio collector jars --> <property name="datacollection-server_jar" value="${lib_dir}/datacollection-server.jar"/> <property name="datacollection-client_jar" value="${lib_dir}/datacollection-client.jar"/> <property name="corpus_jar" value="${lib_dir}/corpus.jar"/> <target name="datacollection-server_jar" depends="compile_src" description="Create ${lib_dir}/datacollection-server.jar"> <mkdir dir="${lib_dir}"/> <jar destfile="${datacollection-server_jar}" compress="true" includes="**/datacollection/server/**" basedir="${classes_dir}"> </jar> </target> <target name="datacollection-client_jar" depends="compile_src" description="Create ${lib_dir}/datacollection-client.jar"> <copy todir="${classes_dir}/edu/cmu/sphinx/tools/datacollection/client/images"> <fileset dir="${src_dir}/edu/cmu/sphinx/tools/datacollection/client/images"/> </copy> <mkdir dir="${lib_dir}"/> <jar destfile="${datacollection-client_jar}" compress="true" includes="**/datacollection/client/**" basedir="${classes_dir}"> <manifest> <attribute name="Class-Path" value="batch.jar corpus.jar javolution.jar sphinx4.jar"/> </manifest> </jar> </target> <target name="corpus_jar" depends="compile_src" description="Create ${lib_dir}/corpus.jar"> <mkdir dir="${lib_dir}"/> <jar destfile="${corpus_jar}" compress="true" includes="**/sphinx/tools/corpus/**,**/sphinx/tools/audio/**" basedir="${classes_dir}"> </jar> </target> <target name="copy_lib_jars" depends="compile_src" description="copies libraries from common/lib"> <mkdir dir="${lib_dir}"/> <copy file="${common_lib_dir}/javolution.jar" todir="${lib_dir}" /> <copy file="${common_lib_dir}/sphinx4.jar" todir="${lib_dir}" /> <copy file="${common_lib_dir}/batch.jar" todir="${lib_dir}" /> </target> <target name="create_exploded_web_module" depends="sign_applet_jars" description="copies libraries from common/lib"> <mkdir dir="${exploded_dir}"/> <mkdir dir="${exploded_dir}/WEB-INF"/> <mkdir dir="${exploded_dir}/WEB-INF/lib"/> <copy file="../data/configs/web.xml" todir="${exploded_dir}/WEB-INF" /> <copy file="${lib_dir}/javolution.jar" todir="${exploded_dir}/WEB-INF/lib" /> <copy file="${lib_dir}/sphinx4.jar" todir="${exploded_dir}/WEB-INF/lib" /> <copy file="${lib_dir}/batch.jar" todir="${exploded_dir}/WEB-INF/lib" /> <copy file="${lib_dir}/datacollection-server.jar" todir="${exploded_dir}/WEB-INF/lib" /> <copy file="${lib_dir}/corpus.jar" todir="${exploded_dir}/WEB-INF/lib" /> <mkdir dir="${exploded_dir}/jsps"/> <copy todir="${exploded_dir}/jsps"> <fileset dir="../src/jsps" /> </copy> <mkdir dir="${exploded_dir}/configs"/> <copy todir="${exploded_dir}/configs"> <fileset dir="../data/samples/"> <include name="**"/> </fileset> </copy> <copy file="${lib_dir}/javolution.jar" todir="${exploded_dir}" /> <copy file="${lib_dir}/sphinx4.jar" todir="${exploded_dir}" /> <copy file="${lib_dir}/batch.jar" todir="${exploded_dir}" /> <copy file="${lib_dir}/corpus.jar" todir="${exploded_dir}" /> <copy file="${lib_dir}/datacollection-client.jar" todir="${exploded_dir}" /> </target> <target name="sign_applet_jars" depends="jars" description="signs the jars used by the applet"> <signjar jar="${lib_dir}/corpus.jar" keystore="sphinx_store" alias="audiocollector" storepass="<PASSWORD>"/> <signjar jar="${lib_dir}/datacollection-client.jar" keystore="sphinx_store" alias="audiocollector" storepass="<PASSWORD>"/> <signjar jar="${lib_dir}/javolution.jar" keystore="sphinx_store" alias="audiocollector" storepass="<PASSWORD>"/> <signjar jar="${lib_dir}/batch.jar" keystore="sphinx_store" alias="audiocollector" storepass="<PASSWORD>"/> <signjar jar="${lib_dir}/sphinx4.jar" keystore="sphinx_store" alias="audiocollector" storepass="<PASSWORD>"/> </target> <target name="build_war" depends="create_exploded_web_module" description="Creates a war file for deployment"> <war warfile="data-collection.war" webxml="${exploded_dir}/WEB-INF/web.xml" basedir="${exploded_dir}"/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Generates the javadoc * --> <!-- * * --> <!-- ********************************************************** --> <property name="javadoc_desc" value="AudioCollector"/> <target name="javadoc" depends="set_patternset_to_doc" description="Generate javadoc, optionally with '-Daccess=private'"> <delete dir="${javadoc_dir}"/> <mkdir dir="${javadoc_dir}"/> <javadoc sourcepath="${src_path}" source="1.5" additionalparam="-breakiterator" destdir="${javadoc_dir}" overview="${build_dir}/overview.html" windowtitle="${javadoc_desc}" doctitle="${javadoc_desc}" access="${javadoc_level}"> <link href="http://java.sun.com/products/java-media/speech/forDevelopers/jsapi-doc" offline="true" packagelistLoc="lib/jsapi" /> <packageset dir="${src_dir}" defaultexcludes="yes"> <patternset refid="${patternset_to_doc}"/> </packageset> <packageset dir="${alt_src_dir}" defaultexcludes="yes"> <patternset refid="${patternset_to_doc}"/> </packageset> <classpath refid="libs"/> </javadoc> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Checks javadocs * --> <!-- * * --> <!-- ********************************************************** --> <target name="javadoc_check" depends="set_patternset_to_doc" description="checks the javadocs"> <mkdir dir="${javadoc_check_dir}"/> <javadoc sourcepath="${src_path}" additionalparam="-source 1.5" packagenames="edu.*" destdir="${javadoc_check_dir}" overview="${build_dir}/overview.html" doclet="com.sun.tools.doclets.doccheck.DocCheck" docletpath="/lab/speech/java/doccheck1.2b2/doccheck.jar" access="${javadoc_level}"> <classpath refid="libs"/> </javadoc> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Deletes all build output and *~ file droppings * --> <!-- * * --> <!-- ********************************************************** --> <target name="clean" description="Delete all build output"> <delete> <fileset defaultexcludes="no" dir="." includes="**/*~"/> <fileset defaultexcludes="no" dir="." includes="*.jar"/> <fileset defaultexcludes="no" dir="${src_dir}" includes="**/*~"/> <fileset defaultexcludes="no" dir="${alt_src_dir}" includes="**/*~"/> </delete> <delete dir="${classes_dir}"/> <delete dir="${javadoc_dir}"/> <delete dir="${exploded_dir}"/> <delete file="${lib_dir}/data-collection.war"/> </target> </project> <file_sep>/archive_s3/s3/src/libs3decoder/new_fe_sp.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #define int32 int #ifndef M_PI #define M_PI (3.14159265358979323846) #endif M_PI #define FORWARD_FFT 1 #define INVERSE_FFT -1 typedef struct { double r, i; } complex; /* functions */ int32 fe_build_melfilters(melfb_t *MEL_FB); int32 fe_compute_melcosine(melfb_t *MEL_FB); float fe_mel(float x); float fe_melinv(float x); void fe_pre_emphasis(int16 *in, double *out, int32 len, float factor, int16 prior); void fe_hamming_window(double *in, double *window, int32 in_len); void fe_create_hamming(double *win, int32 len); void fe_spec_magnitude(double *data, int32 data_len, double *spec, int32 fftsize); void fe_frame_to_fea(fe_t *FE, double *in, double *fea); void fe_mel_spec(fe_t *FE, double *spec, double *mfspec); void fe_mel_cep(fe_t *FE, double *mfspec, double *mfcep); int32 fe_fft(complex *in, complex *out, int32 N, int32 invert); void fe_short_to_double(int16 *in, double *out, int32 len); char **fe_create_2d(int32 d1, int32 d2, int32 elem_size); void fe_free_2d(void **arr); void fe_print_current(fe_t *FE); void fe_parse_general_params(param_t *P, fe_t *FE); void fe_parse_melfb_params(param_t *P, melfb_t *MEL); <file_sep>/SphinxTrain/include/s3/Makefile # ==================================================================== # Copyright (c) 2000 Carnegie Mellon University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 3. The names "Sphinx" and "Carnegie Mellon" must not be used to # endorse or promote products derived from this software without # prior written permission. To obtain permission, contact # <EMAIL>. # # 4. Redistributions of any form whatsoever must retain the following # acknowledgment: # "This product includes software developed by Carnegie # Mellon University (http://www.speech.cs.cmu.edu/)." # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Sphinx3 include files # # ==================================================================== TOP=../.. DIRNAME=include/s3 BUILD_DIRS = ALL_DIRS= H= \ acmod_set.h acmod_set_ds.h agc.h agc_emax.h agc_max.h array_io.h \ bcomment_io.h best_q.h bo_magic.h bquest_io.h btree.h cep_manip.h \ ck_seg.h ckd_alloc.h cmd_ln.h cmn.h common.h corpus.h \ cvt2triphone.h div.h dtree.h enum_subset.h err.h feat.h \ fgets_wo_nl.h floatbuf_io.h fp_cache.h fread_retry.h gauden.h gauden_io.h \ get_cpu_time.h get_host_name.h get_time.h hash.h heap.h int32_io.h \ intbuf_io.h itree.h kmeans.h lambda_io.h lda.h lexicon.h* \ live_norm.h matrix.h merge_den.h metric.h mixw_param_io.h mk_phone_list.h \ mk_phone_seq.h mk_sseq.h mk_trans_seq.h mk_ts2ci.h mk_wordlist.h mllr.h \ mllr_class_io.h mllr_io.h model_def.h model_def_io.h model_inventory.h \ n_words.h norm.h prefetch.h prefix_upto.h prim_type.h profile.h pset_io.h \ quest.h r_agc_noise.h read_line.h read_seno_dtree.h regmat_io.h remap.h \ s2_mixing_weights.h s2_param.h s2_read_cb.h s2_read_map.h s2_read_seno.h \ s2_read_tmat.h s2_write_cb.h s2_write_hmm.h s2_write_seno.h s2io.h s3.h \ s3_open.h s3cb2mllr_io.h s3acc_io.h s3gau_io.h s3io.h s3lamb_io.h s3map_io.h \ s3mixw_io.h s3regmat_io.h s3tmat_io.h s3ts2cb_io.h segdmp.h silcomp.h \ state.h state_param_def_io.h state_seq.h swap.h tmat_param_io.h topo_read.h \ ts2cb.h two_class.h uttfile.h vector.h was_added.h \ array_alloc.h timer.h s3phseg_io.h f2c.h clapack_lite.h FILES = Makefile $(H) ALL = include $(TOP)/config/common_make_rules <file_sep>/archive_s3/s3.3/src/tests/batch_metrics.c /* ==================================================================== * Copyright (c) 1999-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /******************************************************************** * * Adapted from src/programs/main_live_pretend.c * * Collects performance metrics, e.g., accuracy, runtimes * ********************************************************************/ #include <stdio.h> #include <string.h> #include <libutil/libutil.h> #include <libutil/profile.h> #include <libs3decoder/new_fe.h> #include "live_dump.h" #include "metrics.h" #define MAXSAMPLES 1000000 #define STRLEN 2048 #define MAX_REFERENCES 200 void showAccuracy(FILE *rfp); void showTiming(FILE *ftp, const char* name, double audioTime, double processingTime); void showMemory(FILE *rfp); void analyzeResults(const char* referenceResult, const char* parthyp); void addMatch(); void addInsert(); void addDeletion(); void addRecognitionError(); void processMismatch(char *references[], int numReferences, char *parthyp[], int numHypothesis); int countMatches(char *references[], int r, int numReferences, char *parthyp[], int h, int numHypothesis); int stringToArray(char *string, char *array[]); void stringToLowerCase(char *string); void partialHypToString(partialhyp_t *parthyp, int nhypwds, char* hypothesis, int bufferSize); int isFillerWord(char *string); void stringRemoveEndingParenthesis(char *string); int numSentences; int numRefWords; int numHypWords; int numMatchingWords; int numMatchingSentences; int recognitionErrors; int insertionErrors; int deletionErrors; int referenceIndex; int hypothesisIndex; int main (int argc, char *argv[]) { short *samps; int i, buflen, endutt, blksize, nhypwds, nsamp; int numberFiles; int space, lastChar; double sampleRate; double totalAudioTime; double totalProcessingTime; double audioTime; double processingTime; char *argsfile, *ctlfile, *indir, *filename, *referenceResult; char cepfile[STRLEN]; char line[STRLEN], hypothesis[STRLEN]; char *fileTimer = "file"; partialhyp_t *parthyp; FILE *fp, *sfp, *rfp; setbuf(stdout, NULL); setbuf(stderr, NULL); space = ' '; numberFiles = 0; sampleRate = 8000; endutt = 0; totalAudioTime = 0.0; totalProcessingTime = 0.0; audioTime = 0.0; processingTime = 0.0; numSentences = 0; numRefWords = 0; numHypWords = 0; numMatchingWords = 0; numMatchingSentences = 0; recognitionErrors = 0; insertionErrors = 0; deletionErrors = 0; if (argc != 4) { E_FATAL("\nUSAGE: %s <ctlfile> <inrawdir> <argsfile>\n", argv[0]); } ctlfile = argv[1]; indir = argv[2]; argsfile = argv[3]; samps = (short *) calloc(MAXSAMPLES,sizeof(short)); blksize = 2000; if ((fp = fopen(ctlfile,"r")) == NULL) E_FATAL("Unable to read %s\n",ctlfile); rfp = stdout; fprintf(rfp, "BatchDecoder: decoding files in %s\n----------\n", ctlfile); live_initialize_decoder(argsfile); while (fgets(line, STRLEN, fp) != NULL) { /* Parse the speech file and the reference result. */ referenceResult = strchr(line, space); if (referenceResult == NULL) { E_FATAL("No reference result\n", cepfile); } else { referenceResult++; } lastChar = strlen(referenceResult) - 1; if (referenceResult[lastChar] == '\n') { referenceResult[lastChar] = '\0'; } filename = strtok(line, " "); numberFiles++; nhypwds = 0; sprintf(cepfile,"%s/%s",indir,filename); fprintf(rfp, "\nDecoding: %s\n\n", cepfile); if ((sfp = fopen(cepfile,"rb")) == NULL) E_FATAL("Unable to read %s\n",cepfile); E_INFO("\nDecoding: %s\n\n", cepfile); nsamp = fread(samps, sizeof(short), MAXSAMPLES, sfp); fflush(stdout); fclose(sfp); if (needswap) { for (i = 0; i < nsamp; i++) { SWAPW(samps + i); } } metricsReset(fileTimer); metricsStart(fileTimer); for (i = 0; i < nsamp; i += blksize) { buflen = i+blksize < nsamp ? blksize : nsamp-i; endutt = i+blksize <= nsamp-1 ? 0 : 1; nhypwds = live_utt_decode_block(samps+i,buflen,endutt,&parthyp); } metricsStop(fileTimer); if (endutt && nhypwds > 0) { /* convert the hypothesis into a string */ partialHypToString(parthyp, nhypwds, hypothesis, STRLEN); /* convert the referenceResult to lowercase */ stringToLowerCase(referenceResult); stringToLowerCase(hypothesis); /* * If hypothesis is equal to referenceResult * increment the number of matches */ fprintf(rfp, "REF: %s\n", referenceResult); fprintf(rfp, "HYP: %s\n", hypothesis); analyzeResults(referenceResult, hypothesis); showAccuracy(rfp); } /* collect the processing times data */ processingTime = metricsDuration(fileTimer); audioTime = ((double) nsamp) / sampleRate; totalProcessingTime += processingTime; totalAudioTime += audioTime; showTiming(rfp, "This", audioTime, processingTime); showTiming(rfp, "Total", totalAudioTime, totalProcessingTime); showMemory(rfp); fprintf(rfp, "# --------------\n"); } live_print_profiles(rfp); metricsPrint(); fprintf(rfp, "# ------------- Summary statistics -----------\n"); showAccuracy(rfp); showTiming(rfp, "Total", totalAudioTime, totalProcessingTime); showMemory(rfp); return 0; } /** * Converts the words in the given partialhyp_t struct into a string. * * @param parthyp the partial hypothesis struct to extract words from * @param nhypwds number of words in the partial hypothesis struct * @param hypothesis the string to put hypothesized words into * @param bufferSize length of hypothesis char array */ void partialHypToString(partialhyp_t *parthyp, int nhypwds, char* hypothesis, int bufferSize) { char* word; int j; hypothesis[0] = '\0'; for (j = 0; j < nhypwds; j++) { word = parthyp[j].word; if (strcmp(word, "<sil>") != 0 && (strcmp(word, "<s>") != 0 && (strcmp(word, "</s>") != 0 && isFillerWord(word) != 1))) { stringRemoveEndingParenthesis(word); if (strlen(hypothesis) > 0) { strcat(hypothesis, " "); } strcat(hypothesis, word); } } } /** * If the given string has a pair of ending parenthesis, * a return the string without the parenthesis. */ void stringRemoveEndingParenthesis(char *string) { int i; int length; length = strlen(string); /* if it ends with ')' */ if (length > 1 && string[length-1] == ')') { for (i = length - 2; i >= 0; i--) { if (string[i] == '(') { string[i] = '\0'; } } } } void showAccuracy(FILE *rfp) { float wordAccuracy = ((float) numMatchingWords)/((float) numRefWords) * 100.0; float sentenceAccuracy = ((float) numMatchingSentences) / ((float) numSentences) * 100.0; int totalErrors = recognitionErrors + insertionErrors + deletionErrors; fprintf(rfp, " Accuracy: %%%.1f Errors: %d (Rec: %d Ins: %d Del: %d)\n", wordAccuracy, totalErrors, recognitionErrors, insertionErrors, deletionErrors); fprintf(rfp, " Words: %d Matches: %d\n", numRefWords, numMatchingWords); fprintf(rfp, " Sentences: %d Matches: %d SentenceAcc: %%%.1f\n", numSentences, numMatchingSentences, sentenceAccuracy); } void showTiming(FILE *rfp, const char* name, double audioTime, double processingTime) { fprintf(rfp, " %s Timing Audio: %.1fs Proc: %.1fs Speed: %.2f X real time\n", name, audioTime, processingTime, (processingTime/audioTime)); } void showMemory(FILE *rfp) { fprintf(rfp, " Memory usage data unavailable\n"); } /** * Compare the hypothesis to the reference string collecting * statistics on it. * * @param ref the reference string * @param hyp the hypothesis string */ void analyzeResults(const char* referenceResult, const char* hypotheses) { int numReferences; int numHypothesis; char *references[MAX_REFERENCES]; char myReferenceResult[STRLEN]; /* copy because we will modify it */ char *hypothesis[MAX_REFERENCES]; char myHypothesis[STRLEN]; strcpy(myReferenceResult, referenceResult); numReferences = stringToArray(myReferenceResult, references); referenceIndex = 0; strcpy(myHypothesis, hypotheses); numHypothesis = stringToArray(myHypothesis, hypothesis); hypothesisIndex = 0; numRefWords += numReferences; numHypWords += numHypothesis; numSentences++; while (referenceIndex < numReferences || hypothesisIndex < numHypothesis) { if (referenceIndex >= numReferences) { addInsert(); } else if (hypothesisIndex >= numHypothesis) { addDeletion(); } else if (strcmp(references[referenceIndex], hypothesis[hypothesisIndex]) != 0) { processMismatch(references, numReferences, hypothesis, numHypothesis); } else { addMatch(); } } if (strcmp(myReferenceResult, myHypothesis) == 0) { numMatchingSentences++; } } /** * Add an insertion error corresponding to the first item * on the hypList */ void addInsert() { insertionErrors++; hypothesisIndex++; } /** * Add a deletion error corresponding to the first item * on the refList */ void addDeletion() { deletionErrors++; referenceIndex++; } /** * Add a recognition error */ void addRecognitionError() { recognitionErrors++; referenceIndex++; hypothesisIndex++; } /** * Add a match. */ void addMatch() { numMatchingWords++; referenceIndex++; hypothesisIndex++; } /** * Process a mismatch by seeing which type of error is most likely */ void processMismatch(char *references[], int numReferences, char *parthyp[], int numHypothesis) { int deletionMatches; int insertMatches; int normalMatches; deletionMatches = countMatches(references, referenceIndex+1, numReferences, parthyp, hypothesisIndex, numHypothesis); insertMatches = countMatches(references, referenceIndex, numReferences, parthyp, hypothesisIndex+1, numHypothesis); normalMatches = countMatches(references, referenceIndex, numReferences, parthyp, hypothesisIndex, numHypothesis); if (deletionMatches > insertMatches && deletionMatches > normalMatches) { addDeletion(); } else if (insertMatches > deletionMatches && insertMatches > normalMatches) { addInsert(); } else { addRecognitionError(); } } /** * Counts the number of matches between the two lists * starting at the respective indexes * * @param refList the list of reference words * @param r the starting point in the ref list * @param numReferences the number of reference words * @param hypList the list of hypothesis words * @param h the starting point in the hyp list * @param numHypothesis the number of hypotheses * * @return the number of matching words */ int countMatches(char *references[], int r, int numReferences, char *parthyp[], int h, int numHypothesis) { int match; match = 0; while (r < numReferences && h < numHypothesis) { if (strcmp(references[r++], parthyp[h++]) == 0) { match++; } } return match; } /** * Converts the individual words in the string into an array of strings. * * @param string the string to convert * @param array the array of string pointers * @param skipFillerWords non-zero to skip filler words, 0 to no skip them * * @return the number of words */ int stringToArray(char *string, char *array[]) { int i, c, length; i = 0; length = strlen(string); if (length > 0) { array[i++] = string; for (c = 0; c < length; c++) { if (string[c] == ' ') { string[c++] = '\0'; /* skip all blanks */ while (string[c] == ' ') { c++; } /* start a new word only if its not the end of the string */ if (string[c] != '\0') { array[i++] = &string[c]; } } } } return i; } /** * Returns 1 if the given string is a filler word, 0 if not. * * @param string the string to test */ int isFillerWord(char *string) { if (strlen(string) > 1) { if (string[0] == '+' && string[1] == '+') { return 1; } } return 0; } /** * Converts the given string to uppercase in place. * * @param string the string to be converted */ void stringToLowerCase(char *string) { int i, length; length = strlen(string); for (i = 0; i < length; i++) { string[i] = tolower(string[i]); } } <file_sep>/SphinxTrain/python/cmusphinx/test_arpalm.py #!/usr/bin/env python import arpalm import unittest import os import sys import math LOG10TOLOG = math.log(10) class TestArpaLM(unittest.TestCase): def setUp(self): thisdir = os.path.dirname(sys.argv[0]) self.testdir = os.path.join(thisdir, 'test') def test_load(self): lm = arpalm.ArpaLM(os.path.join(self.testdir, "100.arpa.gz")) self.assert_(abs(lm.score('addition') - (-3.2721 * LOG10TOLOG)) < 0.01) self.assert_(abs(lm.score('zero', 'variance', 'vector') - (-0.9404 * LOG10TOLOG)) < 0.01) # Backoff with backoff weight self.assert_(abs(lm.score('zero', 'variance', 'parameters') - ((-1.3188 + -0.8170) * LOG10TOLOG)) < 0.01) # Backoff without backoff weight self.assert_(abs(lm.score('abnormal', 'variance', 'vector') - (-0.8378 * LOG10TOLOG)) < 0.01) if __name__ == '__main__': unittest.main() <file_sep>/CLP/src/Make.depend # -*- Makefile -*- CXX = g++ CC = gcc LIBPATH = -L/usr/lib INCPATH = -I${INCDIR} -I/usr/include/g++ -I/usr/tools/include/g++ -I/usr/tools/include -I../src -I/usr/local/include/g++ -I/usr/include # math library LDLIBS = -lm # optimizations for this architecture # ARCHOPTIM = -mcpu=pentiumpro # for optimizing OPTIM = -O3 -ffast-math # for seeing warnings and debugging #OPTIM = -g -DDEBUG=3 # for profiling #OPTIM = -g -pg -O3 # this is required for old SunOS #OPTIONS = -D__USE_FIXED_PROTOTYPES__ -DFLOAT=float -fexceptions -frtti -m486 #OPTIONS = -mcpu=pentiumpro #WARNS = -Wall -fguiding-decls #WARNS = -Wall WARNS = -w CXXFLAGS = ${OPTIM} ${OPTIONS} ${WARNS} ${LIBPATH} ${INCPATH} CCFLAGS = ${OPTIM} ${OPTIONS} ${WARNS} ${LIBPATH} ${INCPATH} CFLAGS = $(CCFLAGS) LD = ${CXX} ${CXXFLAGS} # 2 lines for sunOS CCC = ${CXX} BINDIR = ../bin INCDIR = ../include SRCDIR = ../src TESTDIR = ../test TARGETS = ${BINDIR}/Consensus ${BINDIR}/Consensus_print makefile: depend all: includes ${TARGETS} clean: -${RM} *.o ../lib/*.a *~ sterile: clean -${RM} *.rpo -${RM} ${TARGETS} distclean: sterile -${RM} makefile remake: clean depend ${MAKE} # figure out the dependencies depend: -$(RM) makefile grep -v '^makefile' Make.depend > makefile echo "" >> makefile echo "# Automatically generated dependencies" >> makefile echo "" >> makefile -${CXX} ${INCPATH} -M *.cc >> makefile Consensus: ${INCDIR}/common.h ${INCDIR}/GetOpt.h ${INCDIR}/Lattice.h ${INCDIR}/Prob.h ${INCDIR}/LineSplitter.h ${INCDIR}/Prons.h ${INCDIR}/Cluster.h ${INCDIR}/Clustering.h ${INCDIR}/Link.h ${INCDIR}/Node.h ${INCDIR}/common_lattice.h ${INCDIR}/Similarities.h ${SRCDIR}/common.cc ${SRCDIR}/GetOpt.cc ${SRCDIR}/Lattice.cc ${SRCDIR}/LineSplitter.cc ${SRCDIR}/Prons.cc ${SRCDIR}/Cluster.cc ${SRCDIR}/Clustering.cc ${SRCDIR}/Similarities.cc common.o GetOpt.o Lattice.o LineSplitter.o Prons.o Cluster.o Clustering.o Similarities.o $(CCC) $(CCFLAGS) -o ${BINDIR}/Consensus Consensus.cc common.o GetOpt.o Lattice.o LineSplitter.o Prons.o Cluster.o Clustering.o Similarities.o $(LDLIBS) Consensus_print: ${INCDIR}/common.h ${INCDIR}/GetOpt.h ${INCDIR}/Lattice.h ${INCDIR}/Prob.h ${INCDIR}/LineSplitter.h ${INCDIR}/Prons.h ${INCDIR}/Cluster.h ${INCDIR}/Clustering.h ${INCDIR}/Link.h ${INCDIR}/Node.h ${INCDIR}/common_lattice.h ${INCDIR}/Similarities.h ${SRCDIR}/common.cc ${SRCDIR}/GetOpt.cc ${SRCDIR}/Lattice.cc ${SRCDIR}/LineSplitter.cc ${SRCDIR}/Prons.cc ${SRCDIR}/Cluster.cc ${SRCDIR}/Clustering_print.cc ${SRCDIR}/Similarities.cc common.o GetOpt.o Lattice.o LineSplitter.o Prons.o Cluster.o Clustering_print.o Similarities.o $(CCC) $(CCFLAGS) -o ${BINDIR}/Consensus_print Consensus_print.cc common.o GetOpt.o Lattice.o LineSplitter.o Prons.o Cluster.o Clustering_print.o Similarities.o $(LDLIBS) <file_sep>/cmuclmtk/src/programs/idngram.h /* ==================================================================== * Copyright (c) 1999-2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* Stuff that is common to both text2idngram and wngram2idngram */ int n; /* Declare it globally, so doesn't need to be passed as a parameter to compare_ngrams. which might cause qsort to choke */ #include "../liblmest/ngram.h" #include "../liblmest/stats.h" int compare_ngrams3(const void *ngram1, const void *ngram2 ) { int i; wordid_t *ngram_pointer1; wordid_t *ngram_pointer2; ngram_pointer1 = (wordid_t *) ngram1; ngram_pointer2 = (wordid_t *) ngram2; for (i=0;i<n;i++) { if (ngram_pointer1[i]<ngram_pointer2[i]) return(1); else { if (ngram_pointer1[i]>ngram_pointer2[i]) return(-1); } } return(0); } void merge_tempfiles (int start_file, int end_file, char *temp_file_root, char *temp_file_ext, int max_files, FILE *outfile, flag write_ascii, int fof_size) { FILE *new_temp_file; char temp_string[1000]; char *new_temp_filename; FILE **temp_file; char **temp_filename; wordid_t **current_ngram; wordid_t *smallest_ngram; wordid_t *previous_ngram; int *current_ngram_count; flag *finished; flag all_finished; int temp_count; int i,j; flag first_ngram; fof_t **fof_array; ngram_sz_t *num_kgrams; int *ng_count; int pos_of_novelty; pos_of_novelty = n; /* Simply for warning-free compilation */ num_kgrams = (ngram_sz_t *) rr_calloc(n-1,sizeof(ngram_sz_t)); ng_count = (int *) rr_calloc(n-1,sizeof(int)); first_ngram = 1; previous_ngram = (wordid_t *) rr_calloc(n,sizeof(wordid_t)); temp_file = (FILE **) rr_malloc(sizeof(FILE *) * (end_file-start_file+1)); temp_filename = (char **) rr_malloc(sizeof(char *) * (end_file-start_file+1)); /* should change to 2d array*/ current_ngram = (wordid_t **) rr_malloc(sizeof(wordid_t *) * (end_file-start_file+1)); for (i=0;i<=end_file-start_file;i++) current_ngram[i] = (wordid_t *) rr_malloc(sizeof(wordid_t)*n); current_ngram_count = (int *) rr_malloc(sizeof(int)*(end_file-start_file+1)); finished = (flag *) rr_malloc(sizeof(flag)*(end_file-start_file+1)); smallest_ngram = (wordid_t *) rr_malloc(sizeof(wordid_t)*n); /* should change to 2d array*/ fof_array = (fof_t **) rr_malloc(sizeof(fof_t *)*(n-1)); for (i=0;i<=n-2;i++) fof_array[i] = (fof_t *) rr_calloc(fof_size+1,sizeof(fof_t)); if (end_file-start_file+1 > max_files) { sprintf(temp_string,"%s%hu%s",temp_file_root, end_file+1,temp_file_ext); new_temp_filename = salloc(temp_string); new_temp_file = rr_oopen(new_temp_filename); merge_tempfiles(start_file,start_file+max_files-1, temp_file_root,temp_file_ext,max_files, new_temp_file,write_ascii,0); merge_tempfiles(start_file+max_files,end_file+1, temp_file_root,temp_file_ext,max_files, outfile,write_ascii,0); }else { /* Open all the temp files for reading */ for (i=0;i<=end_file-start_file;i++) { sprintf(temp_string,"%s%hu%s",temp_file_root, i+start_file,temp_file_ext); temp_filename[i] = salloc(temp_string); temp_file[i] = rr_iopen(temp_filename[i]); } /* Now go through the files simultaneously, and write out the appropriate ngram counts to the output file. */ for (i=end_file-start_file;i>=0;i--) { finished[i] = 0; if (!rr_feof(temp_file[i])) { for (j=0;j<=n-1;j++) { rr_fread((char*) &current_ngram[i][j], sizeof(wordid_t),1, temp_file[i],"temporary n-gram ids",0); } rr_fread((char*) &current_ngram_count[i], sizeof(int),1, temp_file[i],"temporary n-gram counts",0); } } all_finished = 0; while (!all_finished) { /* Find the smallest current ngram */ for (i=0;i<=n-1;i++) smallest_ngram[i] = MAX_WORDID; for (i=0;i<=end_file-start_file;i++) { if (!finished[i]) { if (compare_ngrams3(smallest_ngram,current_ngram[i]) < 0) { for (j=0;j<n;j++) smallest_ngram[j] = current_ngram[i][j]; } } } #if MAX_VOCAB_SIZE < 65535 /* This check is well-meaning but completely useless since smallest_ngram[i] by definition cannot contain any value greater than MAX_VOCAB_SIZE (dhuggins@cs, 2006-03) */ for (i=0;i<=n-1;i++) { if (smallest_ngram[i] > MAX_VOCAB_SIZE) { quit(-1,"Error : Temporary files corrupted, invalid n-gram found.\n"); } } #endif /* For each of the files that are currently holding this ngram, add its count to the temporary count, and read in a new ngram from the files. */ temp_count = 0; for (i=0;i<=end_file-start_file;i++) { if (!finished[i]) { if (compare_ngrams3(smallest_ngram,current_ngram[i]) == 0) { temp_count = temp_count + current_ngram_count[i]; if (!rr_feof(temp_file[i])) { for (j=0;j<=n-1;j++) { rr_fread((char*) &current_ngram[i][j],sizeof(wordid_t),1, temp_file[i],"temporary n-gram ids",0); } rr_fread((char*)&current_ngram_count[i],sizeof(int),1, temp_file[i],"temporary n-gram count",0); }else { finished[i] = 1; all_finished = 1; for (j=0;j<=end_file-start_file;j++) { if (!finished[j]) all_finished = 0; } } } } } if (write_ascii) { for (i=0;i<=n-1;i++) { if (fprintf(outfile,"%d ",smallest_ngram[i]) < 0) { quit(-1,"Write error encountered while attempting to merge temporary files.\nAborting, but keeping temporary files.\n"); } } if (fprintf(outfile,"%d\n",temp_count) < 0) quit(-1,"Write error encountered while attempting to merge temporary files.\nAborting, but keeping temporary files.\n"); }else { for (i=0;i<=n-1;i++) { rr_fwrite((char*)&smallest_ngram[i],sizeof(wordid_t),1, outfile,"n-gram ids"); } rr_fwrite((char*)&temp_count,sizeof(count_t),1,outfile,"n-gram counts"); } if (fof_size > 0 && n>1) { /* Add stuff to fof arrays */ /* Code from idngram2stats */ pos_of_novelty = n; for (i=0;i<=n-1;i++) { if (smallest_ngram[i] > previous_ngram[i]) { pos_of_novelty = i; i=n; } } /* Add new N-gram */ num_kgrams[n-2]++; if (temp_count <= fof_size) fof_array[n-2][temp_count]++; if (!first_ngram) { for (i=n-2;i>=MAX(1,pos_of_novelty);i--) { num_kgrams[i-1]++; if (ng_count[i-1] <= fof_size) { fof_array[i-1][ng_count[i-1]]++; } ng_count[i-1] = temp_count; } }else { for (i=n-2;i>=MAX(1,pos_of_novelty);i--) { ng_count[i-1] = temp_count; } first_ngram = 0; } for (i=0;i<=pos_of_novelty-2;i++) ng_count[i] += temp_count; for (i=0;i<=n-1;i++) previous_ngram[i]=smallest_ngram[i]; } } for (i=0;i<=end_file-start_file;i++) { fclose(temp_file[i]); remove(temp_filename[i]); } } if (fof_size > 0 && n>1) { /* Display fof arrays */ /* Process last ngram */ for (i=n-2;i>=MAX(1,pos_of_novelty);i--) { num_kgrams[i-1]++; if (ng_count[i-1] <= fof_size) fof_array[i-1][ng_count[i-1]]++; ng_count[i-1] = temp_count; } for (i=0;i<=pos_of_novelty-2;i++) ng_count[i] += temp_count; display_fof_array(num_kgrams,fof_array,fof_size,stderr, n); } } <file_sep>/SphinxTrain/include/s3/ckd_alloc.h /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * file: ckd_alloc.h * * traceability: * * description: * * author: * *********************************************************************/ #ifndef CKD_ALLOC_H #define CKD_ALLOC_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <stdlib.h> #define ckd_salloc(s) __ckd_salloc((s), __FILE__, __LINE__) #define ckd_calloc(d1, s) __ckd_calloc((d1), (s), __FILE__, __LINE__) #define ckd_malloc(s) __ckd_malloc((s), __FILE__, __LINE__) #define ckd_realloc(p, s) __ckd_realloc((p), (s), __FILE__, __LINE__) #define ckd_free(p) __ckd_free((p), __FILE__, __LINE__) /* array storage management */ #define ckd_calloc_2d(d1, d2, s) __ckd_calloc_2d((d1), (d2), (s), __FILE__, __LINE__) #define ckd_free_2d(p) __ckd_free_2d((p), __FILE__, __LINE__) #define ckd_alloc_2d_ptr(d1, d2, bf, sz) __ckd_alloc_2d_ptr((d1), (d2), (bf), (sz), __FILE__, __LINE__) #define ckd_calloc_3d(d1, d2, d3, s) __ckd_calloc_3d((d1), (d2), (d3), (s), __FILE__, __LINE__) #define ckd_free_3d(p) __ckd_free_3d((p), __FILE__, __LINE__) #define ckd_alloc_3d_ptr(d1, d2, d3, bf, sz) __ckd_alloc_3d_ptr((d1), (d2), (d3), (bf), (sz), __FILE__, __LINE__) #define ckd_calloc_4d(d1, d2, d3, d4, s) __ckd_calloc_4d((d1), (d2), (d3), (d4), (s), __FILE__, __LINE__) #define ckd_free_4d(p) __ckd_free_4d((p), __FILE__, __LINE__) char * __ckd_salloc(char *string, char *caller_file, int caller_line); void * __ckd_calloc(size_t n_elem, size_t elem_size, char *caller_file, int caller_line); void ** __ckd_calloc_2d(size_t d1, size_t d2, size_t elem_size, char *caller_file, int caller_line); void __ckd_free_2d(void **ptr, char *caller_file, int caller_line); void *** __ckd_calloc_3d(size_t d1, size_t d2, size_t d3, size_t elem_size, char *caller_file, int caller_line); void __ckd_free_3d(void ***ptr, char *caller_file, int caller_line); void **** __ckd_calloc_4d(size_t d1, size_t d2, size_t d3, size_t d4, size_t elem_size, char *caller_file, int caller_line); void __ckd_free_4d(void ****ptr, char *caller_file, int caller_line); void * __ckd_malloc(size_t size, char *caller_file, int caller_line); void * __ckd_realloc(void *ptr, size_t new_size, char *caller_file, int caller_line); void __ckd_free(void *ptr, char *caller_file, int caller_line); void *** __ckd_alloc_3d_ptr(int d1, int d2, int d3, void *store, size_t elem_size, char *caller_file, int caller_line); void ** __ckd_alloc_2d_ptr(int d1, int d2, void *store, size_t elem_size, char *caller_file, int caller_line); #ifdef __cplusplus } #endif #endif /* CKD_ALLOC_H */ /* * Log record. Maintained by CVS. * * $Log$ * Revision 1.4 2004/07/21 17:46:08 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.7 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.6 96/07/29 16:40:50 eht * add array allocation here so that I don't * go crazy trying to remember the function call names * * Revision 1.5 1996/02/02 17:58:00 eht * Add ckd_salloc macro * * Revision 1.4 1996/02/02 17:49:27 eht * Added ckd_salloc function * * Revision 1.3 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.2 1995/10/09 20:29:52 eht * New interface/macros that remove need for __FILE__, __LINE__ args * * Revision 1.1 1995/08/15 13:44:14 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/cdcn_train/em_full_vars.c /* ==================================================================== * Copyright (c) 1994-2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^* Program to compute a Multimodal gaussian distribution for a given data set. Estimates DIAGNOAL covariances ONLY (i.e all modes are assumed to have diagonal covariance matrices). Does NOT compute optimal number of modes; has to be given the number of modes required. The routine runs a variable number of iterations of EM each time it is called. The number of iterations is passed as a variable The parameters passed are x[][] - the data set (float) N - the number of vectors in the data set (int) Ndim - the dimensionality of the dataset (int) K - the number of modes required in the computed distribution (int) mean[][] - Some initial values for the means of the gaussians(float) var[][] - Initial values for the Variances of the modes(float) c[] - Initial values for the a-priori probabilities(float) tempfile - File to store partially converged distributions to numiters - Number of EM iterations to run Before passing to this routing mean, var and c have to be initialized. The mean, var and c values can be initialized by doing a quick VQ on the data and using the means,variances and population ratios of each of the bins for initial values. The returned values are c[] - the a-priori probabilities of each of the modes, i.e the mixing proportions (float) mean[][] - the means of the modes (float) var[][] - the variances of the modes (float) Note - This program requires that the varibles x[][], mean[][] and var[][] have been allocated using the alloc2d() routine! Coded by <NAME> Incoroporated excellent changes by PJM - Begin working in the log domain to eliminate corprod scaling problems. Dec 95 *vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "header.h" #define QUIT(x) {printf x; fflush (stdout); exit(-1);} /*---------------------------------------------------------------------------- Routine to compute the a-posteriori probabilities of each of the modes in the Mixture distribution defined by c,mean and var for the the vector defined by x[]. Returns the posteriors in Tau[] ------------------------------------------------------------------------------*/ float Expectation(float *Tau, /* Mode probablity of observation vector x */ float *x, /* Observation vector x */ float *c, /* Mixing proportions of modes */ float **mean, /* Means of the modes */ float **hafinvvar, /* 1.0/(2.0*variance) of the modes */ float *corprod, /* Precomputed 1/sqrt(2PI**Ndim * mod(variance)) */ int K, /* Number of modes */ int Ndim /* Dimensionality of observation/distribution */ ) { float Probability, max, sum, invsum; int i; Tau[0] = max = gauss(x, mean[0], hafinvvar[0], corprod[0], Ndim); for (i = 1; i < K; ++i) { /* * Note: prior c[i] has already been factored into corprod */ Tau[i] = gauss(x, mean[i], hafinvvar[i], corprod[i], Ndim); if (Tau[i] > max) max = Tau[i]; } /* convert Tau from log to linear */ sum = 0.0; for (i = 0; i < K; ++i) { if (Tau[i] > max - 22) { /* only consider probs within 10^10 of max */ Tau[i] = exp(Tau[i] - max + 10); sum += Tau[i]; } else Tau[i] = 0; } invsum = 1.0 / sum; for (i = 0; i < K; ++i) Tau[i] *= invsum; Probability = max + log(sum) - 10; return (Probability); } void estimate_multi_modals(float **x, /* The observation vectors */ int N, /* Number of observation vectors */ int Ndim, /* Dimensionality of observations */ int K, /* Number of modes in the distribution */ float **mean, /* The means of the various modes */ float **var, /* The variances of all the modes */ float *c, /* A-priori probabilities of each of the modes, or mixing proportion */ char *tempfile, /* File to store temporary distributions */ int numiters, /* Number of iterations of EM to run */ float Threshold /* Convergence ratio */ ) { float **Newvar, **hafinvvar, **Newmean, *Newc, *Tau, *corprod, Const, SumNewc, Prevlogprob, LogProb, Improvement; int i, j, k, iter = 0; FILE *temp; /* * The Constant term that occurs in the computation of the gaussians. * As it turns out, we never use it. This one is a dummy :-) */ Const = pow(2 * PI, (Ndim / 2)); /* * some initializations */ Improvement = 100; /* * Allocate spaces for the local parameter arrays */ Newmean = (float **) ckd_calloc_2d(K, Ndim, sizeof(float)); Newvar = (float **) ckd_calloc_2d(K, Ndim, sizeof(float)); hafinvvar = (float **) ckd_calloc_2d(K, Ndim, sizeof(float)); Newc = (float *) ckd_calloc(K, sizeof(float)); Tau = (float *) ckd_calloc(K, sizeof(float)); corprod = (float *) ckd_calloc(K, sizeof(float)); /* * Initialize all New values to 0 * Note the array position computation for Newmean, as it is a 1-D array */ for (k = 0; k < K; ++k) { Newc[k] = 0; for (j = 0; j < Ndim; ++j) { Newmean[k][j] = 0; Newvar[k][j] = 0; } } /* * Compute the ratio of the prior probabilities of the modulus of the * variance. We do this operation in the log domain to keep the * dynamic range in check */ for (k = 0; k < K; ++k) { corprod[k] = log((double) c[k]); for (j = 0; j < Ndim; ++j) { corprod[k] -= 0.5 * log((double) var[k][j]); if (var[k][j] > 0) hafinvvar[k][j] = 1.0 / (2.0 * var[k][j]); else hafinvvar[k][j] = 1e+20; } } /* * Estimate means and variances and priors while computing overall * Likelihood * Note: variance estimated as Sum((x-mean)*(x-mean))/count * rather than Sum(x*x)/count - mean*mean * because the latter is an unstable formula and tends to give -ve * variances due to numerical errors */ Prevlogprob = 0; for (i = 0; i < N; ++i) { Prevlogprob += Expectation(Tau, x[i], c, mean, hafinvvar, corprod, K, Ndim); for (k = 0; k < K; ++k) { if (Tau[k] > 0) { Newc[k] += Tau[k]; for (j = 0; j < Ndim; ++j) Newmean[k][j] += Tau[k] * x[i][j]; } } } for (k = 0; k < K; ++k) for (j = 0; j < Ndim; ++j) Newmean[k][j] /= Newc[k]; for (i = 0; i < N; ++i) { Expectation(Tau, x[i], c, mean, hafinvvar, corprod, K, Ndim); for (k = 0; k < K; ++k) { if (Tau[k] > 0) { for (j = 0; j < Ndim; ++j) Newvar[k][j] += Tau[k] * (x[i][j] - Newmean[k][j]) * (x[i][j] - Newmean[k][j]); } } } printf("EM : Initial log probablity = %f \n", Prevlogprob); while ((Improvement > Threshold) && (iter < numiters)) { /* * We use SumNewc instead of N as in the formula because the * Newc's may not sum to N, because of accuracy errors of the * computer for large N. */ SumNewc = 0; for (k = 0; k < K; ++k) SumNewc += Newc[k]; for (k = 0; k < K; ++k) { for (j = 0; j < Ndim; ++j) { mean[k][j] = Newmean[k][j]; var[k][j] = Newvar[k][j] / Newc[k]; } c[k] = Newc[k] / SumNewc; } /* * Store partially converged distribution */ temp = fopen(tempfile, "w"); fprintf(temp, "%d %d\n", K, Ndim); for (i = 0; i < K; ++i) { fprintf(temp, "%f\n", c[i]); for (j = 0; j < Ndim; ++j) fprintf(temp, "%f ", mean[i][j]); fprintf(temp, "\n"); for (j = 0; j < Ndim; ++j) fprintf(temp, "%f ", var[i][j]); fprintf(temp, "\n"); } fclose(temp); /* * Initialize all New values to 0 */ for (k = 0; k < K; ++k) { Newc[k] = 0; for (j = 0; j < Ndim; ++j) { Newmean[k][j] = 0; Newvar[k][j] = 0; } } /* * Compute the ratio of the prior probabilities of the modulus of the * variance. We do this operation in the log domain to keep the * dynamic range in check */ for (k = 0; k < K; ++k) { corprod[k] = log((double) c[k]); for (j = 0; j < Ndim; ++j) { corprod[k] -= 0.5 * log((double) var[k][j]); if (var[k][j] > 0) hafinvvar[k][j] = 1.0 / (2.0 * var[k][j]); else hafinvvar[k][j] = 1e+20; } } LogProb = 0; for (i = 0; i < N; ++i) { LogProb += Expectation(Tau, x[i], c, mean, hafinvvar, corprod, K, Ndim); for (k = 0; k < K; ++k) { if (Tau[k] > 0) { Newc[k] += Tau[k]; for (j = 0; j < Ndim; ++j) { Newmean[k][j] += Tau[k] * x[i][j]; Newvar[k][j] += Tau[k] * (x[i][j] - mean[k][j]) * (x[i][j] - mean[k][j]); } } } } for (k = 0; k < K; ++k) for (j = 0; j < Ndim; ++j) Newmean[k][j] /= Newc[k]; /* for (i=0;i<N;++i) { Expectation(Tau,x[i],c,mean,hafinvvar,corprod,K,Ndim); for (k=0; k<K ; ++k) { for (j=0;j<Ndim;++j) Newvar[k][j] += Tau[k] * (x[i][j] - Newmean[k][j]) * (x[i][j] - Newmean[k][j]); } } */ Improvement = (LogProb - Prevlogprob) / LogProb; if (LogProb < 0) Improvement = -Improvement; ++iter; printf ("EM : Log Prob = %f, improvement = %f after %d iterations\n", LogProb, Improvement, iter); fflush(stdout); Prevlogprob = LogProb; } /* * Free local arrays */ ckd_free(Tau); ckd_free(corprod); ckd_free_2d((void **)Newvar); ckd_free_2d((void **)Newmean); ckd_free(Newc); return; } <file_sep>/SphinxTrain/src/programs/kmeans_init/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * This file defines the command line arguments for kmeans_init * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <sys_compat/misc.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ Using the segment dump file generated by external software such as \n\ agg_seg to initilaize the model. It performs k-mean clustering to \n\ create the initial means and variances for s2 hmms. This is an \n\ important process of initialization of s2 training. "; const char examplestr[]= "Example : \n\ \n\ kmeans_init -gthobj single -stride 1 -ntrial 1 -minratio 0.001 \n\ -ndensity 256 -meanfn $outhmm/means -varfn $outhmm/variances -reest no \n\ -segdmpdirs $segdmpdir -segdmpfn $dumpfile -ceplen 13"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-segdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Directory containing the state segmentations" }, { "-segext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "v8_seg", "Extention of state segmentation files" }, { "-omoddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition of output models" }, { "-dmoddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition used for observation dump" }, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied-state-to-codebook mapping file" }, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "LSN file name (word transcripts)" }, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary file name"}, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Filler word dictionary file name"}, { "-cbcntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File containing # of times a codebook ID appears in the corpus" }, { "-maxcbobs", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Cluster at most this many observations per codebook" }, { "-maxtotobs", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Cluster at most approximately this many observations over all codebooks" }, { "-featsel", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The feature stream ( 0, 1, ...) to select" }, /* Defines a corpus */ { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The training corpus control file" }, /* Cepstrum file location and extension */ { "-cepext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_EXTENSION, "The cepstrum file extension" }, { "-cepdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The cepstrum data root directory" }, { "-ceplen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_CEP_LENGTH, "The length of the input feature (e.g. MFCC) vectors"}, { "-cepwin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "sliding window of features to concatenate (for -feat 1s_c ONLY)"}, { "-agc", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "max", "The type of automatic gain control to do {max|emax}"}, { "-cmn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "current", "The do cepstral mean normalization based on {current|prior} utterance(s)"}, { "-varnorm", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Normalize utterance by its variance"}, { "-silcomp", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "none", "Do silence compression based on {current|prior} utterance"}, { "-feat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_TYPE, "This argument selects the derived feature computation to use."}, { "-svspec", CMD_LN_STRING, CMD_LN_NO_VALIDATION, NULL, "Split single stream features into subvectors according to this specification."}, { "-ldafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File containing an LDA transformation matrix."}, { "-ldadim", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "29", "# of output dimensions for LDA"}, { "-segdmpdirs", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "segment dmp directories"}, { "-segdmpfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "segment dmp file"}, { "-segidxfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "segment dmp index file"}, { "-fpcachesz", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "3000", "# of file descriptors to cache for observation dmp files" }, { "-obscachesz", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "92", "# of Mbytes cache to use for observations" }, { "-ndensity", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of densities to initialize per tied state per feature" }, { "-ntrial", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "5", "random initialized K-means: # of trials of k-means w/ random initialization from within corpus" }, { "-minratio", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.01", "K-means: minimum convergence ratio, (p_squerr - squerr) / p_squerr"}, { "-maxiter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "100", "K-means: maximum # of iterations of updating to apply"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output file for mixing weights" }, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output file for means" }, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output file for variances" }, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Calculate full covariance matrices" }, { "-method", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "rkm", "Initialization method. Options: rkm | fnkm" }, { "-reest", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate states according to usual definitions assuming vit seg."}, { "-niter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "20", "# of iterations of reestimation to perform per state" }, { "-gthobj", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "state", "Gather what kind of obj {state, phn, frame}" }, { "-stride", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "32", "Gather every -stride'th frame" }, { "-runlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of utts to process from ctl file" }, { "-tsoff", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "Begin tied state reestimation with this tied state" }, { "-tscnt", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Reestimate this many tied states (if available)" }, { "-tsrngfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The range of tied states reestimated expressed as offset,count"}, { "-vartiethr", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", /* i.e. no variance tying based on occurrance count */ "Tie variances if # of observations for state exceed this number" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/11/29 01:43:46 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.4 2004/11/29 01:11:33 egouvea * Fixed license terms in some new files. * * Revision 1.3 2004/11/29 00:49:21 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.2 2004/08/10 21:58:50 arthchan2003 * Incorporate help and example for the four final tools * * Revision 1.1 2004/06/17 19:39:48 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/s3types.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * s3types.h -- Types specific to s3 decoder. * * * HISTORY * * 23-Apr-98 <NAME> (<EMAIL>) at Carnegie Mellon University. * Changed MAX_CIPID from 128 to 127. * * 12-Jul-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBMAIN_S3TYPES_H_ #define _LIBMAIN_S3TYPES_H_ #include <libutil/prim_type.h> /* * Size definitions for more semantially meaningful units. * Illegal value definitions, limits, and tests for specific types. */ /* CI phone id */ typedef int8 s3cipid_t; #define BAD_CIPID ((s3cipid_t) -1) #define NOT_CIPID(p) ((p)<0) #define IS_CIPID(p) ((p)>=0) #define MAX_CIPID 127 /* Phone id (triphone or ciphone) */ typedef int32 s3pid_t; #define BAD_PID ((s3pid_t) -1) #define NOT_PID(p) ((p)<0) #define IS_PID(p) ((p)>=0) #define MAX_PID ((int32)0x7fffffff) /* Transition matrix id; perhaps as many as pids */ typedef int32 s3tmatid_t; #define BAD_TMATID ((s3tmatid_t) -1) #define NOT_TMATID(t) ((t)<0) #define IS_TMATID(t) ((t)>=0) #define MAX_TMATID ((int32)0x7fffffff) /* Dictionary word id */ typedef int32 s3wid_t; #define BAD_WID ((s3wid_t) -1) #define NOT_WID(w) ((w)<0) #define IS_WID(w) ((w)>=0) #define MAX_WID ((int32)0x7fffffff) /* LM word id (uint16 for conserving space) */ typedef uint16 s3lmwid_t; #define BAD_LMWID ((s3lmwid_t) 0xffff) #define NOT_LMWID(w) ((w)==BAD_LMWID) #define IS_LMWID(w) ((w)!=BAD_LMWID) #define MAX_LMWID ((uint32)0xfffe) /* Senone id */ typedef int16 s3senid_t; #define BAD_SENID ((s3senid_t) -1) #define NOT_SENID(s) ((s)<0) #define IS_SENID(s) ((s)>=0) #define MAX_SENID ((int32)0x7fff) /* Mixture-gaussian codebook id */ typedef int16 s3mgauid_t; #define BAD_MGAUID ((s3mgauid_t) -1) #define NOT_MGAUID(m) ((m)<0) #define IS_MGAUID(m) ((m)>=0) #define MAX_MGAUID ((int16)0x7fff) /* Frame id (must be SIGNED integer) */ typedef int16 s3frmid_t; #define BAD_FRMID ((s3frmid_t) -1) #define NOT_FRMID(f) ((f)<0) #define IS_FRMID(f) ((f)>=0) #define MAX_FRMID ((int32)0x7fff) /* Lattice entry id */ typedef int32 s3latid_t; #define BAD_LATID ((s3latid_t) -1) #define NOT_LATID(l) ((l)<0) #define IS_LATID(l) ((l)>=0) #define MAX_LATID ((int32)0x7fffffff) #endif <file_sep>/SphinxTrain/src/programs/cdcn_norm/header.h /* ==================================================================== * Copyright (c) 1989-2005 Car<NAME>ellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef __CDCN_NORM_HEADER_H__ #define __CDCN_NORM_HEADER_H__ #include <s3/common.h> #include <s3/s2io.h> int readdistribution(char *filename, float ***mean, float ***vars, float **prob, int *ncodes, int *Ndim); float **two_D_ize(float *buff, int length, int dim); float norm_utt(float **z, float **x, int num_frames, float **variance, float *prob, float **mean, int num_codes, int Ndim); void resfft(float *x, int n, int m); void rsfft(float *x, int n, int m); float initialize(float **data, int num_frames, float *noise, float *tilt, float speech_threshold, float **mean, float *prob, float **var, int ncodes, int Ndim); float dist(float *x, float *y, float *variance, int Ndim); void correction(float *tilt, float *noise, float **mean, float **corrbook, int num_codes, int Ndim); float max_q(float **variance, float *prob, float *noise, float *tilt, float **mean, float **corrbook, int num_codes, float **z, int num_frames, int Ndim); void mmse_x(float **variance, float *prob, float *tilt, float *noise, float **means, float **corrbook, int num_codes, float **z, float **x, int num_frames, int Ndim); #endif /* __CDCN_NORM_HEADER_H__ */ <file_sep>/SphinxTrain/src/programs/wave2feat/wave2feat.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _WAVE2FEAT_H_ #define _WAVE2FEAT_H_ #define ON 1 #define OFF 0 #define NULL_CHAR '\0' #define MAXCHARS 2048 #define WAV 1 #define RAW 2 #define NIST 3 #define MSWAV 4 #define ONE_CHAN "1" #define LITTLE 1 #define BIG 2 #define FE_SUCCESS 0 #define FE_OUTPUT_FILE_SUCCESS 0 #define FE_CONTROL_FILE_ERROR 1 #define FE_START_ERROR 2 #define FE_UNKNOWN_SINGLE_OR_BATCH 3 #define FE_INPUT_FILE_OPEN_ERROR 4 #define FE_INPUT_FILE_READ_ERROR 5 #define FE_MEM_ALLOC_ERROR 6 #define FE_OUTPUT_FILE_WRITE_ERROR 7 #define FE_OUTPUT_FILE_OPEN_ERROR 8 #define COUNT_PARTIAL 1 #define COUNT_WHOLE 0 #define HEADER_BYTES 1024 /* #if defined(ALPHA) || defined(ALPHA_OSF1) || defined(alpha_osf1) || defined(__alpha) || defined(mips) */ /*#define SWAPBYTES*/ #define SWAPW(x) *(x) = ((0xff & (*(x))>>8) | (0xff00 & (*(x))<<8)) #define SWAPL(x) *(x) = ((0xff & (*(x))>>24) | (0xff00 & (*(x))>>8) |\ (0xff0000 & (*(x))<<8) | (0xff000000 & (*(x))<<24)) #define SWAPF(x) SWAPL((int *) x) param_t *fe_parse_options(int argc, char **argv); void fe_init_params(param_t *P); int32 fe_convert_files(param_t *P); int32 fe_build_filenames(param_t *P, char *fileroot, char **infilename, char **outfilename); char *fe_copystr(char *dest_str, char *src_str); int32 fe_count_frames(fe_t *FE, int32 nsamps, int32 count_partial_frames); int32 fe_readspch(param_t *P, char *infile, int16 **spdata, int32 *splen); int32 fe_writefeat(fe_t *FE, char *outfile, int32 nframes, float32 **feat); int32 fe_free_param(param_t *P); int32 fe_openfiles(param_t *P, fe_t *FE, char *infile, int32 *fp_in, int32 *nsamps, int32 *nframes, int32 *nblocks, char *outfile, int32 *fp_out); int32 fe_readblock_spch(param_t *P, int32 fp, int32 nsamps, int16 *buf); int32 fe_writeblock_feat(param_t *P, fe_t *FE, int32 fp, int32 nframes, float32 **feat); int32 fe_closefiles(int32 fp_in, int32 fp_out); #endif <file_sep>/archive_s3/s3.0/src/libmain/mdef.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * mdef.c -- HMM model definition: base (CI) phones and triphones * * * HISTORY * * 13-Jul-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added mdef_phone_str(). * * 01-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Allowed mdef_phone_id_nearest to return base phone id if either * left or right context (or both) is undefined. * * 01-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created. */ /* * Major assumptions: * All phones have same #states, same topology. * Every phone has exactly one non-emitting, final state--the last one. * CI phones must appear first in model definition file. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "mdef.h" #define MODEL_DEF_VERSION "0.3" #if _MDEF_TEST_ static void mdef_dump (mdef_t *m) { int32 i, j; char buf[1024]; printf ("%d ciphone\n", m->n_ciphone); printf ("%d phone\n", m->n_phone); printf ("%d emitstate\n", m->n_emit_state); printf ("%d cisen\n", m->n_ci_sen); printf ("%d sen\n", m->n_sen); printf ("%d tmat\n", m->n_tmat); for (i = 0; i < m->n_phone; i++) { printf ("%5d", m->phone[i].tmat); for (j = 0; j < m->n_emit_state; j++) printf (" %5d %3d", m->phone[i].state[j], m->cd2cisen[m->phone[i].state[j]]); mdef_phone_str (m, i, buf); printf ("\t%s\n", buf); } } #endif int32 mdef_hmm_cmp (mdef_t *m, s3pid_t p1, s3pid_t p2) { int32 i; if (m->phone[p1].tmat != m->phone[p2].tmat) return -1; for (i = 0; i < m->n_emit_state; i++) if (m->phone[p1].state[i] != m->phone[p2].state[i]) return -1; return 0; } static void ciphone_add (mdef_t *m, char *ci, s3pid_t p) { assert (p < m->n_ciphone); m->ciphone[p].name = (char *) ckd_salloc (ci); if (hash_enter (m->ciphone_ht, m->ciphone[p].name, p) != p) E_FATAL("hash_enter(%s) failed; duplicate CIphone?\n", m->ciphone[p].name); } static ph_lc_t *find_ph_lc (ph_lc_t *lclist, s3cipid_t lc) { ph_lc_t *lcptr; for (lcptr = lclist; lcptr && (lcptr->lc != lc); lcptr = lcptr->next); return lcptr; } static ph_rc_t *find_ph_rc (ph_rc_t *rclist, s3cipid_t rc) { ph_rc_t *rcptr; for (rcptr = rclist; rcptr && (rcptr->rc != rc); rcptr = rcptr->next); return rcptr; } static void triphone_add (mdef_t *m, s3cipid_t ci, s3cipid_t lc, s3cipid_t rc, word_posn_t wpos, s3pid_t p) { ph_lc_t *lcptr; ph_rc_t *rcptr; assert (p < m->n_phone); /* Fill in phone[p] information (state and tmat mappings added later) */ m->phone[p].ci = ci; m->phone[p].lc = lc; m->phone[p].rc = rc; m->phone[p].wpos = wpos; /* Create <ci,lc,rc,wpos> -> p mapping if not a CI phone */ if (p >= m->n_ciphone) { if ((lcptr = find_ph_lc (m->wpos_ci_lclist[wpos][ci], lc)) == NULL) { lcptr = (ph_lc_t *) ckd_calloc (1, sizeof(ph_lc_t)); lcptr->lc = lc; lcptr->next = m->wpos_ci_lclist[wpos][ci]; m->wpos_ci_lclist[wpos][ci] = lcptr; } if ((rcptr = find_ph_rc (lcptr->rclist, rc)) != NULL) { char buf[4096]; mdef_phone_str (m, rcptr->pid, buf); E_FATAL("Duplicate triphone: %s\n", buf); } rcptr = (ph_rc_t *) ckd_calloc (1, sizeof(ph_rc_t)); rcptr->rc = rc; rcptr->pid = p; rcptr->next = lcptr->rclist; lcptr->rclist = rcptr; } } s3cipid_t mdef_ciphone_id (mdef_t *m, char *ci) { int32 id; assert (m); assert (ci); if (hash_lookup (m->ciphone_ht, ci, &id) < 0) return (BAD_CIPID); return ((s3cipid_t) id); } const char *mdef_ciphone_str (mdef_t *m, s3cipid_t id) { assert (m); assert ((id >= 0) && (id < m->n_ciphone)); return (m->ciphone[id].name); } int32 mdef_phone_str (mdef_t *m, s3pid_t pid, char *buf) { char *wpos_name; assert (m); assert ((pid >= 0) && (pid < m->n_phone)); wpos_name = WPOS_NAME; buf[0] = '\0'; if (pid < m->n_ciphone) sprintf (buf, "%s", mdef_ciphone_str (m, (s3cipid_t) pid)); else { sprintf (buf, "(%s,%s,%s,%c)", mdef_ciphone_str(m, m->phone[pid].ci), mdef_ciphone_str(m, m->phone[pid].lc), mdef_ciphone_str(m, m->phone[pid].rc), wpos_name[m->phone[pid].wpos]); } return 0; } s3pid_t mdef_phone_id (mdef_t *m, s3cipid_t ci, s3cipid_t lc, s3cipid_t rc, word_posn_t wpos) { ph_lc_t *lcptr; ph_rc_t *rcptr; assert (m); assert ((ci >= 0) && (ci < m->n_ciphone)); assert ((lc >= 0) && (lc < m->n_ciphone)); assert ((rc >= 0) && (rc < m->n_ciphone)); assert ((wpos >= 0) && (wpos < N_WORD_POSN)); if (((lcptr = find_ph_lc (m->wpos_ci_lclist[wpos][ci], lc)) == NULL) || ((rcptr = find_ph_rc (lcptr->rclist, rc)) == NULL)) return (BAD_PID); return (rcptr->pid); } s3pid_t mdef_phone_id_nearest (mdef_t *m, s3cipid_t b, s3cipid_t l, s3cipid_t r, word_posn_t pos) { word_posn_t tmppos; s3pid_t p; s3cipid_t newl, newr; char *wpos_name; assert (m); assert ((b >= 0) && (b < m->n_ciphone)); assert ((pos >= 0) && (pos < N_WORD_POSN)); if ((NOT_CIPID(l)) || (NOT_CIPID(r))) return ((s3pid_t) b); assert ((l >= 0) && (l < m->n_ciphone)); assert ((r >= 0) && (r < m->n_ciphone)); p = mdef_phone_id (m, b, l, r, pos); if (IS_PID(p)) return p; /* Exact triphone not found; backoff to other word positions */ for (tmppos = 0; tmppos < N_WORD_POSN; tmppos++) { if (tmppos != pos) { p = mdef_phone_id (m, b, l, r, tmppos); if (IS_PID(p)) return p; } } /* Nothing yet; backoff to silence phone if non-silence filler context */ if (IS_CIPID(m->sil)) { newl = m->ciphone[l].filler ? m->sil : l; newr = m->ciphone[r].filler ? m->sil : r; if ((newl != l) || (newr != r)) { p = mdef_phone_id (m, b, newl, newr, pos); if (IS_PID(p)) return p; for (tmppos = 0; tmppos < N_WORD_POSN; tmppos++) { if (tmppos != pos) { p = mdef_phone_id (m, b, newl, newr, tmppos); if (IS_PID(p)) return p; } } } } /* Nothing yet; backoff to base phone */ if ((m->n_phone > m->n_ciphone) && (! m->ciphone[b].filler)) { wpos_name = WPOS_NAME; E_WARN("Triphone(%s,%s,%s,%c) not found; backing off to CIphone\n", mdef_ciphone_str(m, b), mdef_ciphone_str(m, l), mdef_ciphone_str(m, r), wpos_name[pos]); } return ((s3pid_t) b); } int32 mdef_phone_components (mdef_t *m, s3pid_t p, s3cipid_t *b, s3cipid_t *l, s3cipid_t *r, word_posn_t *pos) { assert (m); assert ((p >= 0) && (p < m->n_phone)); *b = m->phone[p].ci; *l = m->phone[p].lc; *r = m->phone[p].rc; *pos = m->phone[p].wpos; return 0; } int32 mdef_is_ciphone (mdef_t *m, s3pid_t p) { assert (m); assert ((p >= 0) && (p < m->n_phone)); return ((p < m->n_ciphone) ? 1 : 0); } /* Parse tmat and state->senone mappings for phone p and fill in structure */ static void parse_tmat_senmap (mdef_t *m, char *line, int32 off, s3pid_t p) { int32 wlen, n, s; char word[1024], *lp; lp = line + off; /* Read transition matrix id */ if ((sscanf (lp, "%d%n", &n, &wlen) != 1) || (n < 0)) E_FATAL("Missing or bad transition matrix id: %s\n", line); m->phone[p].tmat = n; if (m->n_tmat <= n) E_FATAL("tmat-id(%d) > #tmat in header(%d): %s\n", n, m->n_tmat, line); lp += wlen; /* Read senone mappings for each emitting state */ for (n = 0; n < m->n_emit_state; n++) { if ((sscanf (lp, "%d%n", &s, &wlen) != 1) || (s < 0)) E_FATAL("Missing or bad state[%d]->senone mapping: %s\n", n, line); if ((p < m->n_ciphone) && (m->n_ci_sen <= s)) E_FATAL("CI-senone-id(%d) > #CI-senones(%d): %s\n", s, m->n_ci_sen, line); if (m->n_sen <= s) E_FATAL("Senone-id(%d) > #senones(%d): %s\n", s, m->n_sen, line); m->phone[p].state[n] = s; lp += wlen; } /* Check for the last non-emitting state N */ if ((sscanf (lp, "%s%n", word, &wlen) != 1) || (strcmp (word, "N") != 0)) E_FATAL("Missing non-emitting state spec: %s\n", line); lp += wlen; /* Check for end of line */ if (sscanf (lp, "%s%n", word, &wlen) == 1) E_FATAL("Non-empty beyond non-emitting final state: %s\n", line); } static void parse_base_line (mdef_t *m, char *line, s3pid_t p) { int32 wlen, n; char word[1024], *lp; s3cipid_t ci; lp = line; /* Read base phone name */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing base phone name: %s\n", line); lp += wlen; /* Make sure it's not a duplicate */ ci = mdef_ciphone_id (m, word); if (IS_CIPID(ci)) E_FATAL("Duplicate base phone: %s\n", line); /* Add ciphone to ciphone table with id p */ ciphone_add (m, word, p); ci = (s3cipid_t) p; /* Read and skip "-" for lc, rc, wpos */ for (n = 0; n < 3; n++) { if ((sscanf (lp, "%s%n", word, &wlen) != 1) || (strcmp (word, "-") != 0)) E_FATAL("Bad context info for base phone: %s\n", line); lp += wlen; } /* Read filler attribute, if present */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing filler atribute field: %s\n", line); lp += wlen; if (strcmp (word, "filler") == 0) m->ciphone[ci].filler = 1; else if (strcmp (word, "n/a") == 0) m->ciphone[ci].filler = 0; else E_FATAL("Bad filler attribute field: %s\n", line); triphone_add (m, ci, BAD_CIPID, BAD_CIPID, WORD_POSN_UNDEFINED, p); /* Parse remainder of line: transition matrix and state->senone mappings */ parse_tmat_senmap (m, line, lp-line, p); } static void parse_tri_line (mdef_t *m, char *line, s3pid_t p) { int32 wlen; char word[1024], *lp; s3cipid_t ci, lc, rc; word_posn_t wpos; lp = line; /* Read base phone name */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing base phone name: %s\n", line); lp += wlen; ci = mdef_ciphone_id (m, word); if (NOT_CIPID(ci)) E_FATAL("Unknown base phone: %s\n", line); /* Read lc */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing left context: %s\n", line); lp += wlen; lc = mdef_ciphone_id (m, word); if (NOT_CIPID(lc)) E_FATAL("Unknown left context: %s\n", line); /* Read rc */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing right context: %s\n", line); lp += wlen; rc = mdef_ciphone_id (m, word); if (NOT_CIPID(rc)) E_FATAL("Unknown right context: %s\n", line); /* Read tripone word-position within word */ if ((sscanf (lp, "%s%n", word, &wlen) != 1) || (word[1] != '\0')) E_FATAL("Missing or bad word-position spec: %s\n", line); lp += wlen; switch (word[0]) { case 'b': wpos = WORD_POSN_BEGIN; break; case 'e': wpos = WORD_POSN_END; break; case 's': wpos = WORD_POSN_SINGLE; break; case 'i': wpos = WORD_POSN_INTERNAL; break; default: E_FATAL("Bad word-position spec: %s\n", line); } /* Read filler attribute, if present. Must match base phone attribute */ if (sscanf (lp, "%s%n", word, &wlen) != 1) E_FATAL("Missing filler attribute field: %s\n", line); lp += wlen; if (((strcmp (word, "filler") == 0) && (m->ciphone[ci].filler)) || ((strcmp (word, "n/a") == 0) && (! m->ciphone[ci].filler))) { /* Everything is fine */ } else E_FATAL("Bad filler attribute field: %s\n", line); triphone_add (m, ci, lc, rc, wpos, p); /* Parse remainder of line: transition matrix and state->senone mappings */ parse_tmat_senmap (m, line, lp-line, p); } static int32 noncomment_line(char *line, int32 size, FILE *fp) { while (fgets (line, size, fp) != NULL) { if (line[0] != '#') return 0; } return -1; } /* * Initialize phones (ci and triphones) and state->senone mappings from .mdef file. */ mdef_t *mdef_init (char *mdeffile) { FILE *fp; int32 n_ci, n_tri, n_map, n; char tag[1024], buf[1024]; s3senid_t *senmap; s3pid_t p; int32 s, ci, cd; mdef_t *m; int32 *cdsen_start, *cdsen_end; if (! mdeffile) E_FATAL("No mdef-file\n"); E_INFO("Reading model definition: %s\n", mdeffile); m = (mdef_t *) ckd_calloc (1, sizeof(mdef_t)); if ((fp = fopen(mdeffile, "r")) == NULL) E_FATAL_SYSTEM("fopen(%s,r) failed\n", mdeffile); if (noncomment_line(buf, sizeof(buf), fp) < 0) E_FATAL("Empty file: %s\n", mdeffile); if (strncmp(buf, MODEL_DEF_VERSION, strlen(MODEL_DEF_VERSION)) != 0) E_FATAL("Version error: Expecing %s, but read %s\n", MODEL_DEF_VERSION, buf); /* Read #base phones, #triphones, #senone mappings defined in header */ n_ci = -1; n_tri = -1; n_map = -1; m->n_ci_sen = -1; m->n_sen = -1; m->n_tmat = -1; do { if (noncomment_line(buf, sizeof(buf), fp) < 0) E_FATAL("Incomplete header\n"); if ((sscanf(buf, "%d %s", &n, tag) != 2) || (n < 0)) E_FATAL("Error in header: %s\n", buf); if (strcmp(tag, "n_base") == 0) n_ci = n; else if (strcmp(tag, "n_tri") == 0) n_tri = n; else if (strcmp(tag, "n_state_map") == 0) n_map = n; else if (strcmp(tag, "n_tied_ci_state") == 0) m->n_ci_sen = n; else if (strcmp(tag, "n_tied_state") == 0) m->n_sen = n; else if (strcmp(tag, "n_tied_tmat") == 0) m->n_tmat = n; else E_FATAL("Unknown header line: %s\n", buf); } while ((n_ci < 0) || (n_tri < 0) || (n_map < 0) || (m->n_ci_sen < 0) || (m->n_sen < 0) || (m->n_tmat < 0)); if ((n_ci == 0) || (m->n_ci_sen == 0) || (m->n_tmat == 0) || (m->n_ci_sen > m->n_sen)) E_FATAL("%s: Error in header\n", mdeffile); /* Check typesize limits */ if (n_ci >= MAX_CIPID) E_FATAL("%s: #CI phones (%d) exceeds limit (%d)\n", mdeffile, n_ci, MAX_CIPID); if (n_ci + n_tri >= MAX_PID) E_FATAL("%s: #Phones (%d) exceeds limit (%d)\n", mdeffile, n_ci+n_tri, MAX_PID); if (m->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", mdeffile, m->n_sen, MAX_SENID); if (m->n_tmat >= MAX_TMATID) E_FATAL("%s: #tmats (%d) exceeds limit (%d)\n", mdeffile, m->n_tmat, MAX_TMATID); m->n_emit_state = (n_map / (n_ci+n_tri)) - 1; if ((m->n_emit_state+1) * (n_ci+n_tri) != n_map) E_FATAL("Header error: n_state_map not a multiple of n_ci*n_tri\n"); /* Initialize ciphone info */ m->n_ciphone = n_ci; m->ciphone_ht = hash_new (n_ci, 1); /* With case-insensitive string names */ m->ciphone = (ciphone_t *) ckd_calloc (n_ci, sizeof(ciphone_t)); /* Initialize phones info (ciphones + triphones) */ m->n_phone = n_ci + n_tri; m->phone = (phone_t *) ckd_calloc (m->n_phone, sizeof(phone_t)); /* Allocate space for state->senone map for each phone */ senmap = (s3senid_t *) ckd_calloc (m->n_phone * m->n_emit_state, sizeof(s3senid_t)); for (p = 0; p < m->n_phone; p++) m->phone[p].state = senmap + (p * m->n_emit_state); /* Allocate initial space for <ci,lc,rc,wpos> -> pid mapping */ m->wpos_ci_lclist = (ph_lc_t ***) ckd_calloc_2d (N_WORD_POSN, m->n_ciphone, sizeof(ph_lc_t *)); /* * Read base phones and triphones. They'll simply be assigned a running sequence * number as their "phone-id". If the phone-id < n_ci, it's a ciphone. */ /* Read base phones */ for (p = 0; p < n_ci; p++) { if (noncomment_line(buf, sizeof(buf), fp) < 0) E_FATAL("Premature EOF reading CIphone %d\n", p); parse_base_line (m, buf, p); } m->sil = mdef_ciphone_id (m, SILENCE_CIPHONE); /* Read triphones, if any */ for (; p < m->n_phone; p++) { if (noncomment_line(buf, sizeof(buf), fp) < 0) E_FATAL("Premature EOF reading phone %d\n", p); parse_tri_line (m, buf, p); } if (noncomment_line(buf, sizeof(buf), fp) >= 0) E_ERROR("Non-empty file beyond expected #phones (%d)\n", m->n_phone); /* Build CD senones to CI senones map */ if (m->n_ciphone * m->n_emit_state != m->n_ci_sen) E_FATAL("#CI-senones(%d) != #CI-phone(%d) x #emitting-states(%d)\n", m->n_ci_sen, m->n_ciphone, m->n_emit_state); m->cd2cisen = (s3senid_t *) ckd_calloc (m->n_sen, sizeof(s3senid_t)); m->sen2ciphone = (s3cipid_t *) ckd_calloc (m->n_sen, sizeof(s3cipid_t)); for (s = 0; s < m->n_sen; s++) m->sen2ciphone[s] = BAD_CIPID; for (s = 0; s < m->n_ci_sen; s++) { /* CI senones */ m->cd2cisen[s] = (s3senid_t) s; m->sen2ciphone[s] = s / m->n_emit_state; } for (p = n_ci; p < m->n_phone; p++) { /* CD senones */ for (s = 0; s < m->n_emit_state; s++) { cd = m->phone[p].state[s]; ci = m->phone[m->phone[p].ci].state[s]; m->cd2cisen[cd] = (s3senid_t) ci; m->sen2ciphone[cd] = m->phone[p].ci; } } /* * Count #senones (CI+CD) for each CI phone. * HACK!! For handling holes in senone-CIphone mappings. Does not work if holes * are present at the beginning or end of senones for a given CIphone. */ cdsen_start = (int32 *) ckd_calloc (m->n_ciphone, sizeof(int32)); cdsen_end = (int32 *) ckd_calloc (m->n_ciphone, sizeof(int32)); for (s = m->n_ci_sen; s < m->n_sen; s++) { if (NOT_CIPID(m->sen2ciphone[s])) continue; if (! cdsen_start[m->sen2ciphone[s]]) cdsen_start[m->sen2ciphone[s]] = s; cdsen_end[m->sen2ciphone[s]] = s; } /* Fill up holes */ for (s = m->n_ci_sen; s < m->n_sen; s++) { if (IS_CIPID(m->sen2ciphone[s])) continue; /* Check if properly inside the observed ranges above */ for (p = 0; p < m->n_ciphone; p++) { if ((s > cdsen_start[p]) && (s < cdsen_end[p])) break; } if (p >= m->n_ciphone) E_FATAL("Unreferenced senone %d; cannot determine parent CIphone\n", s); m->sen2ciphone[s] = p; } /* Build #CD-senones for each CIphone */ m->ciphone2n_cd_sen = (int32 *) ckd_calloc (m->n_ciphone, sizeof(int32)); n = 0; for (p = 0; p < m->n_ciphone; p++) { if (cdsen_start[p] > 0) { m->ciphone2n_cd_sen[p] = cdsen_end[p] - cdsen_start[p] + 1; n += m->ciphone2n_cd_sen[p]; } } n += m->n_ci_sen; assert (n == m->n_sen); ckd_free (cdsen_start); ckd_free (cdsen_end); E_INFO("%d CI-phones, %d CD-phones, %d emitting states/phone, %d sen, %d CI-sen\n", m->n_ciphone, m->n_phone - m->n_ciphone, m->n_emit_state, m->n_sen, m->n_ci_sen); fclose (fp); return m; } #if (_MDEF_TEST_) main (int32 argc, char *argv[]) { mdef_t *m; if (argc < 2) E_FATAL("Usage: %s mdeffile\n", argv[0]); m = mdef_init (argv[1]); mdef_dump (m); exit(0); } #endif <file_sep>/archive_s3/s3.3/src/tests/Makefile # ==================================================================== # Copyright (c) 2000 <NAME> University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Sphinx III # # ==================================================================== TOP=../.. DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) H = cmd_ln_args.h fe_dump.h feat_dump.h new_fe_sp_dump.h live_dump.h metrics.h LIVEDECSRCS = parse_args_file.c fe_dump.c feat_dump.c new_fe_sp_dump.c live_dump.c metrics.c MAINSRCS = dump_frontend.c batch_metrics.c lm_test.c lm_utt_test.c # OTHERSRCS = main.c LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile $(SRCS) $(H) LIBNAME= tests LOCAL_INCLUDES = -I$(TOP)/src -I$(TOP)/src/libs3decoder -I$(TOP)/src/libs3audio ALL = $(BINDIR)/dumpfrontend $(BINDIR)/batchmetrics $(BINDIR)/lm_test $(BINDIR)/lm_utt_test include $(TOP)/config/common_make_rules $(BINDIR)/dumpfrontend: dump_frontend.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ dump_frontend.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) -Wl,-R$(LIBDIR) $(BINDIR)/batchmetrics: batch_metrics.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ batch_metrics.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) -Wl,-R$(LIBDIR) $(BINDIR)/lm_test: lm_test.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ lm_test.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) -Wl,-R$(LIBDIR) $(BINDIR)/lm_utt_test: lm_utt_test.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ lm_utt_test.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) -Wl,-R$(LIBDIR) ti46: rm -f gmake-ti46.results $(BINDIR)/batchmetrics ./ti46.ctl /lab/speech/sphinx4/data/ti46/ti20/test/test/raw16k ARGS > gmake-ti46.results ti46-quick: rm -f gmake-ti46-quick.results $(BINDIR)/batchmetrics ./ti46-quick.ctl /lab/speech/sphinx4/data/ti46/ti20/test/test/raw16k ARGS > gmake-ti46-quick.results tidigits: rm -f gmake-tidigits.results $(BINDIR)/batchmetrics ./tidigits.ctl /lab/speech/sphinx4/data/tidigits/test/raw16k ARGS > gmake-tidigits.results tidigits-quick: rm -f gmake-tidigits-quick.results $(BINDIR)/batchmetrics ./tidigits-quick.ctl /lab/speech/sphinx4/data/tidigits/test/raw16k ARGS > gmake-tidigits-quick.results # A simple test of 5000 randomly selected ngrams from the HUB-4 language model lm-test: $(BINDIR)/lm_test ./lm_test.ARGS /lab/speech/sphinx4/data/hub4_model/language_model.arpaformat.DMP /lab/speech/sphinx4/data/hub4_model/random_ngrams.txt # A test of 5000 trigrams, randomly generated from the HUB-4 language model # vocabulary lm-backoff-test: $(BINDIR)/lm_test ./lm_test.ARGS /lab/speech/sphinx4/data/hub4_model/language_model.arpaformat.DMP /lab/speech/sphinx4/data/hub4_model/random_trigrams.txt # A test of a long list of ngrams. This list is generated by logging # the ngrams queried during a run of the hub4_trigram test. lm-utt-test: $(BINDIR)/lm_utt_test ./lm_test.ARGS /lab/speech/sphinx4/data/hub4_model/language_model.arpaformat.DMP /lab/speech/sphinx4/data/hub4_model/ngram.queried <file_sep>/tools/riddler/properties/riddlerdev.properties admin.user=admin admin.password.file=/home/riddlerdev/passwd admin.host=localhost admin.port=4848 http.host=localhost http.port=8080 appserver.instance.name=server module=riddler-ejb appname=${module} build.base.dir=/home/riddlerdev/build build.classes.dir=${build.base.dir}/classes build.generated.dir=${build.base.dir}/generated assemble.dir=${build.base.dir}/archive <file_sep>/archive_s3/s3.0/pgm/treedec/kb.h /* * kb.h -- Collection of databases/data-structures needed for Viterbi search. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 26-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _KB_H_ #define _KB_H_ #include <libmain/kbcore.h> #include <libmain/am.h> typedef struct { mdef_t *mdef; /* Model definition; phones/triphones -> senone/tmat maps */ dict_t *dict; /* Pronunciation lexicon */ lm_t *lm; /* Backoff word-trigram LM */ fillpen_t *fillpen; /* Filler word probabilities */ s3lmwid_t *dict2lmwid; /* dict2lmwid[wid] = LM word-id mapping corresponding to dictionary word-id wid; could be BAD_LMWID if word not in LM or is a filler */ acoustic_t *am; /* Acoustic models; gaussian density codebooks/senones */ tmat_t *tmat; /* HMM transition matrices */ glist_t lextree_root; /* List of lextree root node ptrs */ glist_t lextree_active; /* List of lextree node ptrs active in current frame */ glist_t *vithist; /* vithist[f] = list of Viterbi history node ptrs created @fr f. NOTE: vithist[-1] must be valid for an initial <s> entry!! */ int32 beam; /* Main pruning threshold for beam search */ int32 wordbeam; /* Auxiliary pruning threshold for determining word exits; much narrower than beam. */ int32 wordmax; /* wordbeam might be too permissive at times (e.g., around noisy speech); this provides a hard absolute limit if needed */ int32 *wd_last_sf; /* wd_last_sf[w] = The last start frame for word-ID w. Used to determine if a word is persistent enough. */ /* Profiling stuff */ ptmr_t *tm; ptmr_t *tm_search; int32 n_hmm_eval; int32 n_sen_eval; } kb_t; #endif <file_sep>/sphinx2/src/libsphinx2/Makefile.am ARCH = `uname -m | sed s/i.86/i386/`_`uname -s | tr A-Z a-z` SUBDIRS = include lib_LTLIBRARIES = libsphinx2.la libsphinx2_la_LDFLAGS = -version-info 0:6:0 libsphinx2_la_SOURCES = \ CM_funcs.c \ add-table.c \ agc_emax.c \ allphone.c \ areadchar.c \ areaddouble.c \ areadfloat.c \ areadint.c \ areadshort.c \ awritechar.c \ awritedouble.c \ awritefloat.c \ awriteint.c \ awriteshort.c \ bio.c \ bisearch.c \ bitvec.c \ blk_cdcn_norm.c \ blkarray_list.c \ cache_lm.c \ case.c \ cdcn_init.c \ cdcn_norm.c \ cdcn_update.c \ cdcn_utils.c \ cep_rw.c \ ckd_alloc.c \ cont_mgau.c \ dict.c \ eht_quit.c \ err.c \ f2read.c \ f2write.c \ fbs_main.c \ fsg_psubtree.c \ fsg_lextree.c \ fsg_history.c \ fsg_search.c \ get_a_word.c \ glist.c \ hash.c \ hmm_tied_r.c \ kb_main.c \ lab.c \ linklist.c \ list.c \ live_norm.c \ lm.c \ lm_3g.c \ lmclass.c \ logmsg.c \ logs3.c \ longio.c \ mdef.c \ nxtarg.c \ norm.c \ pconf.c \ peek_length.c \ phone.c \ prime.c \ r_agc_noise.c \ resfft.c \ s3hash.c \ s3mdef_s2map.c \ salloc.c \ sc_cbook_r.c \ sc_vq.c \ search.c \ searchlat.c \ senscr.c \ skipto.c \ str2words.c \ strcasecmp.c \ time_align.c \ unlimit.c \ util.c \ uttproc.c \ vector.c \ word_fsg.c # libsphinx2_la_LIBADD = -lc -lm $(top_srcdir)/src/libsphinx2fe/libsphinx2fe.la # <EMAIL> - Added for Solaris build # LDADD = -L/usr/demo/SOUND/lib/ -laudio INCLUDES = -I$(top_srcdir)/src/libsphinx2/include \ -I$(top_srcdir)/include \ -I$(top_builddir)/include # add for solaris # -I/usr/demo/SOUND/include AM_CPPFLAGS = -DFAST8B=1 <file_sep>/CLP/include/Link.h //------------------------------------- // Link.h stores a lattice link //------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //-------------------------------------------------------------------------------------------------------- #ifndef _Link_h #define _Link_h #include "Prob.h" #include "Prons.h" #include "common_lattice.h" #include "Node.h" #include <string> class Link { friend class Lattice; public: Link(); Link(const string&, const Lattice*, const Prons&); const Node& start_node() const; const Node& end_node() const; float start_time() const; float end_time() const; const NodeId Start_node_id() const {return start_node_id;} const NodeId End_node_id() const {return end_node_id;} LinkId Id() const {return id;} void setId(unsigned i) {id = i;} LnProb ACscore() const{ return ac_score;} LnProb LMscore() const{ return lm_score;} LnProb PRscore() const{ return pr_score;} unsigned Word_idx() const {return word_idx;} bool is_pruned() const {return pruned;} const LnProb Pscore() const { return pscore;} const LnProb Score() const { return score;} friend ostream& operator<<(ostream& os, const Link& link); void print_it(const Prons& ); private: const Lattice* lat_ptr; LinkId id; NodeId start_node_id; NodeId end_node_id; int word_idx; /* the index of the word associated with this link */ LnProb ac_score; /* acoustic model log prob */ LnProb lm_score; /* language model log prob */ LnProb pr_score; /* pronunciation model log prob */ LnProb pscore; /* link posterior probability */ LnProb score; /* the weighted combination of the LM, AC, PR and wdpenalty */ bool pruned; /* a flag for the status of the link (1=pruned, 0=kept) */ void fill_link_fields(const string& id, const string& entry); }; // ///////////////////////////////////////////////////////////////////////////////////// // sort links in lexicographical order of their start/end nodes struct compL : binary_function<Link, Link, bool> { bool operator () (const Link& l1, const Link& l2) { unsigned start1 = l1.Start_node_id(); unsigned start2 = l2.Start_node_id(); unsigned end1 = l1.End_node_id(); unsigned end2 = l2.End_node_id(); if (end1 < end2) return 1; else if (end1 == end2 && start1 < start2) return 1; return 0; } }; // //////////////////////////////////////////////////////////////////////////////////// // sort links in decreasing order of their scores (log posterior probabilities) struct compLS : binary_function<Link, Link, bool> { bool operator () (const Link& l1, const Link& l2) { return (l1.Pscore() > l2.Pscore()); } }; // //////////////////////////////////////////////////////////////////////////////////// #endif <file_sep>/archive_s3/s3.0/pgm/treedec/lextree.h /* * lextree.h -- Maintaining the lexical tree. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 15-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _LEXTREE_H_ #define _LEXTREE_H_ /* * Lextree structure used for search: actually consists of two parts--tree and flat. * The initial prefix, the tree, has HMM nodes shared among more than one word. It * then develops into a flat structure with no such sharing. The tree depth at which * this transition occurs can be controlled. This allows us to control the point at * which LM scores may be applied. Regardless of this transition point, the final * node (HMM) for a word is always in the flat structure. So single phone words, for * example, are entirely within the flat structure. */ #include <libutil/libutil.h> #include <libmain/hmm.h> #include "kb.h" /* * Each "node" in the lextree contains all the HMM/lexicon related info, as well * as a list (glist) of its children "nodes". The entire lextree is a list (glist) * of such top-level "nodes". */ typedef struct { hmm_t hmm; int32 id; /* If < 0, lextree internal node (i.e., not flat part). Else, includes word-id and pronunciation position within the word for this node; see definitions below. */ glist_t children; /* data.ptr should be (lextree_node_t *); see libutil/glist */ } lextree_node_t; /* * Representing word id (wid) and pronunciation position (ppos) in node id field. * Note: pronunciation position is measured from the END, 0 being the final phone for * the word. */ #define LEXTREE_NODEID(wid,ppos) (((wid) & 0x00ffffff) | ((ppos) << 24)) #define LEXTREE_NODEID2WID(id) ((id) & 0x00ffffff) #define LEXTREE_NODEID2PPOS(id) (((id) >> 24) & 0x000000ff) #define LEXTREE_NODEID_MAXWID ((int32) 0x00ffffff) #define LEXTREE_NODEID_MAXPPOS ((int32) 0x0000007f) #define LEXTREE_NODEID_INVALID(id) ((id) < 0) #define LEXTREE_NODEID_VALID(id) ((id) >= 0) #define LEXTREE_NODEID_NONE (-1) /* * Build a lexical tree for the given lexicon. The nodes in the tree are of type * lextree_node_t. * Return value: a glist of top-level nodes in the lextree; NULL if empty or error. */ glist_t lextree_build(dict_t *dict, /* In: Lexicon for which lextree is to be built */ mdef_t *mdef, /* In: Model definition with phone definitions */ bitvec_t active, /* In: Lexicon word-id w is included in the lextree iff active[w] is TRUE. If active is NULL, the entire lexicon is active. The caller must ensure that any active word is in the LM (or is a filler word). */ int32 flatdepth); /* In: Depth starting from which the generated "tree" is forced to be flat; e.g., if 0, the result is entirely flat. */ /* * Prepare for Viterbi decoding of new utterance. Any clutter from earlier utterances must have * been cleared already. */ void lextree_vit_start (kb_t *kb, /* In/Out: Models and search structures */ char *uttid); /* In: String name for new utt */ /* * Push Viterbi search through one frame. Note that the active list of lextree nodes is a glist * given by kb->lextree_active, and it is updated for the next frame as a side-effect. * Return value: Best HMM state score at the end of the current frame. */ int32 lextree_vit_frame (kb_t *kb, /* In/Out: Models and search structures */ int32 frm, /* In: Current frame */ char *uttid); /* In: String name for new utt */ /* * Finish the utterance. * Return value: Viterbi history node for the final node if successful, NULL if error. * (The utterance hypothesis can be extracted by backtracking via the history nodes.) */ vithist_t *lextree_vit_end (kb_t *kb, /* In/Out: Models and search structures */ int32 frm, /* In: #Frames in utterance */ char *uttid); /* In: String name for new utt */ #endif <file_sep>/SphinxTrain/src/libs/libcommon/get_cpu_time.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <s3/prim_type.h> #include <s3/s3.h> #if defined(__alpha) #include <sys/time.h> #include <sys/resource.h> #endif int get_cpu_time(uint32 *sec, float32 *frac_sec) { #if defined(__alpha) int ret; struct rusage r_usage; uint32 out_sec; uint32 t_usec; uint32 out_usec; ret = getrusage(RUSAGE_SELF, &r_usage); if (ret < 0) return S3_ERROR; out_sec = 0; out_sec += r_usage.ru_utime.tv_sec; out_sec += r_usage.ru_stime.tv_sec; t_usec = r_usage.ru_utime.tv_usec+r_usage.ru_stime.tv_usec; out_sec += t_usec / 1000000; out_usec = t_usec % 1000000; *sec = out_sec; *frac_sec = (float32)out_usec / (float32)1000000; return S3_SUCCESS; #else *sec = 0; *frac_sec = 0; return S3_SUCCESS; #endif } <file_sep>/SphinxTrain/src/libs/libmllr/mllr_io.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <string.h> #include <math.h> #include <s3/s3.h> #include <s3/common.h> #include <s3/mllr.h> #include <s3/mllr_io.h> int32 store_reg_mat (const char *regmatfn, const uint32 *veclen, uint32 n_class, uint32 n_stream, float32 ****A, float32 ***B) { uint32 i,j,k,m; FILE *fp; if ((fp = fopen(regmatfn,"w")) == NULL) { E_INFO("Unable to open %s to store MLLR matrices\n",regmatfn); return S3_ERROR; } fprintf(fp,"%d\n",n_class); fprintf(fp,"%d\n",n_stream); for (m = 0; m < n_class; m++) { for (i = 0; i < n_stream; i++) { fprintf(fp,"%d\n", veclen[i]); for (j = 0; j < veclen[i]; j++) { for (k = 0; k < veclen[i]; ++k) { fprintf(fp,"%f ",A[m][i][j][k]); } fprintf(fp,"\n"); } for (j = 0; j < veclen[i]; j++) { fprintf(fp,"%f ",B[m][i][j]); } fprintf(fp,"\n"); /* Identity transform for variances. */ for (j = 0; j < veclen[i]; j++) { fprintf(fp,"1.0 "); } fprintf(fp,"\n"); } } fclose(fp); return S3_SUCCESS; } int32 read_reg_mat ( const char *regmatfn, const uint32 **veclen, uint32 *n_class, uint32 *n_stream, float32 *****A, float32 ****B ) { uint32 i,j,k,m,nstream,nclass; FILE *fp; uint32 *vlen; float32 ****lA,***lB; if ((fp = fopen(regmatfn,"r")) == NULL) { E_INFO("Unable to open %s to read MLLR matrices\n",regmatfn); return S3_ERROR; } fscanf(fp,"%d",&nclass); fscanf(fp,"%d",&nstream); vlen = (uint32 *)ckd_calloc(nstream,sizeof(uint32)); lA = (float32 ****)ckd_calloc_2d (nclass,nstream,sizeof (float32 **)); lB = (float32 ***)ckd_calloc_2d (nclass,nstream,sizeof (float32 *)); for (m = 0; m < nclass; ++m) { for (i = 0; i < nstream; ++i) { fscanf(fp,"%d", &vlen[i]); lA[m][i] = (float32 **) ckd_calloc_2d(vlen[i],vlen[i],sizeof(float32)); lB[m][i] = (float32 *) ckd_calloc(vlen[i],sizeof(float32)); for (j = 0; j < vlen[i]; j++) { for (k = 0; k < vlen[i]; ++k) { fscanf(fp,"%f ",&lA[m][i][j][k]); } } for (j = 0; j < vlen[i]; j++) { fscanf(fp,"%f ",&lB[m][i][j]); } /* Identity transform for variances. */ for (j = 0; j < vlen[i]; j++) { float32 dummy; fscanf(fp,"%f ",&dummy); } } } *n_class = nclass; *n_stream = nstream; *veclen = vlen; *A = lA; *B = lB; fclose(fp); return S3_SUCCESS; } int32 free_mllr_A(float32 ****A, uint32 n_class, uint32 n_stream) { uint32 i,j; for (i=0; i < n_class; i++) { for (j=0; j < n_stream; j++) { ckd_free_2d((void **)A[i][j]); } } ckd_free_2d((void **)A); return S3_SUCCESS; } int32 free_mllr_B(float32 ***B, uint32 n_class, uint32 n_stream) { uint32 i,j; for (i=0; i < n_class; i++) { for (j=0; j < n_stream; j++) { ckd_free((void *)B[i][j]); } } ckd_free_2d((void **)B); return S3_SUCCESS; } int32 free_mllr_reg(float32 *****regl, float32 ****regr, uint32 n_class, uint32 n_stream) { uint32 i,j; for (i=0; i < n_class; i++) { for (j=0; j < n_stream; j++) { ckd_free_3d((void ***)regl[i][j]); ckd_free_2d((void **)regr[i][j]); } } ckd_free_2d((void **)regl); ckd_free_2d((void **)regr); return S3_SUCCESS; } <file_sep>/pocketsphinx/src/libpocketsphinx/tst_search.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2009 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file tst_search.c Time-conditioned lexicon tree search ("S3") * @author <NAME> and <NAME> */ /* System headers. */ #include <string.h> #include <assert.h> /* SphinxBase headers. */ #include <ckd_alloc.h> #include <listelem_alloc.h> #include <profile.h> #include <err.h> /* Local headers. */ #include "pocketsphinx_internal.h" #include "ps_lattice_internal.h" #include "tst_search.h" static int tst_search_start(ps_search_t *search); static int tst_search_step(ps_search_t *search, int frame_idx); static int tst_search_finish(ps_search_t *search); static int tst_search_reinit(ps_search_t *search); static ps_lattice_t *tst_search_lattice(ps_search_t *search); static char const *tst_search_hyp(ps_search_t *search, int32 *out_score); static int32 tst_search_prob(ps_search_t *search); static ps_seg_t *tst_search_seg_iter(ps_search_t *search, int32 *out_score); static ps_searchfuncs_t tst_funcs = { /* name: */ "tst", /* start: */ tst_search_start, /* step: */ tst_search_step, /* finish: */ tst_search_finish, /* reinit: */ tst_search_reinit, /* free: */ tst_search_free, /* lattice: */ tst_search_lattice, /* hyp: */ tst_search_hyp, /* prob: */ tst_search_prob, /* seg_iter: */ tst_search_seg_iter, }; static histprune_t * histprune_init(int32 maxhmm, int32 maxhist, int32 maxword, int32 hmmhistbinsize, int32 numNodes) { histprune_t *h; int32 n; h = (histprune_t *) ckd_calloc(1, sizeof(histprune_t)); h->maxwpf = maxword; h->maxhmmpf = maxhmm; h->maxhistpf = maxhist; h->hmm_hist_binsize = hmmhistbinsize; n = numNodes; n /= h->hmm_hist_binsize; h->hmm_hist_bins = n + 1; h->hmm_hist = (int32 *) ckd_calloc(h->hmm_hist_bins, sizeof(int32)); return h; } static void histprune_zero_histbin(histprune_t * h) { int32 *hmm_hist; int32 numhistbins; /* Local version of number of histogram bins, don't expect it to change */ int32 i; hmm_hist = h->hmm_hist; numhistbins = h->hmm_hist_bins; for (i = 0; i < numhistbins; i++) hmm_hist[i] = 0; } static void histprune_free(histprune_t * h) { if (h != NULL) { if (h->hmm_hist != NULL) { ckd_free(h->hmm_hist); } free(h); } } static void histprune_showhistbin(histprune_t * hp, int32 nfr, char *uttid) { int32 i, j, k; if (nfr == 0) { nfr = 1; E_WARN("Set number of frame to 1\n"); } for (j = hp->hmm_hist_bins - 1; (j >= 0) && (hp->hmm_hist[j] == 0); --j); E_INFO("HMMHist[0..%d](%s):", j, uttid); for (i = 0, k = 0; i <= j; i++) { k += hp->hmm_hist[i]; E_INFOCONT(" %d(%d)", hp->hmm_hist[i], (k * 100) / nfr); } E_INFOCONT("\n"); } static void histprune_report(histprune_t * h) { E_INFO_NOFN("Initialization of histprune_t, report:\n"); E_INFO_NOFN("Parameters used in histogram pruning:\n"); E_INFO_NOFN("Max. HMM per frame=%d\n", h->maxhmmpf); E_INFO_NOFN("Max. history per frame=%d\n", h->maxhistpf); E_INFO_NOFN("Max. word per frame=%d\n", h->maxwpf); E_INFO_NOFN("Size of histogram bin=%d\n", h->hmm_hist_binsize); E_INFO_NOFN("No. of histogram bin=%d\n", h->hmm_hist_bins); E_INFO_NOFN("\n"); } static beam_t * beam_init(float64 hmm, float64 ptr, float64 wd, float64 wdend, int32 ptranskip, int32 n_ciphone, logmath_t *logmath) { beam_t *beam; beam = (beam_t *) ckd_calloc(1, sizeof(beam_t)); beam->hmm = logmath_log(logmath, hmm); beam->ptrans = logmath_log(logmath, ptr); beam->word = logmath_log(logmath, wd); beam->wordend = logmath_log(logmath, wdend); beam->ptranskip = ptranskip; beam->bestscore = MAX_NEG_INT32; beam->bestwordscore = MAX_NEG_INT32; beam->n_ciphone = n_ciphone; beam->wordbestscores = (int32 *) ckd_calloc(n_ciphone, sizeof(int32)); beam->wordbestexits = (int32 *) ckd_calloc(n_ciphone, sizeof(int32)); return beam; } static void beam_report(beam_t * b) { E_INFO_NOFN("Initialization of beam_t, report:\n"); E_INFO_NOFN("Parameters used in Beam Pruning of Viterbi Search:\n"); E_INFO_NOFN("Beam=%d\n", b->hmm); E_INFO_NOFN("PBeam=%d\n", b->ptrans); E_INFO_NOFN("WBeam=%d (Skip=%d)\n", b->word, b->ptranskip); E_INFO_NOFN("WEndBeam=%d \n", b->wordend); E_INFO_NOFN("No of CI Phone assumed=%d \n", b->n_ciphone); E_INFO_NOFN("\n"); } static void beam_free(beam_t * b) { if (b) { if (b->wordbestscores) { free(b->wordbestscores); } if (b->wordbestexits) { free(b->wordbestexits); } free(b); } } static lextree_t ** create_lextree(tst_search_t *tstg, const char *lmname, ptmr_t *tm_build) { int j; lextree_t **lextree; lextree = (lextree_t **)ckd_calloc(tstg->n_lextree, sizeof(lextree_t *)); hash_table_enter(tstg->ugtree, lmname, lextree); for (j = 0; j < tstg->n_lextree; ++j) { if (tm_build) ptmr_start(tm_build); lextree[j] = lextree_init(ps_search_acmod(tstg)->mdef, ps_search_acmod(tstg)->tmat, ps_search_dict(tstg), ps_search_dict2pid(tstg), tstg->fillpen, tstg->lmset, lmname, TRUE, TRUE, LEXTREE_TYPE_UNIGRAM); if (tm_build) ptmr_stop(tm_build); if (lextree[j] == NULL) { int i; E_INFO ("Failed to allocate lexical tree for lm %s and lextree %d\n", lmname, j); for (i = j - 1; i >= 0; --i) lextree_free(lextree[i]); ckd_free(lextree); return NULL; } E_INFO("Lextree (%d) for lm \"%s\" has %d nodes(ug)\n", j, lmname, lextree_n_node(lextree[j])); } lextree_report(lextree[0]); return lextree; } static int tst_search_reinit(ps_search_t *search) { /* set_lm() code goes here. */ return -1; } ps_search_t * tst_search_init(cmd_ln_t *config, acmod_t *acmod, s3dict_t *dict, dict2pid_t *d2p) { tst_search_t *tstg; char const *path; int32 n_ltree; int32 i, j; ptmr_t tm_build; ngram_model_set_iter_t *lmset_iter; lextree_t **lextree = NULL; tstg = ckd_calloc(1, sizeof(*tstg)); ps_search_init(&tstg->base, &tst_funcs, config, acmod, dict, d2p); tstg->fillpen = fillpen_init(ps_search_dict(tstg), NULL, cmd_ln_float32_r(config, "-silprob"), cmd_ln_float32_r(config, "-fillprob"), cmd_ln_float32_r(config, "-lw"), cmd_ln_float32_r(config, "-wip"), acmod->lmath); tstg->beam = beam_init(cmd_ln_float64_r(config, "-beam"), cmd_ln_float64_r(config, "-pbeam"), cmd_ln_float64_r(config, "-wbeam"), cmd_ln_float64_r(config, "-wend_beam"), 0, bin_mdef_n_ciphone(acmod->mdef), acmod->lmath); beam_report(tstg->beam); tstg->ssid_active = bitvec_alloc(bin_mdef_n_sseq(acmod->mdef)); tstg->comssid_active = bitvec_alloc(dict2pid_n_comsseq(ps_search_dict2pid(tstg))); tstg->composite_senone_scores = ckd_calloc(dict2pid_n_comstate(ps_search_dict2pid(tstg)), sizeof(*tstg->composite_senone_scores)); ptmr_init(&(tm_build)); tstg->epl = cmd_ln_int32_r(config, "-epl"); tstg->n_lextree = cmd_ln_int32_r(config, "-Nlextree"); n_ltree = tstg->n_lextree; /* Initialize language model set (this is done for us in Sphinx3, * but not in PocketSphinx) */ if ((path = cmd_ln_str_r(config, "-lmctl"))) { tstg->lmset = ngram_model_set_read(config, path, acmod->lmath); if (tstg->lmset == NULL) { E_ERROR("Failed to read language model control file: %s\n", path); goto error_out; } /* Set the default language model if needed. */ if ((path = cmd_ln_str_r(config, "-lmname"))) { ngram_model_set_select(tstg->lmset, path); } } else if ((path = cmd_ln_str_r(config, "-lm"))) { static const char *name = "default"; ngram_model_t *lm; lm = ngram_model_read(config, path, NGRAM_AUTO, acmod->lmath); if (lm == NULL) { E_ERROR("Failed to read language model file: %s\n", path); goto error_out; } tstg->lmset = ngram_model_set_init(config, &lm, (char **)&name, NULL, 1); if (tstg->lmset == NULL) { E_ERROR("Failed to initialize language model set\n"); goto error_out; } } /* STRUCTURE and REPORT: Initialize lexical tree. Filler tree's initialization is followed. */ tstg->ugtree = hash_table_new(ngram_model_set_count(tstg->lmset), HASH_CASE_YES); /* curugtree is a pointer pointing the current unigram tree which were being used. */ tstg->curugtree = (lextree_t **) ckd_calloc(n_ltree, sizeof(lextree_t *)); /* Just allocate pointers */ ptmr_reset(&(tm_build)); /* * Only create the lextree for the entire language model set * specific ones will be created in srch_TST_set_lm() */ if ((lextree = create_lextree(tstg, "lmset", &tm_build)) == NULL) { goto error_out; } for (j = 0; j < n_ltree; ++j) tstg->curugtree[j] = lextree[j]; E_INFO("Time for building trees, %4.4f CPU %4.4f Clk\n", tm_build.t_cpu, tm_build.t_elapsed); /* STRUCTURE: Create filler lextrees */ /* ARCHAN : only one filler tree is supposed to be built even for dynamic LMs */ tstg->fillertree = (lextree_t **) ckd_calloc(n_ltree, sizeof(lextree_t *)); for (i = 0; i < n_ltree; i++) { if ((tstg->fillertree[i] = fillertree_init(acmod->mdef, acmod->tmat, ps_search_dict(tstg), ps_search_dict2pid(tstg), tstg->fillpen)) == NULL) { E_INFO("Fail to allocate filler tree %d\n", i); goto error_out; } E_INFO("Lextrees(%d), %d nodes(filler)\n", i, lextree_n_node(tstg->fillertree[0])); } if (cmd_ln_int32_r(config, "-lextreedump")) { for (lmset_iter = ngram_model_set_iter(tstg->lmset); lmset_iter; lmset_iter = ngram_model_set_iter_next(lmset_iter)) { const char *model_name; ngram_model_set_iter_model(lmset_iter, &model_name); hash_table_lookup(tstg->ugtree, model_name, (void*)&lextree); for (j = 0; j < n_ltree; j++) { E_INFO("LM name: \'%s\' UGTREE: %d\n", model_name, j); lextree_dump(lextree[j], stderr, cmd_ln_int32_r(config, "-lextreedump")); } } ngram_model_set_iter_free(lmset_iter); for (i = 0; i < n_ltree; i++) { E_INFO("FILLERTREE %d\n", i); lextree_dump(tstg->fillertree[i], stderr, cmd_ln_int32_r(config, "-lextreedump")); } } tstg->histprune = histprune_init(cmd_ln_int32_r(config, "-maxhmmpf"), cmd_ln_int32_r(config, "-maxhistpf"), cmd_ln_int32_r(config, "-maxwpf"), cmd_ln_int32_r(config, "-hmmhistbinsize"), (tstg->curugtree[0]->n_node + tstg->fillertree[0]->n_node) * tstg->n_lextree); histprune_report(tstg->histprune); /* Viterbi history structure */ tstg->vithist = vithist_init(ngram_model_get_counts(tstg->lmset)[0], bin_mdef_n_ciphone(acmod->mdef), logmath_log(acmod->lmath, cmd_ln_float64_r(config, "-vhbeam")), cmd_ln_int32_r(config, "-bghist"), TRUE); return (ps_search_t *)tstg; error_out: tst_search_free(ps_search_base(tstg)); return NULL; } void tst_search_free(ps_search_t *search) { tst_search_t *tstg = (tst_search_t *)search; if (tstg == NULL) return; if (tstg->ugtree) { hash_iter_t *hiter = hash_table_iter(tstg->ugtree); if (hiter) do { lextree_t **lextree = (lextree_t**)hash_entry_val(hiter->ent); if (lextree) { int j; for (j = 0; j < tstg->n_lextree; ++j) lextree_free(lextree[j]); } } while ((hiter = hash_table_iter_next(hiter))); hash_table_free(tstg->ugtree); } ckd_free(tstg->curugtree); if (tstg->fillertree) { int32 j; for (j = 0; j < tstg->n_lextree; ++j) lextree_free(tstg->fillertree[j]); ckd_free(tstg->fillertree); } if (tstg->vithist) vithist_free(tstg->vithist); if (tstg->histprune) histprune_free(tstg->histprune); if (tstg->fillpen) fillpen_free(tstg->fillpen); if (tstg->beam) beam_free(tstg->beam); bitvec_free(tstg->ssid_active); bitvec_free(tstg->comssid_active); ckd_free(tstg->composite_senone_scores); ps_search_deinit(search); ckd_free(tstg); } static int tst_search_start(ps_search_t *search) { tst_search_t *tstg = (tst_search_t *)search; int32 n, pred; int32 i; /* Clean up any previous viterbi history */ vithist_utt_reset(tstg->vithist); histprune_zero_histbin(tstg->histprune); /* Reset statistics */ memset(&tstg->st, 0, sizeof(tstg->st)); tstg->n_frame = 0; /* Insert initial <s> into vithist structure */ pred = vithist_utt_begin(tstg->vithist, s3dict_startwid(ps_search_dict(tstg)), ngram_wid(tstg->lmset, "<s>")); assert(pred == 0); /* Vithist entry ID for <s> */ /* Need to reinitialize GMMs, things like that? */ /* Enter into unigram lextree[0] */ n = lextree_n_next_active(tstg->curugtree[0]); assert(n == 0); lextree_enter(tstg->curugtree[0], bin_mdef_silphone(ps_search_acmod(tstg)->mdef), -1, 0, pred, tstg->beam->hmm); /* Enter into filler lextree */ n = lextree_n_next_active(tstg->fillertree[0]); assert(n == 0); lextree_enter(tstg->fillertree[0], BAD_S3CIPID, -1, 0, pred, tstg->beam->hmm); tstg->n_lextrans = 1; tstg->exit_id = -1; for (i = 0; i < tstg->n_lextree; i++) { lextree_active_swap(tstg->curugtree[i]); lextree_active_swap(tstg->fillertree[i]); } return 0; } static int tst_search_finish(ps_search_t *search) { tst_search_t *tstg = (tst_search_t *)search; int32 i, cf; /* This is the number of frames processed. */ cf = ps_search_acmod(search)->output_frame; /* Find the exit word and wrap up Viterbi history (but don't reset * it yet!) */ tstg->exit_id = vithist_utt_end(tstg->vithist, tstg->lmset, ps_search_dict(tstg), ps_search_dict2pid(tstg), tstg->fillpen); /* Not sure hwo to get the uttid. */ histprune_showhistbin(tstg->histprune, cf, "histbin"); for (i = 0; i < tstg->n_lextree; i++) { lextree_utt_end(tstg->curugtree[i]); lextree_utt_end(tstg->fillertree[i]); } /* Print out some statistics. */ if (cf > 0) { E_INFO("%8d words recognized (%d/fr)\n", vithist_n_entry(tstg->vithist), (vithist_n_entry(tstg->vithist) + (cf >> 1)) / (cf + 1)); E_INFO("%8d senones evaluated (%d/fr)\n", tstg->st.n_senone_active_utt, (tstg->st.n_senone_active_utt + (cf >> 1)) / (cf + 1)); E_INFO("%8d channels searched (%d/fr)\n", tstg->st.n_hmm_eval, tstg->st.n_hmm_eval / (cf + 1)); } if (tstg->exit_id >= 0) return 0; else return -1; } static int srch_TST_hmm_compute_lv2(tst_search_t *tstg, int32 frmno) { /* This is local to this codebase */ int32 i, j; lextree_t *lextree; beam_t *bm; histprune_t *hp; int32 besthmmscr, bestwordscr; int32 frm_nhmm, hb, pb, wb; int32 n_ltree; /* Local version of number of lexical trees used */ int32 maxwpf; /* Local version of Max words per frame, don't expect it to change */ int32 maxhistpf; /* Local version of Max histories per frame, don't expect it to change */ int32 maxhmmpf; /* Local version of Max active HMMs per frame, don't expect it to change */ int32 histbinsize; /* Local version of histogram bin size, don't expect it to change */ int32 numhistbins; /* Local version of number of histogram bins, don't expect it to change */ int32 hmmbeam; /* Local version of hmm beam, don't expect it to change. */ int32 pbeam; /* Local version of phone beam, don't expect it to change. */ int32 wbeam; /* Local version of word beam , don't expect it to change */ int32 *hmm_hist; /* local version of histogram bins. */ n_ltree = tstg->n_lextree; hp = tstg->histprune; bm = tstg->beam; hmm_hist = hp->hmm_hist; maxwpf = hp->maxwpf; maxhistpf = hp->maxhistpf; maxhmmpf = hp->maxhmmpf; histbinsize = hp->hmm_hist_binsize; numhistbins = hp->hmm_hist_bins; hmmbeam = bm->hmm; pbeam = bm->ptrans; wbeam = bm->word; /* Evaluate active HMMs in each lextree; note best HMM state score */ besthmmscr = MAX_NEG_INT32; bestwordscr = MAX_NEG_INT32; frm_nhmm = 0; for (i = 0; i < (n_ltree << 1); i++) { lextree = (i < n_ltree) ? tstg->curugtree[i] : tstg->fillertree[i - n_ltree]; if (tstg->hmmdumpfp != NULL) fprintf(tstg->hmmdumpfp, "Fr %d Lextree %d #HMM %d\n", frmno, i, lextree->n_active); lextree_hmm_eval(lextree, ps_search_acmod(tstg)->senone_scores, tstg->composite_senone_scores, frmno, tstg->hmmdumpfp); if (besthmmscr < lextree->best) besthmmscr = lextree->best; if (bestwordscr < lextree->wbest) bestwordscr = lextree->wbest; tstg->st.n_hmm_eval += lextree->n_active; frm_nhmm += lextree->n_active; } if (besthmmscr > 0) { E_ERROR ("***ERROR*** Fr %d, best HMM score > 0 (%d); int32 wraparound?\n", frmno, besthmmscr); } /* Hack! similar to the one in mode 5. The reason though is because dynamic allocation of node cause the histroyt array need to be allocated too. I skipped this step by just making simple assumption here. */ if (frm_nhmm / histbinsize > hp->hmm_hist_bins - 1) hmm_hist[hp->hmm_hist_bins - 1]++; else hmm_hist[frm_nhmm / histbinsize]++; /* Set pruning threshold depending on whether number of active HMMs * is within limit */ /* ARCHAN: MAGIC */ if (maxhmmpf != -1 && frm_nhmm > (maxhmmpf + (maxhmmpf >> 1))) { int32 *bin, nbin, bw; /* Use histogram pruning */ nbin = 1000; bw = -(hmmbeam) / nbin; bin = (int32 *) ckd_calloc(nbin, sizeof(int32)); for (i = 0; i < (n_ltree << 1); i++) { lextree = (i < n_ltree) ? tstg->curugtree[i] : tstg->fillertree[i - n_ltree]; lextree_hmm_histbin(lextree, besthmmscr, bin, nbin, bw); } for (i = 0, j = 0; (i < nbin) && (j < maxhmmpf); i++, j += bin[i]); ckd_free((void *) bin); /* Determine hmm, phone, word beams */ hb = -(i * bw); pb = (hb > pbeam) ? hb : pbeam; wb = (hb > wbeam) ? hb : wbeam; } else { hb = hmmbeam; pb = pbeam; wb = wbeam; } bm->bestscore = besthmmscr; bm->bestwordscore = bestwordscr; bm->thres = bm->bestscore + hb; /* HMM survival threshold */ bm->phone_thres = bm->bestscore + pb; /* Cross-HMM transition threshold */ bm->word_thres = bm->bestwordscore + wb; /* Word exit threshold */ return 0; } static int srch_TST_propagate_graph_ph_lv2(tst_search_t *tstg, int32 frmno) { int32 i; int32 n_ltree; /* Local version of number of lexical trees used */ lextree_t *lextree; n_ltree = tstg->n_lextree; for (i = 0; i < (n_ltree << 1); i++) { lextree = (i < n_ltree) ? tstg->curugtree[i] : tstg->fillertree[i - tstg-> n_lextree]; if (lextree_hmm_propagate_non_leaves(lextree, frmno, tstg->beam->thres, tstg->beam->phone_thres, tstg->beam->word_thres) != LEXTREE_OPERATION_SUCCESS) { E_ERROR ("Propagation Failed for lextree_hmm_propagate_non_leave at tree %d\n", i); lextree_utt_end(lextree); return -1; } } return 0; } static void mdef_sseq2sen_active(bin_mdef_t * mdef, bitvec_t * sseq, bitvec_t * sen) { int32 ss, i; s3senid_t *sp; for (ss = 0; ss < bin_mdef_n_sseq(mdef); ss++) { if (bitvec_is_set(sseq,ss)) { sp = mdef->sseq[ss]; for (i = 0; i < mdef_n_emit_state(mdef); i++) bitvec_set(sen, sp[i]); } } } static int srch_TST_select_active_gmm(tst_search_t *tstg) { int32 n_ltree; /* Local version of number of lexical trees used */ dict2pid_t *d2p; bin_mdef_t *mdef; lextree_t *lextree; int32 i; n_ltree = tstg->n_lextree; mdef = ps_search_acmod(tstg)->mdef; d2p = ps_search_dict2pid(tstg); bitvec_clear_all(tstg->ssid_active, bin_mdef_n_sseq(mdef)); bitvec_clear_all(tstg->comssid_active, dict2pid_n_comsseq(d2p)); /* Find active senone-sequence IDs (including composite ones) */ for (i = 0; i < (n_ltree << 1); i++) { lextree = (i < n_ltree) ? tstg->curugtree[i] : tstg->fillertree[i - n_ltree]; lextree_ssid_active(lextree, tstg->ssid_active, tstg->comssid_active); } /* Find active senones from active senone-sequences */ acmod_clear_active(ps_search_acmod(tstg)); mdef_sseq2sen_active(mdef, tstg->ssid_active, ps_search_acmod(tstg)->senone_active_vec); /* Add in senones needed for active composite senone-sequences */ dict2pid_comsseq2sen_active(d2p, mdef, tstg->comssid_active, ps_search_acmod(tstg)->senone_active_vec); return 0; } static int srch_TST_rescoring(tst_search_t *tstg, int32 frmno) { int32 i; int32 n_ltree; /* Local version of number of lexical trees used */ lextree_t *lextree; vithist_t *vh; vh = tstg->vithist; n_ltree = tstg->n_lextree; for (i = 0; i < (n_ltree * 2); i++) { lextree = (i < n_ltree) ? tstg->curugtree[i] : tstg->fillertree[i - tstg->n_lextree]; E_DEBUG(1,("Propagating words from lextree %d\n", i)); if (lextree_hmm_propagate_leaves (lextree, vh, frmno, tstg->beam->word_thres) != LEXTREE_OPERATION_SUCCESS) { E_ERROR ("Propagation Failed for lextree_hmm_propagate_leave at tree %d\n", i); lextree_utt_end(lextree); return -1; } } return 0; } static void srch_utt_word_trans(tst_search_t * tstg, int32 cf) { int32 k, th; vithist_t *vh; vithist_entry_t *ve; int32 vhid, le, n_ci, score; int32 maxpscore; int32 *bs = NULL, *bv = NULL, epl; beam_t *bm; s3wid_t wid; int32 p; s3dict_t *dict; bin_mdef_t *mdef; /* Call the rescoring routines at all word end */ maxpscore = MAX_NEG_INT32; bm = tstg->beam; vh = tstg->vithist; th = bm->bestscore + bm->hmm; /* Pruning threshold */ if (vh->bestvh[cf] < 0) return; dict = ps_search_dict(tstg); mdef = ps_search_acmod(tstg)->mdef; n_ci = bin_mdef_n_ciphone(mdef); /* Initialize best exit for each distinct word-final CI phone to NONE */ bs = bm->wordbestscores; bv = bm->wordbestexits; epl = tstg->epl; for (p = 0; p < n_ci; p++) { bs[p] = MAX_NEG_INT32; bv[p] = -1; } /* Find best word exit in this frame for each distinct word-final CI phone */ vhid = vithist_first_entry(vh, cf); le = vithist_n_entry(vh) - 1; for (; vhid <= le; vhid++) { ve = vithist_id2entry(vh, vhid); if (!vithist_entry_valid(ve)) continue; wid = vithist_entry_wid(ve); p = s3dict_last_phone(dict, wid); if (bin_mdef_is_fillerphone(mdef, p)) p = bin_mdef_silphone(mdef); score = vithist_entry_score(ve); if (score > bs[p]) { bs[p] = score; bv[p] = vhid; if (maxpscore < score) { maxpscore = score; /* E_INFO("maxscore = %d\n", maxpscore); */ } } } /* Find lextree instance to be entered */ k = tstg->n_lextrans++; k = (k % (tstg->n_lextree * epl)) / epl; /* Transition to unigram lextrees */ for (p = 0; p < n_ci; p++) { if (bv[p] >= 0) { if (tstg->beam->wordend == 0 || bs[p] > tstg->beam->wordend + maxpscore) { /* RAH, typecast p to (s3cipid_t) to make compiler happy */ lextree_enter(tstg->curugtree[k], (s3cipid_t) p, cf, bs[p], bv[p], th); } } } /* Transition to filler lextrees */ lextree_enter(tstg->fillertree[k], BAD_S3CIPID, cf, vh->bestscore[cf], vh->bestvh[cf], th); } static int srch_TST_propagate_graph_wd_lv2(tst_search_t *tstg, int32 frmno) { s3dict_t *dict; vithist_t *vh; histprune_t *hp; int32 maxwpf; /* Local version of Max words per frame, don't expect it to change */ int32 maxhistpf; /* Local version of Max histories per frame, don't expect it to change */ int32 maxhmmpf; /* Local version of Max active HMMs per frame, don't expect it to change */ hp = tstg->histprune; vh = tstg->vithist; dict = ps_search_dict(tstg); maxwpf = hp->maxwpf; maxhistpf = hp->maxhistpf; maxhmmpf = hp->maxhmmpf; srch_TST_rescoring(tstg, frmno); vithist_prune(vh, dict, frmno, maxwpf, maxhistpf, tstg->beam->word_thres - tstg->beam->bestwordscore); srch_utt_word_trans(tstg, frmno); return 0; } static int srch_TST_frame_windup(tst_search_t *tstg, int32 frmno) { vithist_t *vh; int32 i; vh = tstg->vithist; /* Wind up this frame */ vithist_frame_windup(vh, frmno, NULL, tstg->lmset, ps_search_dict(tstg)); for (i = 0; i < tstg->n_lextree; i++) { lextree_active_swap(tstg->curugtree[i]); lextree_active_swap(tstg->fillertree[i]); } return 0; } static int tst_search_step(ps_search_t *search, int frame_idx) { tst_search_t *tstg = (tst_search_t *)search; int16 const *senscr; /* Select active senones for the current frame. */ srch_TST_select_active_gmm(tstg); /* Compute GMM scores for the current frame. */ if ((senscr = acmod_score(ps_search_acmod(search), &frame_idx)) == NULL) return 0; tstg->st.n_senone_active_utt += ps_search_acmod(search)->n_senone_active; /* Evaluate composite senone scores from senone scores */ memset(tstg->composite_senone_scores, 0, dict2pid_n_comstate(ps_search_dict2pid(tstg)) * sizeof(*tstg->composite_senone_scores)); dict2pid_comsenscr(ps_search_dict2pid(tstg), senscr, tstg->composite_senone_scores); /* Compute HMMs, propagate phone and word exits, etc, etc. */ srch_TST_hmm_compute_lv2(tstg, frame_idx); srch_TST_propagate_graph_ph_lv2(tstg, frame_idx); srch_TST_propagate_graph_wd_lv2(tstg, frame_idx); srch_TST_frame_windup(tstg, frame_idx); /* FIXME: Renormalization? */ ++tstg->n_frame; /* Return the number of frames processed. */ return 1; } static ps_lattice_t * tst_search_lattice(ps_search_t *search) { tst_search_t *tstg = (tst_search_t *)search; vithist_t *vh; glist_t *sfwid; /* To maintain <start-frame, word-id> pair dagnodes */ gnode_t *gn, *gn2, *gn3; int32 min_ef_range; int32 sf, ef, n_node; int32 f, i; ps_lattice_t *dag; ps_latnode_t *dn; int32 exit_id, id; vh = tstg->vithist; if (tstg->exit_id == -1) /* Search not finished */ exit_id = vithist_partialutt_end(vh, tstg->lmset, ps_search_dict(tstg)); else exit_id = tstg->exit_id; if (exit_id < 0) { E_WARN("Failed to retrieve viterbi history.\n"); return NULL; } /* Check to see if a lattice has previously been created over the * same number of frames, and reuse it if so. */ if (search->dag && search->dag->n_frames == tstg->n_frame) return search->dag; /* Nope, create a new one. */ ps_lattice_free(search->dag); search->dag = NULL; dag = ps_lattice_init_search(search, tstg->n_frame); /* Track starting frame, word id pairs. */ sfwid = (glist_t *) ckd_calloc(vh->n_frm + 1, sizeof(glist_t)); /* Min. endframes value that a node must persist for it to be not ignored */ min_ef_range = cmd_ln_int32_r(ps_search_config(search), "-min_endfr"); sf = 0; for (i = 0; i < vh->n_entry; i++) { /* This range includes the dummy <s> and </s> entries */ ps_latnode_t *dn; vithist_entry_t *ve, *ve2; ve = vithist_id2entry(vh, i); if (!ve->valid) continue; /* * The initial <s> entry (at 0) is a dummy, with start/end frame = -1. But the old S3 * code treats it like a real word, so we have to reintroduce it in the dag file with * a start time of 0. And shift the start time of words starting at frame 0 up by 1. * MAJOR HACK!! */ if (ve->sf == -1) { assert(ve->ef == -1); sf = ef = 0; } else if (ve->sf == 0) { assert(ve->ef > 0); sf = ve->sf + 1; ef = ve->ef; } else { sf = ve->sf; ef = ve->ef; } /* Look for other instances of this word starting in the same frame. */ for (gn = sfwid[sf]; gn; gn = gnode_next(gn)) { dn = (ps_latnode_t *) gnode_ptr(gn); if (dn->wid == ve->wid) break; } /* Create a new one if not. */ if (!gn) { dn = listelem_malloc(dag->latnode_alloc); memset(dn, 0, sizeof(*dn)); dn->wid = ve->wid; dn->sf = sf; dn->fef = ef; dn->lef = ef; dn->id = -1; /* Initially all invalid, selected ones validated below */ ++dag->n_nodes; sfwid[sf] = glist_add_ptr(sfwid[sf], (void *) dn); } else { dn->lef = ef; } if (i == exit_id) dag->end = dn; /* * Check if an entry already exists under dn->velist (generated by a different * LM context; retain only the best scoring one. */ for (gn = dn->info.velist; gn; gn = gnode_next(gn)) { ve2 = (vithist_entry_t *) gnode_ptr(gn); if (ve2->ef == ve->ef) break; } if (gn) { if (ve->path.score > ve2->path.score) gnode_ptr(gn) = (void *) ve; } else dn->info.velist = glist_add_ptr(dn->info.velist, (void *) ve); } /* * Validate segments with >=min_endfr end times. * But keep segments in the original hypothesis, regardless; mark them first. */ id = exit_id; while (id >= 0) { vithist_entry_t *ve = vithist_id2entry(vh, id); /* * As long as the above comment about the MAJOR HACK is true * the start time has to be hacked here too */ int hacked_sf = vithist_entry_sf(ve); if (hacked_sf <= 0) ++hacked_sf; assert(hacked_sf >= 0); for (gn2 = sfwid[hacked_sf]; gn2; gn2 = gnode_next(gn2)) { ps_latnode_t *dn = (ps_latnode_t *) gnode_ptr(gn2); if (vithist_entry_wid(ve) == dn->wid) dn->id = 0; /* Do not discard (prune) this dagnode */ } id = vithist_entry_pred(ve); } /* Validate startwid and finishwid nodes */ dn = (ps_latnode_t *) gnode_ptr(sfwid[0]); assert(dn->wid == s3dict_startwid(ps_search_dict(tstg))); dn->id = 0; dag->start = dn; dn = (ps_latnode_t *) gnode_ptr(sfwid[vh->n_frm]); assert(dn->wid == s3dict_finishwid(ps_search_dict(tstg))); dn->id = 0; /* If for some reason the final node is not the same as the end * node, make sure it exists and is also marked valid. */ if (dag->end == NULL) { E_WARN("Final vithist entry %d not found, using </s> node\n", exit_id); dag->end = dn; } dag->end->id = 0; /* Find the exit score for the end node. */ for (gn = (glist_t)dag->end->info.velist; gn; gn = gnode_next(gn)) { vithist_entry_t *ve2 = (vithist_entry_t *) gnode_ptr(gn); if (ve2->ef == vh->n_frm) dag->final_node_ascr = ve2->ascr; } /* Now prune dagnodes with <min_endfr end frames if not validated above */ i = 0; for (f = 0; f <= vh->n_frm; ++f) { for (gn = sfwid[f]; gn; gn = gnode_next(gn)) { ps_latnode_t *dn = (ps_latnode_t *) gnode_ptr(gn); if ((dn->lef - dn->fef > min_ef_range) || (dn->id >= 0)) { dn->id = i++; dn->next = dag->nodes; dag->nodes = dn; } else dn->id = -1; /* Flag: discard */ } } for (f = 0; f < vh->n_frm; ++f) { for (gn = sfwid[f]; gn; gn = gnode_next(gn)) { ps_latnode_t *dn = (ps_latnode_t *) gnode_ptr(gn); /* Look for transitions from this dagnode to later ones, if not discarded */ if (dn->id < 0) continue; for (gn2 = (glist_t) dn->info.velist; gn2; gn2 = gnode_next(gn2)) { vithist_entry_t *ve = (vithist_entry_t *) gnode_ptr(gn2); sf = (ve->ef < 0) ? 1 : (ve->ef + 1); for (gn3 = sfwid[sf]; gn3; gn3 = gnode_next(gn3)) { ps_latnode_t *dn2 = (ps_latnode_t *) gnode_ptr(gn3); if (dn2->id >= 0) ps_lattice_link(dag, dn, dn2, ve->ascr, sf - 1); } } } } /* Free dagnodes structure */ for (f = 0; f <= vh->n_frm; f++) { for (gn = sfwid[f]; gn; gn = gnode_next(gn)) { ps_latnode_t *dn = (ps_latnode_t *) gnode_ptr(gn); glist_free((glist_t) dn->info.velist); dn->info.velist = NULL; if (dn->id == -1) { /* If pruned, free the node too */ listelem_free(dag->latnode_alloc, dn); --dag->n_nodes; } } glist_free(sfwid[f]); } ckd_free((void *)sfwid); dag->n_frames = vh->n_frm; /* FIXME: We should delete unreachable nodes here. */ /* Build links around silence and filler words, since they do not * exist in the language model. */ ps_lattice_bypass_fillers (dag, logmath_log(ps_search_acmod(search)->lmath, tstg->fillpen->silprob), logmath_log(ps_search_acmod(search)->lmath, tstg->fillpen->fillerprob)); search->dag = dag; return dag; } static char const * tst_search_hyp(ps_search_t *base, int32 *out_score) { tst_search_t *tstg = (tst_search_t *)base; vithist_entry_t *ve; char *c; size_t len; int32 exit_id, id; if (tstg->exit_id == -1) /* Search not finished */ exit_id = vithist_partialutt_end(tstg->vithist, tstg->lmset, ps_search_dict(tstg)); else exit_id = tstg->exit_id; if (exit_id < 0) { E_WARN("Failed to retrieve viterbi history.\n"); return NULL; } ve = vithist_id2entry(tstg->vithist, exit_id); *out_score = ve->ascr + ve->lscr; id = exit_id; len = 0; while (id >= 0) { s3wid_t wid; ve = vithist_id2entry(tstg->vithist, id); assert(ve); wid = vithist_entry_wid(ve); id = ve->path.pred; if (s3dict_filler_word(ps_search_dict(tstg), wid) || wid == s3dict_startwid(ps_search_dict(tstg)) || wid == s3dict_finishwid(ps_search_dict(tstg))) continue; len += strlen(s3dict_wordstr(ps_search_dict(tstg), s3dict_basewid(ps_search_dict(tstg), wid))) + 1; } ckd_free(base->hyp_str); if (len == 0) { base->hyp_str = NULL; return base->hyp_str; } base->hyp_str = ckd_calloc(1, len); id = exit_id; c = base->hyp_str + len - 1; while (id >= 0) { s3wid_t wid; ve = vithist_id2entry(tstg->vithist, id); assert(ve); wid = vithist_entry_wid(ve); id = ve->path.pred; if (s3dict_filler_word(ps_search_dict(tstg), wid) || wid == s3dict_startwid(ps_search_dict(tstg)) || wid == s3dict_finishwid(ps_search_dict(tstg))) continue; len = strlen(s3dict_wordstr(ps_search_dict(tstg), s3dict_basewid(ps_search_dict(tstg), wid))); c -= len; memcpy(c, s3dict_wordstr(ps_search_dict(tstg), s3dict_basewid(ps_search_dict(tstg), wid)), len); if (c > base->hyp_str) { --c; *c = ' '; } } return base->hyp_str; } static int32 tst_search_prob(ps_search_t *search) { /* Bogus out-of-band value for now. */ return 1; } /** * Segmentation "iterator" for vithist results. */ typedef struct tst_seg_s { ps_seg_t base; /**< Base structure. */ int32 *bpidx; /**< Sequence of backpointer IDs. */ int16 n_bpidx; /**< Number of backpointer IDs. */ int16 cur; /**< Current position in bpidx. */ } tst_seg_t; static void tst_search_bp2itor(ps_seg_t *seg, int id) { tst_search_t *tstg = (tst_search_t *)seg->search; vithist_entry_t *ve; ve = vithist_id2entry(tstg->vithist, id); assert(ve); seg->word = s3dict_wordstr(ps_search_dict(tstg), vithist_entry_wid(ve)); seg->ef = vithist_entry_ef(ve); seg->sf = vithist_entry_sf(ve); seg->prob = 0; /* Bogus value... */ seg->ascr = vithist_entry_ascr(ve); seg->lscr = vithist_entry_lscr(ve); seg->lback = 0; /* FIXME: Compute this somewhere... */ } static void tst_seg_free(ps_seg_t *seg) { tst_seg_t *itor = (tst_seg_t *)seg; ckd_free(itor->bpidx); ckd_free(itor); } static ps_seg_t * tst_seg_next(ps_seg_t *seg) { tst_seg_t *itor = (tst_seg_t *)seg; if (++itor->cur == itor->n_bpidx) { tst_seg_free(seg); return NULL; } tst_search_bp2itor(seg, itor->bpidx[itor->cur]); return seg; } static ps_segfuncs_t tst_segfuncs = { /* seg_next */ tst_seg_next, /* seg_free */ tst_seg_free }; static ps_seg_t * tst_search_seg_iter(ps_search_t *search, int32 *out_score) { tst_search_t *tstg = (tst_search_t *)search; tst_seg_t *itor; int exit_id, id, cur; if (tstg->exit_id == -1) /* Search not finished */ exit_id = vithist_partialutt_end(tstg->vithist, tstg->lmset, ps_search_dict(tstg)); else exit_id = tstg->exit_id; if (exit_id < 0) { E_WARN("Failed to retrieve viterbi history.\n"); return NULL; } /* Calling this an "iterator" is a bit of a misnomer since we have * to get the entire backtrace in order to produce it. On the * other hand, all we actually need is the vithist IDs, and we can * allocate a fixed-size array of them. */ itor = ckd_calloc(1, sizeof(*itor)); itor->base.vt = &tst_segfuncs; itor->base.search = search; itor->base.lwf = 1.0; itor->n_bpidx = 0; id = exit_id; while (id >= 0) { vithist_entry_t *ve = vithist_id2entry(tstg->vithist, id); assert(ve); id = vithist_entry_pred(ve); ++itor->n_bpidx; } if (itor->n_bpidx == 0) { ckd_free(itor); return NULL; } itor->bpidx = ckd_calloc(itor->n_bpidx, sizeof(*itor->bpidx)); cur = itor->n_bpidx - 1; id = exit_id; while (id >= 0) { vithist_entry_t *ve = vithist_id2entry(tstg->vithist, id); assert(ve); itor->bpidx[cur] = id; id = vithist_entry_pred(ve); --cur; } /* Fill in relevant fields for first element. */ tst_search_bp2itor((ps_seg_t *)itor, itor->bpidx[0]); return (ps_seg_t *)itor; } <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/corpus/RegionOfAudioData.java package edu.cmu.sphinx.tools.corpus; import edu.cmu.sphinx.tools.audio.AudioData; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Mar 3, 2006 * Time: 9:48:04 PM */ /** * RegionOfAudioData is a base class of behavior common to all ojects that describe a region of audio data such as * a recording of a Word or an Utterance. All RegionOfAudioData objects may be decorated with mulitple Notes that associate * user text with a region of time. Finally, all RegionOfAudioData objects may be marked at "excluded" which means that * refer to flawed data and should not be used in the testing and training. */ public class RegionOfAudioData { protected AudioDatabase audioDatabase; protected int beginTime; protected int endTime; protected Collection<Note> notes; protected boolean isExcluded; public boolean isExcluded() { return isExcluded; } public void setNotes(Collection<Note> notes) { this.notes = notes; } public void setExcluded(boolean excluded) { isExcluded = excluded; } public void addNote(Note note) { this.notes.add(note); } public Collection<Note> getNotes() { return notes; } public AudioDatabase getAudioDatabase() { return audioDatabase; } public void setAudioDatabase(AudioDatabase audioDatabase) { this.audioDatabase = audioDatabase; } public int getBeginTime() { return beginTime; } public void setBeginTime(int beginTime) { this.beginTime = beginTime; } public int getEndTime() { return endTime; } public void setEndTime(int endTime) { this.endTime = endTime; } public InputStream toInputStream() throws IOException { audioDatabase.getPcm().open(); InputStream s = new ByteArrayInputStream(audioDatabase.getPcm().readPcmAsBytes(beginTime, endTime)); audioDatabase.getPcm().close(); return s; } public AudioData getAudioData() throws IOException { audioDatabase.getPcm().open(); AudioData ad = new AudioData(audioDatabase.getPcm().readPcmAsShorts(beginTime, endTime), audioDatabase.getPcm().getSamplesPerSecond()); audioDatabase.getPcm().close(); return ad; } public double[] getPitchData() { return null; } public double[] getEnergyData() { return null; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final RegionOfAudioData that = (RegionOfAudioData) o; if (beginTime != that.beginTime) return false; if (endTime != that.endTime) return false; if (isExcluded != that.isExcluded) return false; if (audioDatabase != null ? !audioDatabase.equals(that.audioDatabase) : that.audioDatabase != null) return false; if (notes != null ? !notes.equals(that.notes) : that.notes != null) return false; return true; } public int hashCode() { int result; result = (audioDatabase != null ? audioDatabase.hashCode() : 0); result = 29 * result + beginTime; result = 29 * result + endTime; result = 29 * result + (notes != null ? notes.hashCode() : 0); result = 29 * result + (isExcluded ? 1 : 0); return result; } } <file_sep>/archive_s3/s3.2/src/feat.h /* * feat.h -- Cepstral features computation. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 04-Jan-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_FEAT_H_ #define _S3_FEAT_H_ #include <libutil/libutil.h> /* * Structure for describing a speech feature type (no. of streams and stream widths), * as well as the computation for converting the input speech (e.g., Sphinx-II format * MFC cepstra) into this type of feature vectors. */ typedef struct feat_s { char *name; /* Printable name for this feature type */ int32 cepsize; /* Size of input speech vector (typically, a cepstrum vector) */ int32 cepsize_used; /* No. of cepstrum vector dimensions actually used (0 onwards) */ int32 n_stream; /* #Feature streams; e.g., 4 in Sphinx-II */ int32 *stream_len; /* Vector length of each feature stream */ int32 window_size; /* #Extra frames around given input frame needed to compute corresponding output feature (so total = window_size*2 + 1) */ int32 cmn; /* Whether CMN is to be performed on each utterance */ int32 varnorm; /* Whether variance normalization is to be performed on each utt; Irrelevant if no CMN is performed */ int32 agc; /* Whether AGC-Max is to be performed on each utterance */ void (*compute_feat)(struct feat_s *fcb, float32 **input, float32 **feat); /* Function for converting window of input speech vector (input[-window_size..window_size]) to output feature vector (feat[stream][]). If NULL, no conversion available, the speech input must be feature vector itself. Return value: 0 if successful, -ve otherwise. */ } feat_t; /* Access macros */ #define feat_name(f) ((f)->name) #define feat_cepsize(f) ((f)->cepsize) #define feat_cepsize_used(f) ((f)->cepsize_used) #define feat_n_stream(f) ((f)->n_stream) #define feat_stream_len(f,i) ((f)->stream_len[i]) #define feat_window_size(f) ((f)->window_size) /* * Read feature vectors from the given file. Feature file format: * Line containing the single word: s3 * File header including any argument value pairs/line and other text (e.g., * 'chksum0 yes', 'version 1.0', as in other S3 format binary files) * Header ended by line containing the single word: endhdr * (int32) Byte-order magic number (0x11223344) * (int32) No. of frames in file (N) * (int32) No. of feature streams (S) * (int32 x S) Width or dimensionality of each feature stream (sum = L) * (float32) Feature vector data (NxL float32 items). * (uint32) Checksum (if present). * (Note that this routine does NOT verify the checksum.) * Return value: # frames read if successful, -1 if error. */ int32 feat_readfile (feat_t *fcb, /* In: Control block from feat_init() */ char *file, /* In: File to read */ int32 sf, /* In: Start/end frames (range) to be read from file; use 0, 0x7ffffff0 to read entire file */ int32 ef, float32 ***feat, /* Out: Data structure to be filled with read data; allocate using feat_array_alloc() */ int32 maxfr); /* In: #Frames allocated for feat above; error if attempt to read more than this amount. */ /* * Counterpart to feat_readfile. Feature data is assumed to be in a contiguous block * starting from feat[0][0][0]. (NOTE: No checksum is written.) * Return value: # frames read if successful, -1 if error. */ int32 feat_writefile (feat_t *fcb, /* In: Control block from feat_init() */ char *file, /* In: File to write */ float32 ***feat, /* In: Feature data to be written */ int32 nfr); /* In: #Frames to be written */ /* * Read Sphinx-II format mfc file (s2mfc = Sphinx-II format MFC data). * Return value: #frames read if successful, -1 if error (e.g., mfc array too small). */ int32 feat_s2mfc_read (char *file, /* In: Sphinx-II format MFC file to be read */ int32 sf, int32 ef, /* In: Start/end frames (range) to be read from file; Can use 0,-1 to read entire file */ float32 **mfc, /* Out: 2-D array to be filled with read data; caller must have allocated this array */ int32 maxfr); /* In: #Frames of mfc array allocated; error if attempt to read more than this amount. */ /* * Allocate an array to hold several frames worth of feature vectors. The returned value * is the float32 ***data array, organized as follows: * data[0][0] = frame 0 stream 0 vector, data[0][1] = frame 0 stream 1 vector, ... * data[1][0] = frame 1 stream 0 vector, data[0][1] = frame 1 stream 1 vector, ... * data[2][0] = frame 2 stream 0 vector, data[0][1] = frame 2 stream 1 vector, ... * ... * NOTE: For I/O convenience, the entire data area is allocated as one contiguous block. * Return value: Pointer to the allocated space if successful, NULL if any error. */ float32 ***feat_array_alloc (feat_t *fcb, /* In: Descriptor from feat_init(), used to obtain #streams and stream sizes */ int32 nfr); /* In: #Frames for which to allocate */ /* * Like feat_array_alloc except that only a single frame is allocated. Hence, one * dimension less. */ float32 **feat_vector_alloc (feat_t *fcb); /* In: Descriptor from feat_init(), used to obtain #streams and stream sizes */ /* * Initialize feature module to use the selected type of feature stream. One-time only * initialization at the beginning of the program. Input type is a string defining the * kind of input->feature conversion desired: * "s2_4x": s2mfc->Sphinx-II 4-feature stream, * "s3_1x39": s2mfc->Sphinx-3 single feature stream, * "n1,n2,n3,...": Explicit feature vector layout spec. with comma-separated feature * stream lengths. In this case, the input data is already in the feature format * and there is no conversion necessary. * Return value: (feat_t *) descriptor if successful, NULL if error. Caller must not * directly modify the contents of the returned value. */ feat_t *feat_init (char *type, /* In: Type of feature stream */ char *cmn, /* In: Type of cepstram mean normalization to be done before feature computation; can be NULL (for none) */ char *varnorm, /* In: ("yes" or "no") Whether variance normalization done on each utt; only applicable if CMN also done */ char *agc); /* In: Type of automatic gain control to be done before feature computation; can be NULL (for none) */ /* * Print the given block of feature vectors to the given FILE. */ void feat_print (feat_t *fcb, /* In: Descriptor from feat_init() */ float32 ***feat, /* In: Feature data to be printed */ int32 nfr, /* In: #Frames of feature data above */ FILE *fp); /* In: Output file pointer */ /* * Read a specified MFC file (or given segment within it), perform CMN/AGC as indicated by * fcb, and compute feature vectors. Feature vectors are computed for the entire segment * specified, by including additional surrounding or padding frames to accommodate the feature * windows. * Return value: #Frames of feature vectors computed if successful; -1 if any error. */ int32 feat_s2mfc2feat (feat_t *fcb, /* In: Descriptor from feat_init() */ char *file, /* In: File to be read */ char *dir, /* In: Directory prefix for file, if needed; can be NULL */ int32 sf, int32 ef, /* Start/End frames within file to be read. Use 0,-1 to process entire file */ float32 ***feat, /* Out: Computed feature vectors; caller must allocate this space */ int32 maxfr); /* In: Available space (#frames) in above feat array; it must be sufficient to accommodate the result */ #endif <file_sep>/archive_s3/s3.2/src/libutil/glist.c /* * glist.h -- Module for maintaining a generic, linear linked-list structure. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 09-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added glist_chkdup_*(). * * 13-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Created from earlier version. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "glist.h" #include "ckd_alloc.h" glist_t glist_add_ptr (glist_t g, void *ptr) { gnode_t *gn; gn = (gnode_t *) mymalloc (sizeof(gnode_t)); gn->data.ptr = ptr; gn->next = g; return ((glist_t) gn); /* Return the new head of the list */ } glist_t glist_add_int32 (glist_t g, int32 val) { gnode_t *gn; gn = (gnode_t *) mymalloc (sizeof(gnode_t)); gn->data.int32 = val; gn->next = g; return ((glist_t) gn); /* Return the new head of the list */ } glist_t glist_add_uint32 (glist_t g, uint32 val) { gnode_t *gn; gn = (gnode_t *) mymalloc (sizeof(gnode_t)); gn->data.uint32 = val; gn->next = g; return ((glist_t) gn); /* Return the new head of the list */ } glist_t glist_add_float32 (glist_t g, float32 val) { gnode_t *gn; gn = (gnode_t *) mymalloc (sizeof(gnode_t)); gn->data.float32 = val; gn->next = g; return ((glist_t) gn); /* Return the new head of the list */ } glist_t glist_add_float64 (glist_t g, float64 val) { gnode_t *gn; gn = (gnode_t *) mymalloc (sizeof(gnode_t)); gn->data.float64 = val; gn->next = g; return ((glist_t) gn); /* Return the new head of the list */ } int32 glist_chkdup_ptr (glist_t g, void *val) { gnode_t *gn; for (gn = g; gn; gn = gnode_next(gn)) if (gnode_ptr(gn) == val) return 1; return 0; } int32 glist_chkdup_int32 (glist_t g, int32 val) { gnode_t *gn; for (gn = g; gn; gn = gnode_next(gn)) if (gnode_int32(gn) == val) return 1; return 0; } int32 glist_chkdup_uint32 (glist_t g, uint32 val) { gnode_t *gn; for (gn = g; gn; gn = gnode_next(gn)) if (gnode_uint32(gn) == val) return 1; return 0; } int32 glist_chkdup_float32 (glist_t g, float32 val) { gnode_t *gn; for (gn = g; gn; gn = gnode_next(gn)) if (gnode_float32(gn) == val) return 1; return 0; } int32 glist_chkdup_float64 (glist_t g, float64 val) { gnode_t *gn; for (gn = g; gn; gn = gnode_next(gn)) if (gnode_float64(gn) == val) return 1; return 0; } void glist_apply_ptr (glist_t g, void (*func)(void *)) { gnode_t *gn; for (gn = g; gn; gn = gn->next) (*func)(gn->data.ptr); } void glist_apply_int32 (glist_t g, void (*func)(int32)) { gnode_t *gn; for (gn = g; gn; gn = gn->next) (*func)(gn->data.int32); } void glist_apply_uint32 (glist_t g, void (*func)(uint32)) { gnode_t *gn; for (gn = g; gn; gn = gn->next) (*func)(gn->data.uint32); } void glist_apply_float32 (glist_t g, void (*func)(float32)) { gnode_t *gn; for (gn = g; gn; gn = gn->next) (*func)(gn->data.float32); } void glist_apply_float64 (glist_t g, void (*func)(float64)) { gnode_t *gn; for (gn = g; gn; gn = gn->next) (*func)(gn->data.float64); } void glist_free (glist_t g) { gnode_t *gn; while (g) { gn = g; g = gn->next; myfree((char *)gn, sizeof(gnode_t)); } } void glist_myfree (glist_t g, int32 datasize) { gnode_t *gn; while (g) { gn = g; g = gn->next; myfree((char *)(gn->data.ptr), datasize); myfree((char *)gn, sizeof(gnode_t)); } } int32 glist_count (glist_t g) { gnode_t *gn; int32 n; for (gn = g, n = 0; gn; gn = gn->next, n++); return n; } gnode_t *glist_tail (glist_t g) { gnode_t *gn; if (! g) return NULL; for (gn = g; gn->next; gn = gn->next); return gn; } glist_t glist_reverse (glist_t g) { gnode_t *gn, *nextgn; gnode_t *rev; rev = NULL; for (gn = g; gn; gn = nextgn) { nextgn = gn->next; gn->next = rev; rev = gn; } return rev; } <file_sep>/archive_s3/s3/src/libmisc/corpus.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * corpus.h -- Corpus-file related misc functions. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 25-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #ifndef _LIBMISC_CORPUS_H_ #define _LIBMISC_CORPUS_H_ #include <libutil/libutil.h> /* * Structure for a corpus: essentially a set of strings each associated with a * unique ID. (Such as a reference sentence file, hypothesis file, and various * control files.) */ typedef struct { hash_t ht; /* Hash table for IDs */ int32 n; /* #IDs (and corresponding argument strings) in the corpus */ char **str; /* The argument strings */ } corpus_t; /* * Load a corpus from the given file and return it. * Each line is a separate entry in the corpus. Blank lines and lines beginning with a * hash character (#) are skipped. The ID is the FIRST word in a line. * Return value: Ptr to corpus if successfully loaded (FATAL_ERROR if any error). */ corpus_t *corpus_load_headid (char *file); /* * Similar to corpus_load_headid, but the ID is at the END of each line, in parentheses. */ corpus_t *corpus_load_tailid (char *file); /* * Lookup the given corpus for the given ID and return the associated string. * Return NULL if ID not found. */ char *corpus_lookup (corpus_t *corp, char *id); #endif <file_sep>/archive_s3/s3.0/src/libutil/libutil.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * libutil.h -- Collection of all other .h files in this directory; for brevity * * * HISTORY * * 08-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon * Added SLEEP_SEC macro. * * 08-31-95 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #ifndef _LIBUTIL_LIBUTIL_H_ #define _LIBUTIL_LIBUTIL_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #if (_SUN4 || ALPHA_OSF1) #include <unistd.h> #endif #include <math.h> #include "prim_type.h" #include "bitvec.h" #include "case.h" #include "ckd_alloc.h" #include "cmd_ln.h" #include "err.h" #include "filename.h" #include "glist.h" #include "hash.h" #include "heap.h" #include "io.h" #include "profile.h" #include "str2words.h" #include "unlimit.h" #if (WIN32) #define SLEEP_SEC(sec) (0) /* Why doesn't Sleep((sec)*1000) work? */ #else #define SLEEP_SEC(sec) sleep(sec) /* sec must be integer */ #endif #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifndef M_PI #define M_PI 3.1415926535897932385 /* For the pain-in-the-neck Win32 */ #endif #define PI M_PI #endif <file_sep>/SphinxTrain/src/programs/make_quests/main.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * Clusters CI distributions using a hybrid bottom-up top-down * clustering algorithm to build linguistic questions for * decision trees. * * Author: <NAME> *********************************************************************/ /* * * $Log$ * Revision 1.11 2005/07/09 03:13:03 arthchan2003 * Fix keyword expansion probelm * * Revision 1.10 2005/07/09 03:09:47 arthchan2003 * Fixed typos in error message, added initialization for the variable continuous such that gcc is happy. * * Revision 1.9 2005/07/09 03:02:10 arthchan2003 * 1, Remove tempfn and anything the used tempfn. It is never used in * the entire SphinxTrain codebase. 2, change the example such that * -tempfn is removed but -type .cont. is added. 3, Did **not** * removed -tempfn because some users might just update the code but * not the perl script. This keep backward compatibility (but it is * definitely stupid). 4, Change the perl script as well. People who * update the code and script will then learn the correct usage. 5, * Check type such that if it is not .cont. or .semi., nothing stupid * will happen. (Well, in general, it is a sin for us to release this * program. *sigh*) * Revision 1.8 2005/07/09 02:31:47 arthchan2003 1, When user forgot * to specify -type, make_quest.c failed to check whether type is * valid, when passed as an argument to strcpy, strcpy will cause seg * core. Resolved it by explicitly adding a checking and prompting * user to specify it correctly. 2, Also added keyword for all .c * files. */ #include <math.h> #include "parse_cmd_ln.h" #include <s3/model_def_io.h> #include <s3/s3mixw_io.h> #include <s3/metric.h> #include <s3/div.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/vector.h> #include <s3/s3gau_io.h> #include <s3/gauden.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define IS_LEAF(X) ((X != NULL) && (X->left==NULL && X->right==NULL)) #define IS_TWIG(X) ((X != NULL) && (IS_LEAF(X->left)&&IS_LEAF(X->right))) #define IS_QUEST(X) ((X->depth > 0) && ((X->nphones > 1) || (X->depth <= 3))) typedef struct node_str {int32 nphones; int32 *phoneids; int32 depth; int32 id; float32 lkhd_dec; struct node_str *left; struct node_str *right; } node; int compare(); char *type; float32 likelhddec(float32 *meana, float32 *vara, float32 *meanb, float32 *varb, float32 **cnta, float32 **cntb, int32 ndensity, int32 nfeat, int32 dim) { int32 i, continuous; float32 cntc, la, lb, lc, nm, nv, lkdec, minvar; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; if (continuous) { minvar = *(float32 *)cmd_ln_access("-varfloor"); cntc = cnta[0][0] + cntb[0][0]; for (i=0, lc=0, lb=0, la=0;i<dim;i++){ nm = (cnta[0][0]*meana[i] + cntb[0][0]*meanb[i])/cntc; nv = cnta[0][0]*(vara[i]+meana[i]*meana[i])+ cntb[0][0]*(varb[i]+meanb[i]*meanb[i]); nv = nv/cntc - nm*nm; if (nv < minvar) nv = minvar; lc += (float32)log(nv); lb += (float32)log(varb[i]); la += (float32)log(vara[i]); } lkdec = 0.5*(cntc*lc - cntb[0][0]*lb - cnta[0][0]*la); } else { int32 j; float32 P,Q; for (i=0,lkdec = 0; i < nfeat; i++) { for (j=0,P=0,Q=0; j < ndensity; j++) { P += cnta[i][j]; Q += cntb[i][j]; lkdec += ((cnta[i][j]==0) ? 0 : cnta[i][j]*log(cnta[i][j])) + ((cntb[i][j]==0) ? 0 : cntb[i][j]*log(cntb[i][j])) - (((cnta[i][j]+cntb[i][j])==0) ? 0 : (cnta[i][j]+cntb[i][j])*log(cnta[i][j]+cntb[i][j])); } lkdec -= ((P==0) ? 0 : (P*log(P))) + ((Q==0) ? 0 : (Q*log(Q))) - (((P+Q)==0) ? 0 : ((P+Q)*log(P+Q))); } #if 0 /* The old code, assumed log(0) would give a reasonable answer */ for (i=0,lkdec = 0; i < nfeat; i++) { for (j=0,P=0,Q=0; j < ndensity; j++) { P += cnta[i][j]; Q += cntb[i][j]; lkdec += cnta[i][j]*log(cnta[i][j]) + cntb[i][j]*log(cntb[i][j]) -(cnta[i][j]+cntb[i][j])*log(cnta[i][j]+cntb[i][j]); } lkdec -= P*log(P) + Q*log(Q) - (P+Q)*log(P+Q); } #endif } return(lkdec); } /* Find the two closest distributions. We assume 1 gaussian/state */ int32 findclosestpair(float32 **pmeans, float32 **pvars, float32 ***pmixw, int32 nsets, int32 ndensity, int32 nfeat, int32 dim, int32 *a, int32 *b) { float32 reduction, minreduction; int32 i, j, la=0, lb=0, continuous; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; minreduction = 1.0e+32; for (i=0; i<nsets; i++){ for (j=i+1;j<nsets;j++){ if (i != j){ if (continuous) { reduction = likelhddec(pmeans[i],pvars[i], pmeans[j],pvars[j], pmixw[i],pmixw[j], ndensity,nfeat,dim); } else { reduction = likelhddec(NULL,NULL, NULL,NULL, pmixw[i],pmixw[j], ndensity,nfeat,dim); } if (reduction < minreduction){ minreduction = reduction; la = i; lb = j; } } } } *a = la; *b = lb; return 0; } /* Permute a list of elements (here groups of phones) to obtain the best partitioning of the elements into two groups */ float32 permute(float32 **means, float32 **vars, float32 ***mixw, int32 ndensity, int32 nfeat, int32 dim, int32 **lists, int32 *llists, int32 npermute, int32 **lclass, int32 **rclass, int32 *nlclass, int32 *nrclass) { float32 **tmean=NULL, **tvar=NULL, ***tmixw=NULL; float32 bestdec,reduction,cnt; int32 i,j,k,l,m,n,ncombinations,bestclust=0,continuous; char **identifier, *tmpid; int32 *llclass,*lrclass,lnlclass,lnrclass,ntot; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; /* First gather and compute means and variances for the npermute groups */ tmixw = (float32 ***)ckd_calloc_3d(npermute,nfeat,ndensity,sizeof(float32)); if (continuous) { tmean = (float32 **) ckd_calloc_2d(npermute,dim,sizeof(float32)); tvar = (float32 **) ckd_calloc_2d(npermute,dim,sizeof(float32)); } for (i=0;i<npermute;i++) { for (j=0;j<llists[i];j++) { l = lists[i][j]; if (continuous) { cnt = mixw[l][0][0]; tmixw[i][0][0] += cnt; for (k=0;k<dim;k++){ tmean[i][k] += cnt*means[l][k]; tvar[i][k] += cnt*(vars[l][k] + means[l][k]*means[l][k]); } } else { for (m=0;m<nfeat;m++) for (n=0;n<ndensity;n++) tmixw[i][m][n] += mixw[l][m][n]; } } if (continuous) { for (k=0;k<dim;k++){ tmean[i][k] /= tmixw[i][0][0]; tvar[i][k] = tvar[i][k]/tmixw[i][0][0]-tmean[i][k]*tmean[i][k]; } } } /* We have npermute clusters now; permute them to get two clusters */ /* There are 2^(npermute-1)-1 clusters possible. Test them all out */ /* Create identifiers for 2^(npermute-1) clusters */ for (i=1,ncombinations=1;i<npermute;i++,ncombinations*=2); identifier = (char **)ckd_calloc_2d(ncombinations,npermute,sizeof(char)); tmpid = (char *)ckd_calloc(npermute,sizeof(char)); for (i=0;i<ncombinations-1;i++){ for(j=0,tmpid[0]=!tmpid[0];!tmpid[j];j++,tmpid[j]=!tmpid[j]); for(j=0;j<npermute;j++) identifier[i][j] = tmpid[j]; } ckd_free(tmpid); /* Go through the list and find best pair */ for (i=0,bestdec=-1.0e+30;i<ncombinations-1;i++){ float32 *meana=NULL, *vara=NULL, *meanb=NULL; float32 *varb=NULL, **counta=NULL, **countb=NULL; counta = (float32 **) ckd_calloc_2d(nfeat,ndensity,sizeof(float32)); countb = (float32 **) ckd_calloc_2d(nfeat,ndensity,sizeof(float32)); if (continuous) { meana = (float32 *)ckd_calloc(dim,sizeof(float32)); vara = (float32 *)ckd_calloc(dim,sizeof(float32)); meanb = (float32 *)ckd_calloc(dim,sizeof(float32)); varb = (float32 *)ckd_calloc(dim,sizeof(float32)); for (j=0;j<npermute;j++){ float32 *om = tmean[j]; float32 *ov = tvar[j]; cnt = tmixw[j][0][0]; if (identifier[i][j]){ counta[0][0] += cnt; for (k=0;k<dim;k++){ meana[k] += cnt * om[k]; vara[k] += cnt*(ov[k] + om[k]*om[k]); } } else{ countb[0][0] += cnt; for (k=0;k<dim;k++){ meanb[k] += cnt * om[k]; varb[k] += cnt*(ov[k] + om[k]*om[k]); } } } for (k=0;k<dim;k++){ meana[k] /= counta[0][0]; meanb[k] /= countb[0][0]; vara[k] = vara[k]/counta[0][0] - meana[k]*meana[k]; varb[k] = varb[k]/countb[0][0] - meanb[k]*meanb[k]; } } else { for (j=0;j<npermute;j++){ if (identifier[i][j]){ for (m=0;m<nfeat;m++) for (n=0; n<ndensity; n++) counta[m][n] += tmixw[j][m][n]; } else { for (m=0;m<nfeat;m++) for (n=0; n<ndensity; n++) countb[m][n] += tmixw[j][m][n]; } } } reduction = likelhddec(meana,vara, meanb,varb,counta,countb, ndensity,nfeat,dim); if (reduction > bestdec) { bestdec = reduction; bestclust = i; } if (continuous) { ckd_free(meana);ckd_free(vara);ckd_free(meanb);ckd_free(varb); } ckd_free_2d((void **)counta); ckd_free_2d((void **)countb); } for (i=0,ntot=0;i<npermute;i++) ntot += llists[i]; llclass = (int32 *) ckd_calloc(ntot,sizeof(int32)); /* Overalloc */ lrclass = (int32 *) ckd_calloc(ntot,sizeof(int32)); /* Overalloc */ for (j=0,lnlclass=0,lnrclass=0;j<npermute;j++){ if (identifier[bestclust][j]){ for (l=0;l<llists[j];l++,lnlclass++) llclass[lnlclass] = lists[j][l]; } else { for (l=0;l<llists[j];l++,lnrclass++) lrclass[lnrclass] = lists[j][l]; } } *lclass = llclass; *rclass = lrclass; *nlclass = lnlclass; *nrclass = lnrclass; if (continuous) { ckd_free_2d((void **)tmean); ckd_free_2d((void **)tvar); } ckd_free_3d((void ***)tmixw); ckd_free_2d((void **)identifier); return(bestdec); } node *make_simple_tree (float32 **means, float32 **vars, float32 ***mixw, int32 *nodephoneids, int32 nphones, int32 ndensity, int32 nfeat, int32 ndim, int32 npermute, int32 depth) { float32 **oldmeans=NULL, **oldvars=NULL, **newmeans=NULL, **newvars=NULL; float32 ***oldmixw, ***newmixw, **tmp2d, ***tmp3d; float32 minvar=0, bestdec; int32 **phoneid, **newphoneid, *numphones, *newnumphones, **it2d, *it1d; int32 i,j,k,l,a,b,set,nsets; int32 *lphoneids,*rphoneids,lnphones,rnphones,continuous; node *root; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; /* Allocate and set basic root parameters */ root = (node *) ckd_calloc(1,sizeof(node)); root->phoneids = (int32 *) ckd_calloc(nphones,sizeof(int32)); root->nphones = nphones; memcpy(root->phoneids,nodephoneids,nphones*sizeof(int32)); root->depth = depth; /* Build the node by clustering and partitioning */ oldmixw = (float32***)ckd_calloc_3d(nphones,nfeat,ndensity,sizeof(float32)); newmixw = (float32***)ckd_calloc_3d(nphones,nfeat,ndensity,sizeof(float32)); phoneid = (int32 **)ckd_calloc_2d(nphones,nphones,sizeof(int32)); numphones = (int32 *) ckd_calloc(nphones,sizeof(int32)); newphoneid = (int32 **)ckd_calloc_2d(nphones,nphones,sizeof(int32)); newnumphones = (int32 *) ckd_calloc(nphones,sizeof(int32)); if (continuous) { minvar = *(float32 *)cmd_ln_access("-varfloor"); oldmeans = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); oldvars = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); newmeans = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); newvars = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); } for (i=0;i<nphones;i++){ numphones[i] = 1; phoneid[i][0] = nodephoneids[i]; /* Phone ids */ for (j=0;j<nfeat;j++) for (k=0;k<ndensity;k++) oldmixw[i][j][k] = mixw[nodephoneids[i]][j][k]; if (continuous) { for (l=0;l<ndim;l++){ oldmeans[i][l] = means[nodephoneids[i]][l]; oldvars[i][l] = vars[nodephoneids[i]][l]; } } } if (nphones > npermute){ for (nsets = nphones; nsets > npermute; nsets--) { /* Find the closest distributions */ findclosestpair(oldmeans,oldvars,oldmixw,nsets,ndensity, nfeat,ndim,&a,&b); /* Copy and Merge distributions... */ /* Copy unmerged distributions first */ for (i=0,set=0;i<nsets;i++){ if (i != a && i != b){ newnumphones[set] = numphones[i]; for (l=0;l<numphones[i];l++) newphoneid[set][l] = phoneid[i][l]; for (j=0;j<nfeat;j++) for (k=0;k<ndensity;k++) newmixw[set][j][k] = oldmixw[i][j][k]; if (continuous) { for (l=0;l<ndim;l++){ newmeans[set][l] = oldmeans[i][l]; newvars[set][l] = oldvars[i][l]; } } set++; } } /* Merge a and b */ newnumphones[set] = numphones[a]+numphones[b]; for (i=0;i<numphones[a];i++) newphoneid[set][i] = phoneid[a][i]; for (l=0;l<numphones[b];l++,i++) newphoneid[set][i] = phoneid[b][l]; if (continuous) { float32 *nm = newmeans[set]; float32 *nv = newvars[set]; float32 *oma = oldmeans[a]; float32 *ova = oldvars[a]; float32 *omb = oldmeans[b]; float32 *ovb = oldvars[b]; float32 cnta, cntb; cnta = oldmixw[a][0][0]; cntb = oldmixw[b][0][0]; newmixw[set][0][0] = cnta + cntb; for (l=0;l<ndim;l++){ nm[l] = (cnta*oma[l] + cntb*omb[l]) / (cnta + cntb); nv[l] = cnta*(ova[l]+oma[l]*oma[l]) + cntb*(ovb[l]+omb[l]*omb[l]); nv[l] = nv[l]/(cnta+cntb) - nm[l]*nm[l]; if (nv[l] < minvar) nv[l] = minvar; } } else { for (j=0;j<nfeat;j++) for (k=0;k<ndensity;k++) newmixw[set][j][k] = oldmixw[a][j][k]+oldmixw[b][j][k]; } /* Switch old and new variables */ tmp2d = oldmeans; oldmeans = newmeans; newmeans = tmp2d; tmp2d = oldvars; oldvars = newvars; newvars = tmp2d; tmp3d = oldmixw; oldmixw = newmixw; newmixw = tmp3d; it2d = phoneid; phoneid = newphoneid; newphoneid = it2d; it1d = numphones; numphones = newnumphones; newnumphones = it1d; } } else npermute = nphones; if (nphones < 2){ root->left = root->right = NULL; /* Dont split further */ return(root); } bestdec = permute(means,vars,mixw,ndensity,nfeat,ndim,phoneid,numphones, npermute,&lphoneids,&rphoneids,&lnphones,&rnphones); root->lkhd_dec = bestdec; if (continuous) { ckd_free_2d((void **)oldmeans); ckd_free_2d((void **)oldvars); ckd_free_2d((void **)newmeans); ckd_free_2d((void **)newvars); } ckd_free_3d((void ***)oldmixw); ckd_free_3d((void ***)newmixw); ckd_free_2d((void **)newphoneid); ckd_free_2d((void **)phoneid); /* Recurse */ root->left = make_simple_tree(means,vars,mixw,lphoneids,lnphones, ndensity,nfeat,ndim,npermute,root->depth+1); root->right = make_simple_tree(means,vars,mixw,rphoneids,rnphones, ndensity,nfeat,ndim,npermute,root->depth+1); return(root); } /* Associates a unique id with all the nodes in a tree */ int32 id_nodes(node *root, node **idlist, int32 id) { if (root->left != NULL) id = id_nodes(root->left,idlist,id); if (root->right != NULL) id = id_nodes(root->right,idlist,id); root->id = id; idlist[id] = root; return(id+1); } void free_tree(node *root) { if (root->left != NULL) free_tree(root->left); if (root->right != NULL) free_tree(root->right); ckd_free((void *) root->phoneids); ckd_free((void *) root); return; } /* Pares a tree down to npermute leaves */ int32 pare_tree(node *sroot, int32 npermute, int32 **lists, int32 *llist) { float32 *twiglkhddec,maxdec; int32 *leaflist, nleaves, *twiglist, ntwigs; int32 nnodes,i,maxid; node **idlist; /* Overallocate idlist */ idlist = (node **) ckd_calloc(1024,sizeof(node *)); /* First "id" all the nodes */ nnodes = id_nodes(sroot,idlist,0); /* Allocate lists (overallocate for safety margin) */ leaflist = (int32 *) ckd_calloc(nnodes,sizeof(int32)); twiglist = (int32 *) ckd_calloc(nnodes,sizeof(int32)); twiglkhddec = (float32 *) ckd_calloc(nnodes,sizeof(float32)); nleaves = ntwigs = 0; for(i=0;i<nnodes;i++) { if (IS_LEAF(idlist[i])) leaflist[nleaves++] = i; else if (IS_TWIG(idlist[i])) { twiglist[ntwigs] = i; twiglkhddec[ntwigs++] = (idlist[i])->lkhd_dec; } } while (nleaves > npermute) { /* find twig for which likelihood decerase was maximum * this is the worst merge */ maxdec = twiglkhddec[0]; maxid = twiglist[0]; for (i=1; i<ntwigs;i++) { if (twiglkhddec[i] > maxdec) { maxdec = twiglkhddec[i]; maxid = twiglist[i]; } } /* remove children of twig, make twig a leaf, eliminate if from the node list, and continue */ idlist[idlist[maxid]->left->id] = NULL; idlist[idlist[maxid]->right->id] = NULL; free_tree(idlist[maxid]->left); free_tree(idlist[maxid]->right); idlist[maxid]->left = idlist[maxid]->right = NULL; nleaves = ntwigs = 0; for(i=0;i<nnodes;i++) { if (IS_LEAF(idlist[i])) leaflist[nleaves++] = i; else if (IS_TWIG(idlist[i])) { twiglist[ntwigs] = i; twiglkhddec[ntwigs++] = (idlist[i])->lkhd_dec; } } } for (i=0;i<nleaves;i++) { llist[i] = idlist[leaflist[i]]->nphones; memcpy(lists[i],idlist[leaflist[i]]->phoneids,sizeof(int32)*llist[i]); } ckd_free(idlist); ckd_free(leaflist); ckd_free(twiglist); ckd_free(twiglkhddec); return(nleaves); } /* Prunes a tree down to nnode question nodes */ int32 prune_quests(node *sroot, int32 ndesirdnodes) { float32 *twiglkhddec,maxdec; int32 *leaflist, nquests, nleaves, *twiglist, ntwigs; int32 nnodes,i,maxid; node **idlist; /* Ignore root node == preincrement ndesirdnodes */ ndesirdnodes++; /* Overallocate idlist */ idlist = (node **) ckd_calloc(1024,sizeof(node *)); /* First "id" all the nodes */ nnodes = id_nodes(sroot,idlist,0); /* Allocate lists (overallocate for safety margin) */ leaflist = (int32 *) ckd_calloc(nnodes,sizeof(int32)); twiglist = (int32 *) ckd_calloc(nnodes,sizeof(int32)); twiglkhddec = (float32 *) ckd_calloc(nnodes,sizeof(float32)); nleaves = ntwigs = nquests = 0; for(i=0;i<nnodes;i++) { if (IS_QUEST(idlist[i])) nquests++; if (IS_LEAF(idlist[i])) leaflist[nleaves++] = i; else if (IS_TWIG(idlist[i])) { twiglist[ntwigs] = i; twiglkhddec[ntwigs++] = (idlist[i])->lkhd_dec; } } while (nquests > ndesirdnodes) { /* find twig for which likelihood decerase was maximum */ maxdec = twiglkhddec[0]; maxid = twiglist[0]; for (i=1; i<ntwigs;i++) { if (twiglkhddec[i] > maxdec) { maxdec = twiglkhddec[i]; maxid = twiglist[i]; } } /* remove children of twig, make twig a leaf, eliminate it from the node list, and continue */ free_tree(idlist[maxid]->left); free_tree(idlist[maxid]->right); idlist[maxid]->left = idlist[maxid]->right = NULL; ckd_free(idlist); idlist = (node **) ckd_calloc(1024,sizeof(node *)); nnodes = id_nodes(sroot,idlist,0); nleaves = ntwigs = nquests = 0; for(i=0;i<nnodes;i++) { if (IS_QUEST(idlist[i])) nquests++; if (IS_LEAF(idlist[i])) leaflist[nleaves++] = i; else if (IS_TWIG(idlist[i])) { twiglist[ntwigs] = i; twiglkhddec[ntwigs++] = (idlist[i])->lkhd_dec; } } } ckd_free(idlist); ckd_free(leaflist); ckd_free(twiglist); ckd_free(twiglkhddec); return(nquests); } node *make_tree (float32 **means, float32 **vars, float32 ***mixw, int32 *phnids, int32 nphones, int32 ndensity, int32 nfeat, int32 dim, int32 npermute, int32 depth) { float32 lkhddec; int32 niter,iter,jpermute, **lists, *llists; int32 *lclass, nlclass, *rclass, nrclass,continuous; node *sroot; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; niter = *(int32 *) cmd_ln_access("-niter"); sroot = make_simple_tree(means,vars,mixw,phnids,nphones,ndensity,nfeat,dim,npermute,depth); for (iter = 0; iter < niter; iter++) { /* overallocate lists of lists */ lists = (int32 **) ckd_calloc_2d(npermute,nphones,sizeof(int32)); llists = (int32 *) ckd_calloc(npermute,sizeof(int32)); jpermute = pare_tree(sroot,npermute,lists,llists); if (jpermute > 1){ lkhddec = permute(means,vars,mixw,ndensity,nfeat,dim,lists,llists, jpermute,&lclass,&rclass,&nlclass,&nrclass); free_tree(sroot->left); free_tree(sroot->right); sroot->lkhd_dec = lkhddec; sroot->left = make_tree(means,vars,mixw,lclass,nlclass,ndensity,nfeat, dim,npermute,depth+1); sroot->right = make_tree(means,vars,mixw,rclass,nrclass,ndensity,nfeat, dim,npermute,depth+1); } else { sroot->left = sroot->right = NULL; } ckd_free_2d((void **)lists); ckd_free(llists); } return(sroot); } int32 get_quests(node *root,int32 **qarr,int32 *nph,int32 nquests,int32 depth) { int32 *sortedidx,i; if (root->nphones < 2 && depth > 3) return nquests; if (depth > 0){ sortedidx = (int32 *)ckd_calloc(root->nphones,sizeof(int32)); for (i=0;i<root->nphones;i++) sortedidx[i] = root->phoneids[i]; qsort(sortedidx,root->nphones,sizeof(int32),compare); nph[nquests] = root->nphones; qarr[nquests++] = sortedidx; } if (root->nphones < 2) return nquests; if (root->left != NULL) nquests = get_quests(root->left,qarr,nph,nquests,depth+1); if (root->right != NULL) nquests = get_quests(root->right,qarr,nph,nquests,depth+1); return nquests; } int compare(int *i, int *j) { if (*i > *j) return 1; if (*j > *i) return -1; return 0; } void sort_quests(int32 **qarr, int32 *nqfone, uint32 nfone, int32 *nquests) { int32 i, j, k; int32 *marker, *flag; marker = (int32 *) ckd_calloc(*nquests,sizeof(int32)); for (i=0;i<*nquests;i++){ for (j=i+1; j < *nquests; j++){ if (nqfone[i]+nqfone[j] != nfone) continue; flag = (int32 *) ckd_calloc(nfone,sizeof(int32)); for (k=0;k < nqfone[i];k++) flag[qarr[i][k]] = 1; for (k=0;k < nqfone[j];k++) flag[qarr[j][k]] = 1; for (k=0;k < nfone;k++) if (flag[k] == 0) break; if (k == nfone) { /* the two questions are complements */ if (nqfone[i] > nqfone[j]) marker [i] = 1; else marker[j] = 1; } ckd_free((void *)flag); } } for (i=0,j=0;i<*nquests;i++){ if (marker[i] == 1) { ckd_free((void *)qarr[i]); continue; } qarr[j] = qarr[i]; nqfone[j] = nqfone[i]; j++; } *nquests = j; ckd_free((void *) marker); } static int init(float32 *****out_mixw, float32 ****out_mean, float32 ****out_var, uint32 *out_veclen, uint32 *out_n_model, uint32 *out_n_state, uint32 *out_n_feat, uint32 *out_n_density, char ***out_phone) { const char *moddeffn; const char *mixwfn; model_def_t *mdef; uint32 p_s = NO_ID, p_e = NO_ID, s, m, n_ci, id; uint32 mixw_s, mixw_e; float32 ****mixw=0; float32 ****mixw_occ=0; float32 ***in_mixw; uint32 n_state, n_model, n_in_mixw, n_stream, n_density; uint32 i, j, k; float64 dnom; const uint32 *l_veclen, *t_veclen; uint32 l_nstates, t_nstates; uint32 t_nfeat, t_ndensity; vector_t ***fullmean=NULL; vector_t ***fullvar=NULL; vector_t ****fullvar_full=NULL; float32 ***mean=NULL; float32 ***var=NULL; float32 varfloor; uint32 ll=0,n,nn,sumveclen,continuous; char **phone; if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; moddeffn = cmd_ln_access("-moddeffn"); if (moddeffn == NULL) E_FATAL("Specify -moddeffn\n"); E_INFO("Reading: %s\n", moddeffn); if (model_def_read(&mdef, moddeffn) != S3_SUCCESS) return S3_ERROR; n_ci = mdef->acmod_set->n_ci; p_s = 0; p_e = n_ci - 1; phone = (char **) ckd_calloc_2d(n_ci,100,sizeof(char)); for (id = 0;id < n_ci;id++) strcpy(phone[id],acmod_set_id2name(mdef->acmod_set,id)); *out_phone = phone; /* Find first and last mixing weight used for p_s through p_e */ mixw_s = mdef->defn[0].state[0]; mixw_e = mdef->defn[p_e].state[mdef->defn[p_e].n_state-2]; mixwfn = cmd_ln_access("-mixwfn"); if (mixwfn == NULL) E_FATAL("Specify -mixwfn\n"); E_INFO("Reading: %s\n", mixwfn); if (s3mixw_read(mixwfn, &in_mixw, &n_in_mixw, &n_stream, &n_density) != S3_SUCCESS) return S3_ERROR; n_model = n_ci; n_state = mdef->defn[p_s].n_state - 1; *out_n_feat = n_stream; *out_n_state = n_state; *out_n_density = n_density; for (i = p_s+1; i <= p_e; i++) { if ((mdef->defn[i].n_state - 1) != n_state) { E_FATAL("Models do not have uniform topology\n"); } } /* * Build the 4D array: * * mixw[0..n_model-1][0..n_state-1][0..n_feat-1][0..n_density-1] * * out of the usual mixw[][][] array * */ mixw_occ = (float32 ****)ckd_calloc_2d(n_model, n_state, sizeof(float32 **)); *out_mixw = mixw; /* Re-index mixing weights by model and topological state position */ for (i = p_s, j = 0; i <= p_e; i++, j++) { for (k = 0; k < n_state; k++) { s = mdef->defn[i].state[k] - mixw_s; mixw_occ[j][k] = in_mixw[s]; } } assert(j == n_model); if (continuous) { /* bother with means and variances only if not semi*/ int32 var_is_full = cmd_ln_int32("-fullvar"); /* Read Means and Variances; perform consistency checks */ if (s3gau_read(cmd_ln_access("-meanfn"), &fullmean, &l_nstates, &t_nfeat, &t_ndensity, &l_veclen) != S3_SUCCESS) E_FATAL("Error reading mean file %s\n",cmd_ln_access("-meanfn")); *out_veclen = (uint32)l_veclen[0]; if (t_nfeat != n_stream && t_ndensity != n_density) E_FATAL("Mismatch between Mean and Mixture weight files\n"); if (var_is_full) { if (s3gau_read_full(cmd_ln_access("-varfn"), &fullvar_full, &t_nstates, &t_nfeat, &t_ndensity, &t_veclen) != S3_SUCCESS) E_FATAL("Error reading var file %s\n",cmd_ln_access("-varfn")); } else { if (s3gau_read(cmd_ln_access("-varfn"), &fullvar, &t_nstates, &t_nfeat, &t_ndensity, &t_veclen) != S3_SUCCESS) E_FATAL("Error reading var file %s\n",cmd_ln_access("-varfn")); } if (t_nfeat != n_stream && t_ndensity != n_density) E_FATAL("Mismatch between Variance and Mixture weight files\n"); for (i=0;i<n_stream;i++) if (t_veclen[i] != l_veclen[i]) E_FATAL("Feature length %d in var file != %d in mean file for feature %d\n",t_veclen[i],l_veclen[i],i); if (l_nstates != t_nstates) E_FATAL("Total no. of states %d in var file != %d in mean file\n",t_nstates,l_nstates); if (t_nfeat > 1) E_FATAL("N-Feat = %d! N-Feat > 1 not implemented yet..\n",t_nfeat); if (t_ndensity > 1) E_WARN("The state distributions given have %d gaussians per state;\n..*..shrinking them down to 1 gau per state..\n",t_ndensity); /* Allocate for out_mean and out_var. If input are multi_gaussian distributions convert to single gaussians. Copy appropriate states to out_mean and out_var */ for (i=0,sumveclen=0; i < n_stream; i++) sumveclen += t_veclen[i]; mean = (float32 ***)ckd_calloc_3d(n_model,n_state,sumveclen,sizeof(float32)); /* Use only the diagonals regardless of whether -varfn is full. */ var = (float32 ***)ckd_calloc_3d(n_model,n_state,sumveclen,sizeof(float32)); mixw = (float32 ****)ckd_calloc_4d(n_model,n_state,1,1,sizeof(float32)); varfloor = *(float32 *)cmd_ln_access("-varfloor"); for (i = p_s, j = 0, m = mixw_s; i <= p_e; i++, j++) { for (k = 0; k < n_state; k++, m++) { float32 *featmean=NULL,*featvar=NULL; featmean = mean[j][k]; featvar = var[j][k]; dnom = 0; for (n = 0; n < n_density; n++) { float32 mw = mixw_occ[j][k][0][n]; dnom += mw; for (nn = 0; nn < l_veclen[0]; nn++) { featmean[nn] += mw * fullmean[m][0][n][nn]; if (var_is_full) featvar[nn] += mw *(fullmean[m][0][n][nn]*fullmean[m][0][n][nn] + fullvar_full[m][0][n][nn][nn]); else featvar[nn] += mw *(fullmean[m][0][n][nn]*fullmean[m][0][n][nn] + fullvar[m][0][n][nn]); } } if (dnom != 0) { for (nn = 0; nn < l_veclen[0]; nn++) { featmean[nn] /= dnom; featvar[nn] = featvar[nn]/dnom - featmean[nn]*featmean[nn]; if (featvar[nn] < varfloor) featvar[nn] = varfloor; } } else { for (nn = 0; nn < l_veclen[0]; nn++) { if (featmean[nn] != 0) E_FATAL("dnom = 0, but featmean[nn] != 0, = %f for ll = %d\n",featmean[nn],ll); } } /* Now on we need only have global counts for the mixws, so we store them all in mixw_occ[][] */ mixw[j][k][0][0] = dnom; } } for (i=0,j=0;i<n_ci;i++){ if (strstr(phone[i],"+") == NULL && strcmp(phone[i],"SIL") != 0){ strcpy(phone[j],phone[i]); for (k=0;k<n_state;k++){ mixw[j][k][0][0] = mixw[i][k][0][0]; for (n=0;n<l_veclen[0];n++){ mean[j][k][n] = mean[i][k][n]; var[j][k][n] = var[i][k][n]; } } j++; } } n_model = j; *out_n_feat = *out_n_density = 1; } else { int32 l; mixw = (float32 ****)ckd_calloc_4d(n_model,n_state,n_stream,n_density,sizeof(float32)); for (i=0,j=0;i<n_ci;i++){ if (strstr(phone[i],"+") == NULL && strcmp(phone[i],"SIL") != 0){ strcpy(phone[j],phone[i]); for (k=0;k<n_state;k++){ for (l=0;l<n_stream;l++){ for (m=0;m<n_density;m++) mixw[j][k][l][m] = mixw_occ[i][k][l][m]; } } j++; } } n_model = j; } *out_n_model = n_model; *out_mean = mean; *out_var = var; *out_mixw = mixw; if (continuous) { ckd_free_4d((void ****)fullmean); if (fullvar) ckd_free_4d((void ****)fullvar); if (fullvar_full) gauden_free_param_full(fullvar_full); } return S3_SUCCESS; } int main(int argc, char *argv[]) { float32 ****mixw,***lmixw; float32 ***means=NULL, **lmeans=NULL; float32 ***vars=NULL, **lvars=NULL; uint32 veclen; uint32 n_model; uint32 n_state; uint32 n_feat; uint32 n_density; uint32 state; uint32 npermute, nquests_per_state; int32 i,j,k,continuous, **questarr, *nquestphone, nquests=0; int32 *phoneids,nphones; char **phone_list; char *outfile; node *root; FILE *fp; parse_cmd_ln(argc, argv); type = (char *)cmd_ln_access("-type"); if(type==NULL){ E_FATAL("-type is empty. Please specify -type correctly, either \".cont.\" or \".semi.\"\n"); } continuous = -1; if (strcmp(type,".cont.") == 0) continuous = 1; else if (strcmp(type,".semi.") == 0) continuous = 0; else{ E_FATAL("Unknown type %s, either \".cont.\" or \".semi.\"\n", type); } if(continuous ==-1){ E_FATAL("-type is not set correctly\n"); } outfile = (char *) cmd_ln_access("-questfn"); npermute = *(int32 *) cmd_ln_access("-npermute"); nquests_per_state = *(int32 *) cmd_ln_access("-qstperstt"); /* Test and cleanup outfile */ if ((fp = fopen(outfile,"w")) == NULL) E_FATAL("Unable to open %s for writing!\n",outfile); fprintf(fp,"WDBNDRY_B\nWDBNDRY_E\nWDBNDRY_S\nWDBNDRY_I\nSILENCE SIL\n"); fclose(fp); if (init(&mixw, &means, &vars, &veclen, &n_model, &n_state, &n_feat, &n_density, &phone_list) != S3_SUCCESS) { E_FATAL("Initialization failed\n"); } for (state = 0; state < n_state; state++){ phoneids = (int32 *) ckd_calloc(n_model,sizeof(int32)); root = (node *) ckd_calloc(1,sizeof(node)); nphones = n_model; lmixw = (float32 ***)ckd_calloc_3d(n_model,n_feat,n_density,sizeof(float32)); if (continuous) { lmeans = (float32 **)ckd_calloc_2d(n_model,veclen,sizeof(float32)); lvars = (float32 **)ckd_calloc_2d(n_model,veclen,sizeof(float32)); for (i=0;i<n_model;i++){ phoneids[i] = i; lmixw[i][0][0] = mixw[i][state][0][0]; for (j=0;j<veclen;j++){ lmeans[i][j] = means[i][state][j]; lvars[i][j] = vars[i][state][j]; } } } else { for (i=0;i<n_model;i++){ phoneids[i] = i; for (j=0;j<n_feat;j++) for (k=0;k<n_density;k++) lmixw[i][j][k] = mixw[i][state][j][k]; } } root = make_tree(lmeans,lvars,lmixw,phoneids,nphones,n_density,n_feat,veclen,npermute,0); if (continuous) { ckd_free_2d((void **)lmeans); ckd_free_2d((void **)lvars); } ckd_free_3d((void ***)lmixw); ckd_free((void *)phoneids); questarr = (int32 **)ckd_calloc(n_state*n_model,sizeof(int32 *)); nquestphone = (int32 *)ckd_calloc(n_state*n_model,sizeof(int32)); prune_quests(root,nquests_per_state); nquests = get_quests(root,questarr,nquestphone,0,0); free_tree(root); fp = fopen(outfile,"a"); for (i=0;i<nquests;i++){ if (state < n_state/2) fprintf(fp,"QUESTION%d_%d_R ",state,i); else if (state == n_state/2) fprintf(fp,"QUESTION%d ",i); else fprintf(fp,"QUESTION%d_%d_L ",state,i); for (j=0;j<nquestphone[i];j++) fprintf(fp," %s",phone_list[questarr[i][j]]); fprintf(fp,"\n"); } fclose(fp); E_INFO("Done building questions using state %d\n",state); E_INFO(" %d questions from state %d\n",nquests,state); for(i=0;i<nquests;i++) ckd_free((void *)questarr[i]); ckd_free((void **)questarr); ckd_free((void *)nquestphone); } E_INFO ("Stored questions in %s\n",outfile); /* sort_quests(questarr,nquestphone,n_model,&nquests); for (i=0;i<nquests;i++){ for (j=0;j<nquestphone[i];j++) fprintf(fp," %s",phone_list[questarr[i][j]]); fprintf(fp,"\n"); } fclose(fp); */ return 0; } <file_sep>/archive_s3/s3.0/src/libmain/dict.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * dict.c -- Pronunciation dictionary. * * * HISTORY * * 23-Apr-98 <NAME> (<EMAIL>) at Carnegie Mellon University. * Made usage of mdef optional. If no mdef is specified while loading * a dictionary, it maintains the needed CI phone information internally. * Added dict_ciphone_str(). * * 02-Jul-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added startwid, finishwid, silwid to dict_t. Modified dict_filler_word * to check for start and finishwid. * * 07-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created from previous Sphinx-3 version. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "dict.h" #define DELIM " \t\n" /* Set of field separator characters */ #define DEFAULT_NUM_PHONE (MAX_CIPID+1) static s3cipid_t dict_ciphone_id (dict_t *d, char *str) { int32 id; if (d->mdef) return mdef_ciphone_id (d->mdef, str); else { if (hash_lookup (d->pht, str, &id) < 0) { id = (d->n_ciphone)++; if (id >= MAX_CIPID) E_FATAL("Too many CIphones in dictionary; increase MAX_CIPID\n"); d->ciphone_str[id] = (char *) ckd_salloc(str); if (hash_enter (d->pht, d->ciphone_str[id], id) != id) E_FATAL("hash_enter(local-phonetable, %s) failed\n", str); } return id; } } const char *dict_ciphone_str (dict_t *d, s3wid_t wid, int32 pos) { assert (d != NULL); assert ((wid >= 0) && (wid < d->n_word)); assert ((pos >= 0) && (pos < d->word[wid].pronlen)); if (d->mdef) return mdef_ciphone_str (d->mdef, d->word[wid].ciphone[pos]); else return (d->ciphone_str[d->word[wid].ciphone[pos]]); } s3wid_t dict_add_word (dict_t *d, char *word, s3cipid_t *p, int32 np) { int32 w, len; dictword_t *wordp; s3wid_t newwid; if (d->n_word >= d->max_words) { E_ERROR("Dictionary full; add(%s) failed\n", word); return (BAD_WID); } wordp = d->word + d->n_word; wordp->word = (char *) ckd_salloc (word); /* Associate word string with d->n_word in hash table */ if (hash_enter (d->ht, wordp->word, d->n_word) != d->n_word) { ckd_free (wordp->word); return (BAD_WID); } /* Fill in word entry, and set defaults */ if (p && (np > 0)) { wordp->ciphone = (s3cipid_t *) ckd_malloc (np * sizeof(s3cipid_t)); memcpy (wordp->ciphone, p, np*sizeof(s3cipid_t)); wordp->pronlen = np; } else { wordp->ciphone = NULL; wordp->pronlen = 0; } wordp->alt = BAD_WID; wordp->basewid = d->n_word; wordp->n_comp = 0; wordp->comp = NULL; /* Determine base/alt wids */ if ((len = word2basestr (word)) > 0) { /* Truncated to a baseword string; find its ID */ if (hash_lookup (d->ht, word, &w) < 0) { word[len] = '('; /* Get back the original word */ E_FATAL("Missing base word for: %s\n", word); } else word[len] = '('; /* Get back the original word */ /* Link into alt list */ wordp->basewid = w; wordp->alt = d->word[w].alt; d->word[w].alt = d->n_word; } newwid = d->n_word++; return (newwid); } static int32 dict_read (FILE *fp, dict_t *d) { char line[16384], **wptr; s3cipid_t p[4096]; int32 lineno, nwd; s3wid_t w; int32 i, maxwd; maxwd = 4092; wptr = (char **) ckd_calloc (maxwd, sizeof(char *)); lineno = 0; while (fgets (line, sizeof(line), fp) != NULL) { lineno++; if (line[0] == '#') /* Comment line */ continue; if ((nwd = str2words (line, wptr, maxwd)) < 0) E_FATAL("str2words(%s) failed; Increase maxwd from %d\n", line, maxwd); if (nwd == 0) /* Empty line */ continue; /* wptr[0] is the word-string and wptr[1..nwd-1] the pronunciation sequence */ if (nwd == 1) { E_ERROR("Line %d: No pronunciation for word %s; ignored\n", lineno, wptr[0]); continue; } /* Convert pronunciation string to CI-phone-ids */ for (i = 1; i < nwd; i++) { p[i-1] = dict_ciphone_id (d, wptr[i]); if (NOT_CIPID(p[i-1])) { E_ERROR("Line %d: Bad ciphone: %s; word %s ignored\n", lineno, wptr[i], wptr[0]); break; } } if (i == nwd) { /* All CI-phones successfully converted to IDs */ w = dict_add_word (d, wptr[0], p, nwd-1); if (NOT_WID(w)) E_ERROR("Line %d: dict_add_word (%s) failed (duplicate?); ignored\n", lineno, wptr[0]); } } ckd_free (wptr); return 0; } static s3wid_t *dict_comp_head (dict_t *d) { int32 w; s3wid_t *comp_head; comp_head = (s3wid_t *) ckd_calloc (d->n_word, sizeof(s3wid_t)); for (w = 0; w < d->n_word; w++) comp_head[w] = BAD_WID; for (w = 0; w < d->n_word; w++) { if (d->word[w].n_comp > 0) { comp_head[w] = comp_head[d->word[w].comp[0]]; comp_head[d->word[w].comp[0]] = w; } } return comp_head; } /* * Scan the dictionary for compound words. This function should be called just after * loading the dictionary. For the moment, compound words in a compound word are * assumed to be separated by the given sep character, (underscore in the CMU dict). * Return value: #compound words found in dictionary. */ static int32 dict_build_comp (dict_t *d, char sep) /* Separator character */ { char wd[4096]; int32 w, cwid; dictword_t *wordp; int32 nc; /* # compound words in dictionary */ int32 i, j, l, n; nc = 0; for (w = 0; w < d->n_word; w++) { wordp = d->word + dict_basewid(d, w); strcpy (wd, wordp->word); l = strlen(wd); if ((wd[0] == sep) || (wd[l-1] == sep)) E_FATAL("Bad compound word %s: leading or trailing separator\n", wordp->word); /* Count no. of components in this word */ n = 1; for (i = 1; i < l-1; i++) /* 0 and l-1 already checked above */ if (wd[i] == sep) n++; if (n == 1) continue; /* Not a compound word */ nc++; if ((w == d->startwid) || (w == d->finishwid) || dict_filler_word (d, w)) E_FATAL("Compound special/filler word (%s) not allowed\n", wordp->word); /* Allocate and fill in component word info */ wordp->n_comp = n; wordp->comp = (s3wid_t *) ckd_calloc (n, sizeof(s3wid_t)); /* Parse word string into components */ n = 0; for (i = 0; i < l; i++) { for (j = i; (i < l) && (wd[i] != sep); i++); if (j == i) E_FATAL("Bad compound word %s: successive separators\n", wordp->word); wd[i] = '\0'; cwid = dict_wordid (d, wd+j); if (NOT_WID(cwid)) E_FATAL("Component word %s of %s not in dictionary\n", wd+j, wordp->word); wordp->comp[n] = cwid; n++; } } if (nc > 0) d->comp_head = dict_comp_head (d); return nc; } dict_t *dict_init (mdef_t *mdef, char *dictfile, char *fillerfile, char comp_sep) { FILE *fp, *fp2; int32 n ; char line[1024]; dict_t *d; if (! dictfile) E_FATAL("No dictionary file\n"); /* * First obtain #words in dictionary (for hash table allocation). * Reason: The PC NT system doesn't like to grow memory gradually. Better to allocate * all the required memory in one go. */ if ((fp = fopen(dictfile, "r")) == NULL) E_FATAL_SYSTEM("fopen(%s,r) failed\n", dictfile); n = 0; while (fgets (line, sizeof(line), fp) != NULL) { if (line[0] != '#') n++; } rewind (fp); if (fillerfile) { if ((fp2 = fopen(fillerfile, "r")) == NULL) E_FATAL_SYSTEM("fopen(%s,r) failed\n", fillerfile); while (fgets (line, sizeof(line), fp2) != NULL) { if (line[0] != '#') n++; } rewind (fp2); } /* * Allocate dict entries. HACK!! Allow some extra entries for words not in file. * Also check for type size restrictions. */ d = (dict_t *) ckd_calloc (1, sizeof(dict_t)); d->max_words = (n+1024 < MAX_WID) ? n+1024 : MAX_WID; if (n >= MAX_WID) E_FATAL("#Words in dictionaries (%d) exceeds limit (%d)\n", n, MAX_WID); d->word = (dictword_t *) ckd_calloc (d->max_words, sizeof(dictword_t)); d->n_word = 0; d->mdef = mdef; if (mdef) { d->pht = NULL; d->ciphone_str = NULL; } else { d->pht = hash_new (DEFAULT_NUM_PHONE, 1 /* No case */); d->ciphone_str = (char **) ckd_calloc (DEFAULT_NUM_PHONE, sizeof(char *)); } d->n_ciphone = 0; /* Create new hash table for word strings; case-insensitive word strings */ d->ht = hash_new (d->max_words, 1 /* no-case */); /* Initialize with no compound words */ d->comp_head = NULL; /* Digest main dictionary file */ E_INFO("Reading main dictionary: %s\n", dictfile); dict_read (fp, d); fclose (fp); E_INFO("%d words read\n", d->n_word); /* Now the filler dictionary file, if it exists */ d->filler_start = d->n_word; if (fillerfile) { E_INFO("Reading filler dictionary: %s\n", fillerfile); dict_read (fp2, d); fclose (fp2); E_INFO("%d words read\n", d->n_word - d->filler_start); } d->filler_end = d->n_word-1; /* Initialize distinguished word-ids */ d->startwid = dict_wordid (d, START_WORD); d->finishwid = dict_wordid (d, FINISH_WORD); d->silwid = dict_wordid (d, SILENCE_WORD); if (NOT_WID(d->startwid)) E_WARN("%s not in dictionary\n", START_WORD); if (NOT_WID(d->finishwid)) E_WARN("%s not in dictionary\n", FINISH_WORD); if (NOT_WID(d->silwid)) E_WARN("%s not in dictionary\n", SILENCE_WORD); /* Identify compound words if indicated */ if (comp_sep) { E_INFO("Building compound words (separator = '%c')\n", comp_sep); n = dict_build_comp (d, comp_sep); E_INFO("%d compound words\n", n); } return d; } s3wid_t dict_wordid (dict_t *d, char *word) { int32 w; assert (d); assert (word); if (hash_lookup (d->ht, word, &w) < 0) return (BAD_WID); return ((s3wid_t) w); } s3wid_t _dict_basewid (dict_t *d, s3wid_t w) { assert (d); assert ((w >= 0) && (w < d->n_word)); return (d->word[w].basewid); } char *_dict_wordstr (dict_t *d, s3wid_t wid) { assert (d); assert (IS_WID(wid) && (wid < d->n_word)); return (d->word[wid].word); } s3wid_t _dict_nextalt (dict_t *d, s3wid_t wid) { assert (d); assert (IS_WID(wid) && (wid < d->n_word)); return (d->word[wid].alt); } int32 dict_filler_word (dict_t *d, s3wid_t w) { assert (d); assert ((w >= 0) && (w < d->n_word)); w = dict_basewid(d, w); if ((w == d->startwid) || (w == d->finishwid)) return 0; if ((w >= d->filler_start) && (w <= d->filler_end)) return 1; return 0; } s3wid_t dict_wids2compwid (dict_t *d, s3wid_t *wid, int32 len) { s3wid_t w; int32 i; if (! d->comp_head) return BAD_WID; assert (len > 1); for (w = d->comp_head[wid[0]]; IS_WID(w); w = d->comp_head[w]) { /* w is a compound word beginning with wid[0]; check if rest matches */ assert (d->word[w].n_comp > 1); assert (d->word[w].comp[0] == wid[0]); if (d->word[w].n_comp == len) { for (i = 0; (i < len) && (d->word[w].comp[i] == wid[i]); i++); if (i == len) return (dict_basewid(d, w)); } } return BAD_WID; } #if (_DICT_TEST_) main (int32 argc, char *argv[]) { mdef_t *m; dict_t *d; char wd[1024]; s3wid_t wid; int32 p; if (argc < 3) E_FATAL("Usage: %s {mdeffile | NULL} dict [fillerdict]\n", argv[0]); m = (strcmp (argv[1], "NULL") != 0) ? mdef_init (argv[1]) : NULL; d = dict_init (m, argv[2], ((argc > 3) ? argv[3] : NULL), '_'); for (;;) { printf ("word> "); scanf ("%s", wd); wid = dict_wordid (d, wd); if (NOT_WID(wid)) E_ERROR("Unknown word\n"); else { for (wid = dict_basewid(d, wid); IS_WID(wid); wid = d->word[wid].alt) { printf ("%s\t", dict_wordstr(d, wid)); for (p = 0; p < d->word[wid].pronlen; p++) printf (" %s", dict_ciphone_str (d, wid, p)); printf ("\n"); } } } } #endif <file_sep>/SphinxTrain/src/programs/delint/main.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * This smooths the counts produced by bw(1). * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include "interp_fn.h" #include "parse_cmd_ln.h" /* SPHINX-III includes */ #include <s3/cmd_ln.h> #include <s3/acmod_set.h> #include <s3/model_def_io.h> #include <s3/s3tmat_io.h> #include <s3/s3mixw_io.h> #include <s3/s3gau_io.h> #include <s3/gauden_io.h> #include <s3/gauden.h> #include <s3/matrix.h> #include <s3/prim_type.h> /* define int32, etc. */ #include <s3/ckd_alloc.h> /* memory allocation */ #include <s3/err.h> /* define E_ERROR, E_INFO, etc */ #include <sys_compat/file.h> /* system wide includes */ #include <assert.h> /* for assert() macro */ #include <math.h> /* for fabs(), etc */ static int rd_interp_wr(void); int compute_mixw_lambda(float32 **lambda, float64 **lambda_acc, unsigned char *converged, uint32 n_cd_state, uint32 n_ci_state, uint32 **ci_mixw, float32 ***mixw_acc_a, float32 ***mixw_acc_b, float64 *dnom, uint32 n_mixw, uint32 n_feat, uint32 n_gau) { float64 tt_uni; float64 tt_ci; float64 tt_cd; float32 **acc_a; float32 **acc_b; float32 **ci_acc_b; float64 ci_dnom; float32 uniform_prob = 1.0 / n_gau; float64 norm; uint32 i, cd_i, j, k, l; for (i = 0; i < n_cd_state; i++) { if (converged[i]) continue; /* skip the ones which have converged */ cd_i = i + n_ci_state; acc_a = mixw_acc_a[cd_i]; acc_b = mixw_acc_b[cd_i]; for (j = 0; ci_mixw[i][j] != TYING_NO_ID; j++) { ci_acc_b = mixw_acc_b[ci_mixw[i][j]]; ci_dnom = dnom[ci_mixw[i][j]]; /* for all non-zero weight counts, accumulate lambda */ for (k = 0; k < n_feat; k++) { for (l = 0; l < n_gau; l++) { if (acc_a[k][l] > MIN_IEEE_NORM_POS_FLOAT32) { /* non-vanishing codeword */ tt_uni = lambda[i][DIST_UNIFORM] * uniform_prob; tt_ci = lambda[i][DIST_CI] * (ci_acc_b[k][l] * ci_dnom); /* i.e. CI lambda * CI prob */ tt_cd = lambda[i][DIST_CD] * (acc_b[k][l] * dnom[cd_i]); /* i.e. CD lambda * CD prob */ assert((tt_uni + tt_ci + tt_cd) > 0); norm = 1.0 / (tt_uni + tt_ci + tt_cd); if (tt_uni > MIN_IEEE_NORM_POS_FLOAT32) { tt_uni *= norm; lambda_acc[i][DIST_UNIFORM] += tt_uni * acc_a[k][l]; } if (tt_ci > MIN_IEEE_NORM_POS_FLOAT32) { tt_ci *= norm; lambda_acc[i][DIST_CI] += tt_ci * acc_a[k][l]; } if (tt_cd > MIN_IEEE_NORM_POS_FLOAT32) { tt_cd *= norm; lambda_acc[i][DIST_CD] += tt_cd * acc_a[k][l]; } } } } } } return S3_SUCCESS; } #define CON_TH 0.0001 int32 smooth_mixw(float32 ****out_mixw, float32 ***mixw_acc_a, float32 ***mixw_acc_b, uint32 n_mixw, uint32 n_feat, uint32 n_gau, model_def_t *mdef ) { uint32 i, j, k; uint32 n_base, cd_start, n_phone; uint32 n_ci_state; uint32 n_cd_state; uint32 n_state; uint32 max_state_pm; float64 *dnom_a; float64 *dnom_b; float64 *dnom; float64 sum_a; float64 sum_b; float64 sum; float32 **lambda; float64 **lambda_acc; uint32 **ci_mixw; uint32 *ci_state; uint32 max_iter; uint32 tt; unsigned char *conv_flag; uint32 converged; uint32 state_converged; acmod_id_t base; uint32 iter; float64 norm; float32 prior_lambda; model_def_entry_t *defn; float32 cilambda = *(float32 *)cmd_ln_access("-cilambda"); uint32 n_conv_state; uint32 **n_tied; acmod_set_t *acmod_set; acmod_set = mdef->acmod_set; /* * Compute normalization factors */ n_state = mdef->n_tied_state; dnom_a = (float64 *)ckd_calloc(n_state, sizeof(float64)); dnom_b = (float64 *)ckd_calloc(n_state, sizeof(float64)); dnom = (float64 *)ckd_calloc(n_state, sizeof(float64)); /* compute the count normalization factor for all tied states */ for (i = 0; i < n_state; i++) { sum_a = sum_b = sum = 0; for (k = 0; k < n_gau; k++) { sum_a += mixw_acc_a[i][0][k]; sum_b += mixw_acc_b[i][0][k]; } if ((sum_a > 0) && (sum_b > 0)) { dnom_a[i] = 1.0 / sum_a; dnom_b[i] = 1.0 / sum_b; dnom[i] = 1.0 / (sum_a + sum_b); } else { E_WARN("Tied state %u never observed in the training corpus\n", i); dnom_a[i] = dnom_b[i] = dnom[i] = 0.0; } } /* * Interpolate CI states */ n_cd_state = mdef->n_tied_state - mdef->n_tied_ci_state; n_ci_state = mdef->n_tied_ci_state; if (n_cd_state == 0) { E_INFO("Only CI states.\n"); E_INFO(" CI PDF == %.2f * CI + %.2f * UNIFORM\n", cilambda, (1.0 - cilambda)); /* add together counts for context independent states */ accum_3d(mixw_acc_a, mixw_acc_b, n_ci_state, /* run over n_ci_state states */ n_feat, n_gau); /* interpolate CI distributions with uniform distribution */ interp_counts_3d_uniform(mixw_acc_a, 0, /* start state */ n_ci_state, /* run length */ n_feat, n_gau, cilambda); *out_mixw = mixw_acc_a; ckd_free_3d((void ***)mixw_acc_b); return S3_SUCCESS; } /* * Interpolate all states */ max_state_pm = mdef->max_n_state; E_INFO("Interpolating %u CD states\n", n_cd_state); E_INFO("%u states max/model\n", max_state_pm); ci_mixw = (uint32 **)ckd_calloc_2d(n_cd_state, max_state_pm+1, sizeof(uint32)); for (i = 0; i < n_cd_state; i++) for (j = 0; j < max_state_pm+1; j++) ci_mixw[i][j] = TYING_NO_ID; n_tied = (uint32 **)ckd_calloc_2d(n_cd_state, max_state_pm+1, sizeof(uint32)); for (i = 0; i < n_cd_state; i++) for (j = 0; j < max_state_pm+1; j++) n_tied[i][j] = TYING_NO_ID; cd_start = n_base = acmod_set_n_ci(acmod_set); n_phone = acmod_set_n_acmod(acmod_set); defn = mdef->defn; /* for each cd state, find the id's of the associated ci states */ for (i = cd_start; i < n_phone; i++) { base = acmod_set_base_phone(acmod_set, i); for (j = 0; j < defn[i].n_state; j++) { if (defn[i].state[j] < n_ci_state) { /* This is a ci state, so skip it */ continue; } if (defn[i].state[j] != TYING_NON_EMITTING) { tt = defn[i].state[j] - n_ci_state; ci_state = ci_mixw[tt]; for (k = 0; (k < max_state_pm) && (ci_state[k] != TYING_NO_ID); k++) { if (ci_state[k] == defn[base].state[j]) break; /* already on list */ } if (ci_state[k] != defn[base].state[j]) { /* not on list, so add */ ci_state[k] = defn[base].state[j]; n_tied[tt][k] = 0; } ++n_tied[tt][k]; /* # of times CD and CI occur in same state position */ } } } lambda = (float32 **)ckd_calloc_2d(n_cd_state, N_DIST_TYPE, sizeof(float32)); /* storage is returned zeroed */ lambda_acc = (float64 **)ckd_calloc_2d(n_cd_state, N_DIST_TYPE, sizeof(float64)); for (i = 0; i < n_cd_state; i++) { /* biased initialization should help generally well trained models * converge faster */ lambda[i][(int)DIST_CD] = 0.6; lambda[i][(int)DIST_CI] = 0.3; lambda[i][(int)DIST_UNIFORM] = 0.1; } max_iter = *(const int *)cmd_ln_access("-maxiter"); conv_flag = (unsigned char *)ckd_calloc(n_cd_state, sizeof(unsigned char)); for (iter = 0, converged = FALSE, n_conv_state = 0; (iter < max_iter) && (!converged); iter++) { compute_mixw_lambda(lambda, lambda_acc, conv_flag, n_cd_state, n_ci_state, ci_mixw, mixw_acc_b, mixw_acc_a, dnom_a, n_mixw, n_feat, n_gau); compute_mixw_lambda(lambda, lambda_acc, conv_flag, n_cd_state, n_ci_state, ci_mixw, mixw_acc_a, mixw_acc_b, dnom_b, n_mixw, n_feat, n_gau); /* update lambdas and check for convergence */ for (i = 0; i < n_cd_state; i++) { if (conv_flag[i] == TRUE) /* don't update converged states */ continue; norm = 0.0; for (j = 0; j < N_DIST_TYPE; j++) { norm += lambda_acc[i][j]; } if (norm > MIN_IEEE_NORM_POS_FLOAT32) { norm = 1.0 / norm; for (j = 0, state_converged = TRUE; j < N_DIST_TYPE; j++) { prior_lambda = lambda[i][j]; lambda[i][j] = lambda_acc[i][j] * norm; lambda_acc[i][j] = 0.0; if (fabs(prior_lambda - lambda[i][j]) > CON_TH) { state_converged = converged = FALSE; } } } else { for (j = 0; j < N_DIST_TYPE; j++) { lambda[i][j] = 1.0 / N_DIST_TYPE; } state_converged = TRUE; } if (state_converged) { conv_flag[i] = TRUE; ++n_conv_state; } } E_INFO("%u:%u:%u\n", iter, n_conv_state, n_cd_state); } if (!converged) { E_WARN("%u of %u states converged after %u iterations.\n", n_conv_state, n_cd_state, iter); } printf("SUMMARY\n\n"); printf(" State Count A Count B Total CD CI UNI Cnv\n"); printf("------ --------- --------- --------- ----- ----- ------ ---\n"); for (i = 0; i < n_cd_state; i++) { j = n_ci_state + i; /* CD tied state id */ printf("%6u %.3e %.3e %.3e %.3f %.3f %.3f %s\n", j, (dnom_a[j] > 0 ? 1.0 / dnom_a[j] : 0.0), /* count of partition A tied state j */ (dnom_b[j] > 0 ? 1.0 / dnom_b[j] : 0.0), /* count of partition B tied state j */ (dnom[j] > 0 ? 1.0 / dnom[j] : 0.0), /* count of partition A+B tied state j */ lambda[i][DIST_CD], lambda[i][DIST_CI], lambda[i][DIST_UNIFORM], (conv_flag[i] ? "y" : "n")); } interp_mixw(out_mixw, mixw_acc_a, mixw_acc_b, dnom, lambda, cilambda, ci_mixw, n_tied, n_cd_state, n_ci_state, n_mixw, n_feat, n_gau); return S3_SUCCESS; } static int interp(float32 ****out_mixw, model_def_t *mdef, float32 ***mixw_acc_a, float32 ***mixw_acc_b, uint32 n_mixw, uint32 n_feat, uint32 n_gau) { int ret = S3_SUCCESS; if (smooth_mixw(out_mixw, mixw_acc_a, mixw_acc_b, n_mixw, n_feat, n_gau, mdef) != S3_SUCCESS) { ret = S3_ERROR; } return ret; } static int rd_param(uint32 *idx, const char **accum_dirs, float32 ****out_mixw_acc, uint32 *out_n_mixw, uint32 *out_n_feat, uint32 *out_n_gau) { char fn[MAXPATHLEN+1]; const char *accum_dir; uint32 i; i = *idx; accum_dir = accum_dirs[i]; sprintf(fn, "%s/mixw_counts", accum_dir); E_INFO("Reading %s\n", fn); if (s3mixw_read(fn, out_mixw_acc, out_n_mixw, out_n_feat, out_n_gau) != S3_SUCCESS) { return S3_ERROR; } ++(*idx); return S3_SUCCESS; } static void accum_param(float32 ***mixw_acc, float32 ***mixw_acc_in, uint32 n_mixw, uint32 n_feat, uint32 n_gau) { if (mixw_acc_in) { accum_3d(mixw_acc, mixw_acc_in, n_mixw, n_feat, n_gau); } } int wr_param(float32 ***mixw_acc, uint32 n_mixw, uint32 n_feat, uint32 n_density) { /* * Write the parameters to files */ E_INFO("Writing %s\n", cmd_ln_access("-mixwfn")); if (s3mixw_write(cmd_ln_access("-mixwfn"), mixw_acc, n_mixw, n_feat, n_density) != S3_SUCCESS) { return S3_ERROR; } return S3_SUCCESS; } static int rd_interp_wr() { model_def_t *mdef; float32 ***mixw_acc_in; float32 ***mixw_acc_a; float32 ***mixw_acc_b; float32 ***mixw; uint32 n_mixw; uint32 n_feat; uint32 n_gau; const char **accum_dir; uint32 i; if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { return S3_ERROR; } i = 0; accum_dir = (const char **)cmd_ln_access("-accumdirs"); /* must be at least two accum dirs for interpolation */ assert(accum_dir[i] != NULL); rd_param(&i, accum_dir, &mixw_acc_a, &n_mixw, &n_feat, &n_gau); assert(accum_dir[i] != NULL); rd_param(&i, accum_dir, &mixw_acc_b, &n_mixw, &n_feat, &n_gau); while (accum_dir[i] != NULL) { rd_param(&i, accum_dir, &mixw_acc_in, &n_mixw, &n_feat, &n_gau); /* accumulate additional "a" counts into "a" buffers */ accum_param(mixw_acc_a, mixw_acc_in, n_mixw, n_feat, n_gau); ckd_free_3d((void ***)mixw_acc_in); /* must be an even # of accum dirs for interpolation */ assert(accum_dir[i] != NULL); rd_param(&i, accum_dir, &mixw_acc_in, &n_mixw, &n_feat, &n_gau); /* accumulate additional "b" counts into "b" buffers */ accum_param(mixw_acc_b, mixw_acc_in, n_mixw, n_feat, n_gau); ckd_free_3d((void ***)mixw_acc_in); } if (interp(&mixw, mdef, mixw_acc_a, mixw_acc_b, n_mixw, n_feat, n_gau) != S3_SUCCESS) { } if (wr_param(mixw, n_mixw, n_feat, n_gau) != S3_SUCCESS) { E_FATAL("Error writing parameters\n"); } return S3_SUCCESS; } int main(int argc, char *argv[]) { parse_cmd_ln(argc, argv); if (rd_interp_wr() != S3_SUCCESS) exit(1); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.14 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.13 1996/03/25 15:40:05 eht * Added ability to set input feature vector length * * Revision 1.12 1996/03/04 15:57:41 eht * Made some changes so that acmod_set conforms to its interface * * Revision 1.11 1996/01/26 18:07:00 eht * Use the feat module * * Revision 1.10 1995/12/15 18:37:07 eht * Added some type cases for memory alloc/free * * Revision 1.9 1995/10/10 12:53:35 eht * Changed to use <s3/prim_type.h> * * Revision 1.8 1995/10/09 15:30:33 eht * Removed __FILE__, __LINE__ arguments to ckd_alloc routines * * Revision 1.7 1995/10/05 12:55:06 eht * Deal w/ untrained tied states and change in acmod_set interface * * Revision 1.6 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.5 1995/09/07 19:10:22 eht * Don't consider CI states when computing the set of * CI states associated with CD states. * * Revision 1.4 1995/08/15 13:39:57 eht * Compute the number of times a seno appears with a given CI distribution. * * Revision 1.3 1995/08/10 20:29:40 eht * Yet another development version * * Revision 1.2 1995/08/09 00:38:05 eht * Another development version * * Revision 1.1 1995/06/02 20:56:53 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/kdtree.h /* ==================================================================== * Copyright (c) 2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: kdtree.h * * Description: kd-tree implementation for mixture Gaussians * * Author: <NAME> <<EMAIL>> * *********************************************************************/ #ifndef __KDTREE_H__ #define __KDTREE_H__ #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include "s3/prim_type.h" #include "s3/gauden.h" #include "s3/vector.h" typedef struct kd_tree_node_s kd_tree_node_t; struct kd_tree_node_s { const vector_t *means, *variances; /* Codebook of Gaussians, shared by all nodes */ float32 **boxes; /* Gaussian boxes for codebook, shared by all nodes */ float32 threshold; /* Threshold for Gaussian boxes */ uint32 n_level; /* Number of levels (0 for non-root) */ uint32 n_density, n_comp; /* Number of densities, number of components. */ uint8 *bbi; /* BBI vector of intersecting Gaussians */ vector_t lower, upper; /* Lower and upper coordinates of projection */ uint32 split_comp; /* Dimension in which split is done */ float32 split_plane; /* Hyperplane splitting this node */ kd_tree_node_t *left, *right; /* Child nodes */ }; kd_tree_node_t *build_kd_tree(const vector_t *means, const vector_t *variances, uint32 n_density, uint32 n_comp, float32 threshold, int32 n_levels, int32 absolute); void free_kd_tree(kd_tree_node_t *tree); int32 write_kd_trees(const char *outfile, kd_tree_node_t **trees, uint32 n_trees); int32 read_kd_trees(const char *infile, kd_tree_node_t ***out_trees, uint32 *out_n_trees); #ifdef __cplusplus } #endif #endif /* __KDTREE_H__ */ <file_sep>/archive_s3/s3/src/libfbs/tmat.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * tmat.h * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 13-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created, liberally borrowed from <NAME>'s S3 trainer. */ #ifndef _LIBFBS_TMAT_H_ #define _LIBFBS_TMAT_H_ #include <libutil/prim_type.h> #include "s3types.h" #include <s3.h> /* * Transition matrix data structure. */ typedef struct { int32 ***tp; /* The transition matrices; int32 since probs in logs3 domain: tp[tmatid][from-state][to-state] */ int32 n_tmat; /* #matrices */ int32 n_state; /* #states/matrix (#from states = n_state-1, since the final state is a non-emitting state, with no transition out of it) */ float32 tpfloor; /* Floor value applied to real (non-zero-prob) transitions */ } tmat_t; tmat_t *tmat_init (char *tmatfile, /* In: input file */ float32 tpfloor); /* In: floor value for each non-zero transition probability */ tmat_t *tmat_gettmat ( void ); /* * Check if all tmats are upper triangular. * Return value: 0 if yes, -1 if failed. */ int32 tmat_chk_uppertri (tmat_t *tmat); /* In: tmat structure read in by tmat_init */ #endif <file_sep>/SphinxTrain/src/programs/init_gau/accum.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: accum.c * * Description: * Accumulate mean and variance estimation sums * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/matrix.h> #include <s3/ckd_alloc.h> #include "accum.h" int accum_state_mean(vector_t ***mean, float32 ***dnom, vector_t **feat, uint32 *del_b, uint32 *del_e, uint32 n_del, uint32 n_feat, const uint32 *veclen, uint32 *sseq, uint32 *ci_sseq, uint32 n_frame) { uint32 t; /* time (in frames) */ uint32 s; /* a tied state */ uint32 ci_s; /* a CI tied state */ uint32 f; /* a feature stream idx */ uint32 c; /* a vector component idx */ for (t = 0; t < n_frame; t++) { if (sseq && ci_sseq) { s = sseq[t]; ci_s = ci_sseq[t]; } else { s = 0; ci_s = 0; } for (f = 0; f < n_feat; f++) { dnom[s][f][0] += 1.0; if (s != ci_s) { dnom[ci_s][f][0] += 1.0; } for (c = 0; c < veclen[f]; c++) { /* only one Gaussian per state */ mean[s][f][0][c] += feat[t][f][c]; if (s != ci_s) { mean[ci_s][f][0][c] += feat[t][f][c]; } } } } return 0; } int accum_state_var(vector_t ***var, vector_t ***mean, float32 ***dnom, vector_t **feat, uint32 *del_b, uint32 *del_e, uint32 n_del, uint32 n_feat, const uint32 *veclen, uint32 *sseq, uint32 *ci_sseq, uint32 n_frame) { uint32 t; /* time (in frames) */ uint32 s; /* a tied state */ uint32 ci_s; /* a CI tied state */ uint32 f; /* a feature stream idx */ uint32 c; /* a vector component idx */ float32 diff; for (t = 0; t < n_frame; t++) { if (sseq && ci_sseq) { /* get the tied state for time t */ s = sseq[t]; /* get the CI state as well */ ci_s = ci_sseq[t]; } else { s = 0; ci_s = 0; } for (f = 0; f < n_feat; f++) { dnom[s][f][0] += 1.0; if (s != ci_s) { dnom[ci_s][f][0] += 1.0; } for (c = 0; c < veclen[f]; c++) { /* only one Gaussian per state */ diff = feat[t][f][c] - mean[s][f][0][c]; var[s][f][0][c] += diff * diff; if (s != ci_s) { diff = feat[t][f][c] - mean[ci_s][f][0][c]; var[ci_s][f][0][c] += diff * diff; } } } } return 0; } int accum_state_fullvar(vector_t ****var, vector_t ***mean, float32 ***dnom, vector_t **feat, uint32 *del_b, uint32 *del_e, uint32 n_del, uint32 n_feat, const uint32 *veclen, uint32 *sseq, uint32 *ci_sseq, uint32 n_frame) { uint32 t; /* time (in frames) */ uint32 s; /* a tied state */ uint32 ci_s; /* a CI tied state */ uint32 f; /* a feature stream idx */ uint32 c; /* a vector component idx */ for (t = 0; t < n_frame; t++) { if (sseq && ci_sseq) { /* get the tied state for time t */ s = sseq[t]; /* get the CI state as well */ ci_s = ci_sseq[t]; } else { s = 0; ci_s = 0; } for (f = 0; f < n_feat; f++) { vector_t dvec = ckd_calloc(veclen[f], sizeof(float32)); vector_t *cov = (vector_t *)ckd_calloc_2d(veclen[f], veclen[f], sizeof(float32)); dnom[s][f][0] += 1.0; if (s != ci_s) { dnom[ci_s][f][0] += 1.0; } for (c = 0; c < veclen[f]; c++) dvec[c] = feat[t][f][c] - mean[s][f][0][c]; outerproduct(cov, dvec, dvec, veclen[f]); matrixadd(var[s][f][0], cov, veclen[f], veclen[f]); if (s != ci_s) { for (c = 0; c < veclen[f]; c++) dvec[c] = feat[t][f][c] - mean[ci_s][f][0][c]; outerproduct(cov, dvec, dvec, veclen[f]); matrixadd(var[ci_s][f][0], cov, veclen[f], veclen[f]); } ckd_free(dvec); ckd_free_2d((void **)cov); } } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1996/08/06 14:13:04 eht * added "const" attribute to veclen arguments * * Revision 1.2 1996/02/02 17:32:59 eht * Added estimation of CI mean/var when only CD states are present * * Revision 1.1 1995/12/14 19:52:59 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/wnet2pnet.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * wnet2pnet.c -- Build a triphone HMM net from a given word net. * * * HISTORY * * 05-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "senone.h" #include "wnet2pnet.h" static glist_t pnet; static int32 n_pnode, n_plink; /* * Additional data needed at each word node to build the phone net. */ typedef struct wnode_data_s { wnode_t *wnode; glist_t *lc; /* lc[p] = list of initial pnode_t with left context = p */ glist_t *rc; /* rc[p] = list of final pnode_t with right context = p */ } wnode_data_t; static void link_pnodes (pnode_t *src, pnode_t *dst) { plink_t *pl; pl = (plink_t *) mymalloc (sizeof(plink_t)); pl->dst = dst; src->succ = glist_add_ptr (src->succ, (void *)pl); n_plink++; } static plink_t *plink_lookup (pnode_t *src, pnode_t *dst) { gnode_t *gn; plink_t *pl; for (gn = src->succ; gn; gn = gn->next) { pl = (plink_t *) gnode_ptr(gn); if (pl->dst == dst) return pl; } return NULL; } /* * Lookup the list of pnodes for an HMM with the same underlying model as the given * pid. Return pointer if found, NULL otherwise. */ static pnode_t *plist_lookup_hmm (mdef_t *mdef, glist_t plist, s3pid_t pid) { gnode_t *gn; pnode_t *pn; for (gn = plist; gn; gn = gnode_next(gn)) { pn = (pnode_t *) gnode_ptr(gn); if (mdef_hmm_cmp (mdef, pn->hmm.pid, pid) == 0) return pn; } return NULL; } static pnode_t *pnode_create (mdef_t *mdef, s3pid_t pid, s3wid_t wid, int32 pos) { pnode_t *pn; pn = (pnode_t *) mymalloc (sizeof(pnode_t)); pn->wid = wid; pn->pos = pos; pn->hmm.state = (hmm_state_t *) ckd_calloc (mdef->n_emit_state, sizeof(hmm_state_t)); pn->hmm.pid = pid; pn->succ = NULL; pnet = glist_add_ptr (pnet, (void *) pn); n_pnode++; return pn; } /* * Build HMM net for the given word. All the internal links are set up. But the net * is isolated, with no connections to any other word. However, wnode_data->{lc,rc} * are updated with the HMMs at the extreme ends (left and right) so that one can later * complete the entire net. */ static void wnode2pnet_build (mdef_t *mdef, dict_t *dict, wnode_data_t *wnode_data) { uint8 *lc, *rc; wnode_t *wn; gnode_t *gn, *gn2; wlink_t *wl; s3wid_t wid; s3pid_t pid; s3cipid_t ci, l, r; int32 pronlen; int32 i, j; glist_t p1list, p2list; pnode_t *pn, *prevpn; wn = wnode_data->wnode; /* Mark all the left and right context for this word node */ lc = (uint8 *) ckd_calloc (mdef->n_ciphone, sizeof(uint8)); rc = (uint8 *) ckd_calloc (mdef->n_ciphone, sizeof(uint8)); if (! wn->pred) { /* No predecessor, pick SILENCE_CIPHONE as left context */ lc[mdef->sil] = 1; } else { for (gn = wn->pred; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); wid = wl->dst->wid; /* Predecessor word id */ lc[dict_last_phone(dict, wid)] = 1; } } if (! wn->succ) { /* No successor, use SILENCE_CIPHONE as right context */ rc[mdef->sil] = 1; } else { for (gn = wn->succ; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); wid = wl->dst->wid; rc[dict_first_phone(dict, wid)] = 1; } } wnode_data->lc = (glist_t *) ckd_calloc (mdef->n_ciphone, sizeof(glist_t)); wnode_data->rc = (glist_t *) ckd_calloc (mdef->n_ciphone, sizeof(glist_t)); /* Create phone net for wn->wid */ wid = wn->wid; if ((pronlen = dict_pronlen (dict, wid)) > 1) { /* Multi-phone pronunciation; initial phone position, expand left contexts */ p1list = NULL; /* List of distinct HMMs allocated for leftmost phone */ ci = dict_pron(dict, wid, 0); r = dict_pron(dict, wid, 1); for (i = 0; i < mdef->n_ciphone; i++) { if (! lc[i]) continue; pid = mdef_phone_id_nearest (mdef, ci, (s3cipid_t)i, r, WORD_POSN_BEGIN); assert (IS_PID(pid)); if ((pn = plist_lookup_hmm (mdef, p1list, pid)) == NULL) { pn = pnode_create (mdef, pid, wid, 0); p1list = glist_add_ptr (p1list, (void *) pn); } wnode_data->lc[i] = glist_add_ptr (wnode_data->lc[i], (void *) pn); } /* Intermediate phones; known left/right contexts */ for (i = 1; i < pronlen-1; i++) { p2list = NULL; /* Create HMM node for phone position i */ ci = dict_pron (dict, wid, i); l = dict_pron (dict, wid, i-1); r = dict_pron (dict, wid, i+1); pid = mdef_phone_id_nearest (mdef, ci, l, r, WORD_POSN_INTERNAL); assert (IS_PID(pid)); pn = pnode_create (mdef, pid, wid, i); p2list = glist_add_ptr (p2list, (void *) pn); /* Link from previous nodes */ for (gn = p1list; gn; gn = gn->next) { prevpn = (pnode_t *) gnode_ptr(gn); link_pnodes (prevpn, pn); } glist_free (p1list); p1list = p2list; } /* Final phone position; expand right context (for the ones present) */ p2list = NULL; ci = dict_pron(dict, wid, pronlen-1); l = dict_pron(dict, wid, pronlen-2); for (i = 0; i < mdef->n_ciphone; i++) { if (! rc[i]) continue; pid = mdef_phone_id_nearest (mdef, ci, l, (s3cipid_t)i, WORD_POSN_END); assert (IS_PID(pid)); if ((pn = plist_lookup_hmm (mdef, p2list, pid)) == NULL) { pn = pnode_create (mdef, pid, wid, pronlen-1); p2list = glist_add_ptr (p2list, (void *) pn); } wnode_data->rc[i] = glist_add_ptr (wnode_data->rc[i], (void *) pn); } /* Link from previous nodes */ for (gn = p1list; gn; gn = gn->next) { prevpn = (pnode_t *) gnode_ptr(gn); for (gn2 = p2list; gn2; gn2 = gn2->next) { pn = (pnode_t *) gnode_ptr(gn2); link_pnodes (prevpn, pn); } } glist_free (p1list); glist_free (p2list); } else { /* Single-phone word; handle left/right contexts simultaneously */ p1list = NULL; ci = dict_pron(dict, wid, 0); for (i = 0; i < mdef->n_ciphone; i++) { if (! lc[i]) continue; for (j = 0; j < mdef->n_ciphone; j++) { if (! rc[j]) continue; pid = mdef_phone_id_nearest (mdef, ci, (s3cipid_t)i, (s3cipid_t)j, WORD_POSN_SINGLE); assert (IS_PID(pid)); if ((pn = plist_lookup_hmm (mdef, p1list, pid)) == NULL) { pn = pnode_create (mdef, pid, wid, 0); p1list = glist_add_ptr (p1list, (void *) pn); } wnode_data->lc[i] = glist_add_ptr (wnode_data->lc[i], (void *) pn); wnode_data->rc[j] = glist_add_ptr (wnode_data->rc[j], (void *) pn); } } glist_free (p1list); } ckd_free (lc); ckd_free (rc); } /* * Build cross-word HMM links, taking phonetic context into account: * Let the last CIphone in src = l (i.e., the left context for dst), and * the first CIphone in dst = r (i.e., the right phonetic context for src). Then, * create links from the HMMs in the glist src->rc[r] to those in dst->lc[l]. But, * avoid creating duplicate links, since several entries in a glist may share the * same HMM. */ static void link_wnodes (dict_t *dict, wnode_data_t *src, wnode_data_t *dst) { s3cipid_t l, r; wnode_t *wn; gnode_t *gn1, *gn2; pnode_t *pn1, *pn2; /* Find the last phone for the source node (the left context for the destination) */ wn = src->wnode; l = dict_pron (dict, wn->wid, dict_pronlen(dict, wn->wid) - 1); /* Find the first phone for the dest. node (the right context for the source) */ wn = dst->wnode; r = dict_pron (dict, wn->wid, 0); /* Link each HMM in src->rc[r] to each in dst->lc[l] */ for (gn1 = src->rc[r]; gn1; gn1 = gn1->next) { pn1 = (pnode_t *) gnode_ptr(gn1); for (gn2 = dst->lc[l]; gn2; gn2 = gn2->next) { pn2 = (pnode_t *) gnode_ptr(gn2); /* Check if a link already exists */ if (! plink_lookup (pn1, pn2)) link_pnodes (pn1, pn2); } } } /* * Convert a wordnet into a phone net. */ glist_t wnet2pnet (mdef_t *mdef, dict_t *dict, glist_t wnet, wnode_t *wstart, wnode_t *wend, /* In: Dummy start/end anchors */ pnode_t **pstart, pnode_t **pend) /* Out: Dummy start/end anchors */ { gnode_t *gn, *gn2; wnode_t *wn; wlink_t *wl; int32 n, i, j; wnode_data_t *wnode_data; pnode_t *pn, *pn2; if (NOT_CIPID(mdef->sil)) E_FATAL("%s not defined\n", SILENCE_CIPHONE); pnet = NULL; n_pnode = 0; n_plink = 0; /* Allocate wnode_data_t prior to building the phone net */ n = glist_count (wnet) - 2; /* Skip wstart and wend */ if (n <= 0) { E_ERROR("Empty word net\n"); return NULL; } wnode_data = (wnode_data_t *) ckd_calloc (n, sizeof(wnode_data_t)); for (gn = wnet, i = 0; gn; gn = gn->next) { wn = (wnode_t *) gnode_ptr(gn); if ((wn == wstart) || (wn == wend)) continue; /* Skip the dummy start/end nodes */ wn->data = i; wnode_data[i].wnode = wn; wnode2pnet_build (mdef, dict, wnode_data+i); i++; } assert (i == n); /* Create links between the pnodes created for each word above */ for (i = 0; i < n; i++) { wn = wnode_data[i].wnode; for (gn = wn->succ; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); if ((wnode_t *)wl->dst != wend) link_wnodes (dict, wnode_data+i, wnode_data+(wl->dst->data)); } } /* Add dummy pnode at the beginning of the net */ pn = pnode_create (mdef, mdef->sil, BAD_WID, 0); /* Link it to initial phones of all successors of wstart */ for (gn = wstart->succ; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); i = wl->dst->data; for (j = 0; j < mdef->n_ciphone; j++) { for (gn2 = wnode_data[i].lc[j]; gn2; gn2 = gn2->next) { pn2 = (pnode_t *) gnode_ptr(gn2); if (! plink_lookup (pn, pn2)) link_pnodes (pn, pn2); } } } *pstart = pn; /* Add dummy pnode at the end of the net */ pn = pnode_create (mdef, mdef->sil, BAD_WID, 0); /* Link from the final phones of all predecessors of wend to pn */ for (gn = wend->pred; gn; gn = gn->next) { wl = (wlink_t *) gnode_ptr(gn); i = wl->dst->data; for (j = 0; j < mdef->n_ciphone; j++) { for (gn2 = wnode_data[i].rc[j]; gn2; gn2 = gn2->next) { pn2 = (pnode_t *) gnode_ptr(gn2); if (! plink_lookup (pn2, pn)) link_pnodes (pn2, pn); } } } *pend = pn; /* Free working data */ for (i = 0; i < n; i++) { for (j = 0; j < mdef->n_ciphone; j++) { glist_free (wnode_data[i].lc[j]); glist_free (wnode_data[i].rc[j]); } ckd_free (wnode_data[i].lc); ckd_free (wnode_data[i].rc); } ckd_free (wnode_data); E_INFO("%d pnodes, %d plinks\n", n_pnode, n_plink); return pnet; } static void pnode_free (void *data) { pnode_t *pn; pn = (pnode_t *) data; ckd_free (pn->hmm.state); glist_myfree (pn->succ, sizeof(plink_t)); } void pnet_free (glist_t pnet) { glist_apply_ptr (pnet, pnode_free); glist_myfree (pnet, sizeof(pnode_t)); } void pnet_set_senactive (mdef_t *m, glist_t plist, bitvec_t active, int32 n_sen) { gnode_t *gn; pnode_t *pn; bitvec_clear_all (active, n_sen); for (gn = plist; gn; gn = gnode_next(gn)) { pn = (pnode_t *) gnode_ptr(gn); senone_set_active (active, m->phone[pn->hmm.pid].state, m->n_emit_state); } } /* Used only by the following dump routines */ static mdef_t *tmpmdef; static dict_t *tmpdict; static void pnet_dump_pnode (void *data) { pnode_t *pn; char buf[4096]; pn = (pnode_t *) data; mdef_phone_str (tmpmdef, pn->hmm.pid, buf); if (IS_WID(pn->wid)) printf ("%s.%d.%s\n", dict_wordstr(tmpdict, pn->wid), pn->pos, buf); else printf ("%s.%d.%s\n", "<>", pn->pos, buf); /* Dummy node */ fflush (stdout); } static void pnet_dump_plink (void *data) { pnode_t *pn; plink_t *pl; gnode_t *gn; pnet_dump_pnode (data); pn = (pnode_t *) data; for (gn = pn->succ; gn; gn = gn->next) { pl = (plink_t *) gnode_ptr(gn); printf ("\t\t-> "); pnet_dump_pnode (pl->dst); } fflush (stdout); } void pnet_dump (mdef_t *m, dict_t *d, glist_t pnet) { tmpdict = d; tmpmdef = m; E_INFO("pnodes:\n"); glist_apply_ptr (pnet, pnet_dump_pnode); E_INFO("plinks:\n"); glist_apply_ptr (pnet, pnet_dump_plink); } <file_sep>/SphinxTrain/src/programs/mk_s2sendump/mk_s2sendump.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: mk_s2sendump.c * * Description: * Make sendump file in converting S3 models to S2 models * * Author: * <NAME> (<EMAIL>) * Picked togeterh out off rkm's sen2s2.c *********************************************************************/ #include "parse_cmd_ln.h" /* The SPHINX-III common library */ #include <s3/common.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3mixw_io.h> #include <s3/s3tmat_io.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s3/s2_read_map.h> #include <s3/s2_write_seno.h> #include <s2/byteorder.h> #include <s3/cmd_ln.h> #include "s3/hash.h" typedef hash_t hash_table_t; #include "s3types.h" #include "another_s3types.h" #include "another_senone.h" #include "bio.h" #include "logs3.h" #include "feat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #define NO_STATE 0xffffffff #define MIXW_PARAM_VERSION "1.0" #define SPDEF_PARAM_VERSION "1.2" static char *fmtdesc[] = { "BEGIN FILE FORMAT DESCRIPTION", "(int32) <length(string)> (including trailing 0)", "<string> (including trailing 0)", "... preceding 2 items repeated any number of times", "(int32) 0 (length(string)=0 terminates the header)", "(int32) <#codewords>", "(int32) <#pdfs>", "256 (int32) cluster-prob values for codebook-0 codeword-0", "#pdf (unsigned char) cluster-prob ids for codebook-0 codeword-0", "... preceding 2 items repeated for all codewords in codebook-0", "preceding 3 items repeated for codebooks 1, 2, 3.", "END FILE FORMAT DESCRIPTION", NULL, }; #if 0 #if defined(_HPUX_SOURCE) #define SWAPW(x) x = ( (((x)<<8)&0x0000ff00) | (((x)>>8)&0x00ff) ) #define SWAPL(x) x = ( (((x)<<24)&0xff000000) | (((x)<<8)&0x00ff0000) | \ (((x)>>8)&0x0000ff00) | (((x)>>24)&0x000000ff) ) #else #define SWAPW(x) #define SWAPL(x) #endif #endif /* For Pocketsphinx ONLY: Allocate 0..159 for negated quantized * mixture weights and 0..96 for negated normalized acoustic scores, * so that the combination of the two (for a single mixture) can never * exceed 255. */ #define MAX_NEG_MIXW 159 /**< Maximum negated mixture weight value. */ #define MAX_NEG_ASCR 96 /**< Maximum negated acoustic score value. */ float64 vector_sum_norm (float32 *vec, int32 len) { float64 sum, f; int32 i; sum = 0.0; for (i = 0; i < len; i++) sum += vec[i]; if (sum != 0.0) { f = 1.0 / sum; for (i = 0; i < len; i++) vec[i] *= f; } return sum; } static void fwrite_int32 (fp, val) FILE *fp; int val; { SWAP_L(val); fwrite (&val, sizeof(int), 1, fp); } static void senone_dump (const model_def_t *mdef, const senone_t *s, char *file) { int32 i, j, k, c, m, f, n, p, sb, se; mixw_t *fw; FILE *fpout; int32 lut[256]; senprob_t *sp; int n_emit_state,d,d2,pmax,lpmax; E_INFO("Writing S2 format sendump file: %s\n", file); if ((fpout = fopen(file, "wb")) == NULL) E_FATAL("fopen(%s,wb) failed\n", file); /* Write format description into header */ for (i = 0; fmtdesc[i] != NULL; i++) { n = strlen(fmtdesc[i])+1; fwrite_int32 (fpout, n); fwrite (fmtdesc[i], sizeof(char), n, fpout); } /* Terminate header */ fwrite_int32 (fpout, 0); /* Write #codewords, #pdfs */ if (s->n_mgau != 1) E_FATAL("#codebooks(%d) != 1\n", s->n_mgau); if (s->mgau2sen[0].n_sen != s->n_sen) E_FATAL("#senones for mgau[0](%d) != total #senones(%d)\n", s->mgau2sen[0].n_sen, s->n_sen); if (s->n_feat != 4) E_FATAL("#Features(%d) != 4\n", s->n_feat); for (i = 0; i < s->n_feat; i++) { if (s->mgau2sen[0].feat_mixw[i].n_wt != s->mgau2sen[0].feat_mixw[0].n_wt) E_FATAL("#Wts not same for all features\n"); } if (s->mgau2sen[0].feat_mixw[0].n_wt != 256) E_FATAL("#Wts(%d) != 256\n", s->mgau2sen[0].feat_mixw[0].n_wt); fwrite_int32 (fpout, s->mgau2sen[0].feat_mixw[0].n_wt); fwrite_int32 (fpout, s->n_sen); /* Create lut */ for (i = 0; i < 256; i++) lut[i] = -(i << s->shift); sp = (senprob_t *) ckd_calloc (s->n_sen, sizeof(senprob_t)); /* Write PDFs (#feat x #wt x #sen) */ if (mdef->max_n_state - 1 != 5) E_FATAL("#States(%d) != 5\n", mdef->max_n_state - 1); n_emit_state = mdef->max_n_state - 1; for (f = 0; f < s->n_feat; f++) { fw = s->mgau2sen[0].feat_mixw; for (c = 0; c < fw[f].n_wt; c++) { /* * In S3, all CI-senones (for all CI-phones) come first. CD-senones later. * But in S2, for each CI-phone, CD-senones come first and then CI-senones. */ k = 0, d=mdef->acmod_set->n_ci; lpmax = mdef->acmod_set->n_ci * n_emit_state - 1; for (p = 0; p < mdef->acmod_set->n_ci; p++) { /* CD senones first; find start and end points in S3 data */ for (pmax = lpmax ; mdef->defn[d].tmat == p; d++) { for (d2=0; d2 < n_emit_state; d2++) if (mdef->defn[d].state[d2] > pmax) pmax = mdef->defn[d].state[d2]; } sb = lpmax + 1; se = pmax; lpmax = pmax; for (i = sb; i <= se; i++) { m = s->sen2mgau[i]; assert (m == 0); j = s->mgau2sen_idx[i]; assert (j == i); sp[k++] = fw[f].prob[j][c]; } /* CI senones next */ sb = p * n_emit_state; se = sb + n_emit_state - 1; for (i = sb; i <= se; i++) { m = s->sen2mgau[i]; assert (m == 0); j = s->mgau2sen_idx[i]; assert (j == i); sp[k++] = fw[f].prob[j][c]; } } assert (k == mdef->n_tied_state); /* Write lut for feat f, codeword c */ for (i = 0; i < 256; i++) fwrite_int32 (fpout, lut[i]); /* Write data for feat f, codeword c */ fwrite (sp, sizeof(uint8), s->n_sen, fpout); } } fclose (fpout); } static void pocketsphinx_senone_dump(const model_def_t *mdef, const senone_t *s, char *file) { FILE *fpout; char pshdr[256]; int32 i, n, k, c, d, f; E_INFO("Writing PocketSphinx format sendump file: %s\n", file); if ((fpout = fopen(file, "wb")) == NULL) E_FATAL("fopen(%s,wb) failed\n", file); /* Write format description into header */ for (i = 0; fmtdesc[i] != NULL; i++) { n = strlen(fmtdesc[i])+1; fwrite_int32 (fpout, n); fwrite (fmtdesc[i], sizeof(char), n, fpout); } /* Now write the cluster, feature and codebook counts */ sprintf(pshdr, "cluster_count %d", 0); fwrite_int32(fpout, strlen(pshdr)+1); fwrite(pshdr, sizeof(char), strlen(pshdr)+1, fpout); sprintf(pshdr, "codebook_count %d", s->n_mgau); fwrite_int32(fpout, strlen(pshdr)+1); fwrite(pshdr, sizeof(char), strlen(pshdr)+1, fpout); sprintf(pshdr, "feature_count %d", s->n_feat); fwrite_int32(fpout, strlen(pshdr)+1); fwrite(pshdr, sizeof(char), strlen(pshdr)+1, fpout); /* Pad the header for alignment purposes */ k = ftell(fpout) & 3; if (k > 0) { k = 4 - k; fwrite_int32(fpout, k); fwrite("!!!!", 1, k, fpout); } /* Terminate header */ fwrite_int32(fpout, 0); /* For each codebook, write #codewords, #pdfs */ for (c = 0; c < s->n_mgau; ++c) { /* Write #densities, #senones (indicates that they are transposed) */ fwrite_int32 (fpout, s->mgau2sen[c].feat_mixw[0].n_wt); fwrite_int32 (fpout, s->mgau2sen[c].n_sen); /* Now write out transposed, quantized senones. */ /* Note! PocketSphinx puts them in Sphinx3 order. */ for (f = 0; f < s->n_feat; f++) { for (d = 0; d < s->mgau2sen[c].feat_mixw[f].n_wt; ++d) { for (i = 0; i < s->mgau2sen[c].n_sen; ++i) { fputc(s->mgau2sen[c].feat_mixw[f].prob[i][d], fpout); } } } } fclose (fpout); } static int32 senone_mgau_map_read (senone_t *s, char *file_name) { FILE *fp; int32 byteswap, chksum_present, n_mgau_present; uint32 chksum; int32 i; char eofchk; char **argname, **argval; float32 v; E_INFO("Reading senone-codebook map file: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; n_mgau_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], SPDEF_PARAM_VERSION) != 0) { E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], SPDEF_PARAM_VERSION); } /* HACK!! Convert version# to float32 and take appropriate action */ if (sscanf (argval[i], "%f", &v) != 1) E_FATAL("%s: Bad version no. string: %s\n", file_name, argval[i]); n_mgau_present = (v > 1.1) ? 1 : 0; } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #gauden (if version matches) */ if (n_mgau_present) { if (bio_fread (&(s->n_mgau), sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#gauden) failed\n", file_name); } /* Read 1d array data; s->sen2mgau allocated by called function */ if (bio_fread_1d ((void **)(&s->sen2mgau), sizeof(int32), &(s->n_sen), fp, byteswap, &chksum) < 0) { E_FATAL("bio_fread_1d(%s) failed\n", file_name); } /* Infer n_mgau if not present in this version */ if (! n_mgau_present) { s->n_mgau = 1; for (i = 0; i < s->n_sen; i++) { if (s->sen2mgau[i] >= s->n_mgau) s->n_mgau = s->sen2mgau[i]+1; } } if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); /* Check for validity of mappings */ for (i = 0; i < s->n_sen; i++) { if ((s->sen2mgau[i] >= s->n_mgau) || NOT_MGAUID(s->sen2mgau[i])) E_FATAL("Bad sen2mgau[%d]= %d, out of range [0, %d)\n", i, s->sen2mgau[i], s->n_mgau); } if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read %d->%d senone-codebook mappings\n", s->n_sen, s->n_mgau); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static void build_mgau2sen (senone_t *s, int32 n_cw) { int32 i, j, m, f; s3senid_t *sen; mixw_t *fw; /* Create mgau2sen map from sen2mgau */ s->mgau2sen = (mgau2sen_t *) ckd_calloc (s->n_mgau, sizeof(mgau2sen_t)); s->mgau2sen_idx = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; assert ((m < s->n_mgau) && (m >= 0)); (s->mgau2sen[m].n_sen)++; } sen = (s3senid_t *) ckd_calloc (s->n_sen, sizeof(s3senid_t)); for (m = 0; m < s->n_mgau; m++) { s->mgau2sen[m].sen = sen; sen += s->mgau2sen[m].n_sen; s->mgau2sen[m].n_sen = 0; } for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; j = s->mgau2sen[m].n_sen; s->mgau2sen[m].sen[j] = i; s->mgau2sen_idx[i] = j; (s->mgau2sen[m].n_sen)++; } /* Allocate space for the weights */ for (m = 0; m < s->n_mgau; m++) { fw = (mixw_t *) ckd_calloc (s->n_feat, sizeof(mixw_t)); s->mgau2sen[m].feat_mixw = fw; for (f = 0; f < s->n_feat; f++) { fw[f].n_wt = n_cw; fw[f].prob = (senprob_t **) ckd_calloc_2d (s->mgau2sen[m].n_sen, n_cw, sizeof(senprob_t)); } } } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static int32 senone_mixw_read(senone_t *s, char *file_name, float64 mixwfloor) { FILE *fp; char **argname, **argval; int32 byteswap, chksum_present; uint32 chksum; float32 *pdf; int32 i, j, f, m, c, p, n_sen, n_err, n_cw, nval; char eofchk; mixw_t *fw; int32 pocketsphinx = cmd_ln_boolean("-pocketsphinx"); E_INFO("Reading senone mixture weights: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], MIXW_PARAM_VERSION) != 0) E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], MIXW_PARAM_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #senones, #features, #codewords, arraysize */ n_sen = s->n_sen; if ((bio_fread (&(s->n_sen), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(s->n_feat), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(n_cw), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&nval, sizeof(int32), 1, fp, byteswap, &chksum) != 1)) { E_FATAL("bio_fread(%s) (arraysize) failed\n", file_name); } if ((n_sen != 0) && (s->n_sen != n_sen)) E_FATAL("#senones(%d) conflict with mapping file(%d)\n", s->n_sen, n_sen); if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_feat <= 0) E_FATAL("Bad #features: %d\n", s->n_feat); if (n_cw <= 0) E_FATAL("Bad #mixing-wts/senone: %d\n", n_cw); /* Allocate sen2mgau map if not yet done so (i.e. no explicit mapping file given */ if (! s->sen2mgau) { assert ((s->n_mgau == 0) || (s->n_mgau == 1)); s->sen2mgau = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); if (s->n_mgau == 1) { /* Semicontinuous mode; all senones map to single, shared gaussian: 0 */ for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = 0; } else { /* Fully continuous mode; each senone maps to own parent gaussian */ s->n_mgau = s->n_sen; for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = i; } } else assert (s->n_mgau != 0); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); if (nval != s->n_sen * s->n_feat * n_cw) { E_FATAL("%s: #float32 values(%d) doesn't match dimensions: %d x %d x %d\n", file_name, nval, s->n_sen, s->n_feat, n_cw); } /* * Compute #LSB bits to be dropped to represent mixwfloor with 8 bits. * All PDF values will be truncated (in the LSB positions) by these many bits. */ if ((mixwfloor <= 0.0) || (mixwfloor >= 1.0)) E_FATAL("mixwfloor (%e) not in range (0, 1)\n", mixwfloor); p = logs3(mixwfloor); for (s->shift = 0, p = -p; p >= 256; s->shift++, p >>= 1); if (pocketsphinx) /* PocketSphinx uses a fixed 10-bit shift. */ s->shift = 10; E_INFO("Truncating senone logs3(wt) values by %d bits, to 8 bits\n", s->shift); /* Allocate memory for s->mgau2sen and senone PDF data */ build_mgau2sen (s, n_cw); /* Temporary structure to read in floats */ pdf = (float32 *) ckd_calloc (n_cw, sizeof(float32)); /* Read senone probs data, normalize, floor, convert to logs3, truncate to 8 bits */ n_err = 0; for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; /* Parent mgau */ j = s->mgau2sen_idx[i]; /* Index of senone i within list of senones for mgau m */ fw = s->mgau2sen[m].feat_mixw; for (f = 0; f < s->n_feat; f++) { if (bio_fread((void *)pdf, sizeof(float32), n_cw, fp, byteswap, &chksum) != n_cw) { E_FATAL("bio_fread(%s) (arraydata) failed\n", file_name); } /* Normalize and floor */ if (vector_sum_norm (pdf, n_cw) == 0.0) n_err++; vector_floor (pdf, n_cw, mixwfloor); vector_sum_norm (pdf, n_cw); /* Convert to logs3, truncate to 8 bits, and store in s->pdf */ for (c = 0; c < n_cw; c++) { p = -(logs3(pdf[c])); p += (1 << (s->shift-1)) - 1; /* Rounding before truncation */ if (pocketsphinx) p = (p < (MAX_NEG_MIXW << s->shift)) ? (p >> s->shift) : MAX_NEG_MIXW; /* Trunc/shift */ else p = (p < (255 << s->shift)) ? (p >> s->shift) : 255; /* Trunc/shift */ fw[f].prob[j][c] = p; } } } if (n_err > 0) E_WARN("Weight normalization failed for %d senones\n", n_err); ckd_free (pdf); if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read mixture weights for %d senones: %d features x %d codewords\n", s->n_sen, s->n_feat, n_cw); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ senone_t *senone_init (char *mixwfile, char *sen2mgau_map, float64 mixwfloor) { senone_t *s; s = (senone_t *) ckd_calloc (1, sizeof(senone_t)); s->n_sen = 0; /* As yet unknown */ s->sen2mgau = NULL; assert (sen2mgau_map); if (strcmp (sen2mgau_map, ".semi.") == 0) { /* Not a file; map all senones to a single parent mgau */ s->n_mgau = 1; /* But we don't yet know the #senones */ } else if (strcmp (sen2mgau_map, ".cont.") == 0) { /* Not a file; map each senone to its own distinct parent mgau */ s->n_mgau = 0; /* We don't yet know the #senones */ } else { /* Read mapping file */ senone_mgau_map_read (s, sen2mgau_map); /* Fills in n_sen */ } assert (mixwfile); senone_mixw_read (s, mixwfile, mixwfloor); return s; } #if 0 int32 senone_eval (senone_t *s, s3senid_t sid, int32 f, int32 *dist, int32 n_dist) { int32 i, c, scr, fscr; s3mgauid_t m; mixw_t *fw; m = s->sen2mgau[sid]; assert ((m >= 0) && (m < s->n_mgau)); fw = &(s->mgau2sen[m].feat_mixw[f]); assert (fw->n_wt == n_dist); i = s->mgau2sen_idx[sid]; /* Weight first codeword */ scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } return scr; } void senone_eval_all (senone_t *s, s3mgauid_t m, int32 f, int32 *dist, int32 n_dist, int32 *senscr) { int32 i, c, scr, fscr; s3senid_t sid; mixw_t *fw; fw = &(s->mgau2sen[m].feat_mixw[f]); assert (fw->n_wt == n_dist); for (i = 0; i < s->mgau2sen[m].n_sen; i++) { sid = s->mgau2sen[m].sen[i]; #if 1 /* Weight first codeword */ scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } senscr[sid] += scr; #else senscr[sid] += senone_eval (s, sid, f, dist, n_dist); #endif } } #endif int main (int32 argc, char **argv) { model_def_t *m; float64 wtflr; char *mdeffile, *senfile, *mgaumap, *feattype, *outfile; senone_t *s; parse_cmd_ln(argc, argv); feattype = "s2_4x"; mdeffile = (char *)cmd_ln_access("-moddeffn"); mgaumap = ".semi."; senfile = (char *)cmd_ln_access("-mixwfn"); wtflr = (float64)(*(float32 *)cmd_ln_access("-mwfloor")); outfile = (char *)cmd_ln_access("-sendumpfn"); logs3_init ((float64) 1.0001); feat_init (feattype); model_def_read(&m, mdeffile); s = senone_init (senfile, mgaumap, wtflr); printf("%p\n",s); if (m->n_tied_state != s->n_sen) E_FATAL("#senones different in mdef(%d) and mixw(%d) files\n", m->n_tied_state, s->n_sen); if (cmd_ln_boolean("-pocketsphinx")) { pocketsphinx_senone_dump(m, s, outfile); } else { senone_dump(m, s, outfile); } return 0; } <file_sep>/archive_s3/s3.0/pgm/timealign/align-main.c /* * align-main.c -- Time alignment driver. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 23-Mar-1998 <NAME> (<EMAIL>) at Carnegie Mellon * Added checks between dimensions of various KB components. * Added data (KB) argument to align_utt(). * * 22-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon * Added NULL validation and duplicate-resolution arguments to corpus_load() * call, following a change to that function definition. * * 11-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libfeat/libfeat.h> #include <libmisc/libmisc.h> #include <libmain/cmn.h> #include <libmain/agc.h> #include "align.h" #include "wdnet.h" static arg_t arglist[] = { { "-logbase", ARG_FLOAT32, "1.0001", "Base in which all log values calculated" }, { "-feat", ARG_STRING, "s3_1x39", "Feature type: s3_1x39 / s2_4x / cep_dcep[,%d] / cep[,%d] / %d,%d,...,%d" }, { "-mdeffn", REQARG_STRING, NULL, "Model definition input file" }, { "-dictfn", REQARG_STRING, NULL, "Pronunciation dictionary input file" }, { "-fdictfn", REQARG_STRING, NULL, "Filler word pronunciation dictionary input file" }, { "-compsep", ARG_STRING, "", /* Default: No compound word (NULL separator char) */ "Separator character between components of a compound word (NULL if none)" }, { "-meanfn", REQARG_STRING, NULL, "Mixture gaussian means input file" }, { "-varfn", REQARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to -var file)" }, { "-senmgaufn", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, { "-mixwfn", REQARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to -mixw file)" }, { "-tmatfn", REQARG_STRING, NULL, "HMM state transition matrix input file" }, { "-tmatfloor", ARG_FLOAT32, "0.0001", "HMM state transition probability floor (applied to -tmat file)" }, { "-beam", ARG_FLOAT64, "1e-64", "Main pruning beam" }, { "-mgaubeam", ARG_FLOAT64, "1e-3", "Beam selecting highest scoring components within each mixture Gaussian [0(widest)..1(narrowest)]" }, { "-ctlfn", REQARG_STRING, NULL, "Control file listing utterances to be processed" }, { "-ctloffset", ARG_INT32, "0", "No. of utterances at the beginning of -ctlfn file to be skipped" }, { "-ctlcount", ARG_INT32, "1000000000", /* A big number to approximate the default: "until EOF" */ "No. of utterances to be processed (after -ctloffset)" }, { "-cepdir", ARG_STRING, ".", "Directory of mfc files (for utterances in -ctl file)" }, { "-cepext", ARG_STRING, "mfc", "File extension to be appended to utterances listed in -ctlfn file" }, { "-agc", ARG_STRING, "max", "Automatic Gain Control. max: C0 -= max(C0) in current utt; none: no AGC" }, { "-cmn", ARG_STRING, "current", "Cepstral Mean Normalization. current: C[1..n-1] -= mean(C[1..n-1]) in current utt; none: no CMN" }, { "-insentfn", REQARG_STRING, NULL, "Input transcript file corresponding to utterances in the control file" }, { "-noalt", ARG_INT32, "0", "Do NOT insert alternative pronunciations or compound words if TRUE" }, { "-nosil", ARG_INT32, "0", "Do NOT insert optional silence between transcript words if TRUE" }, { "-nofiller", ARG_INT32, "0", "Do NOT insert optional filler (non-silence) words between transcript words if TRUE" }, { "-wdsegdir", ARG_STRING, NULL, "Output directory for writing word segmentation files; use ,CTL suffix for following control file directory structure" }, { "-wdsegext", ARG_STRING, "wdseg", "File extension for word-segmentation output files" }, { "-s2stsegdir", ARG_STRING, NULL, "Output directory for writing Sphinx-II format state segmentation files; use ,CTL suffix for following control file directory structure" }, { "-s2stsegext", ARG_STRING, "v8_seg", "File extension for Sphinx-II format state segmentation output files" }, { "-outsentfn", ARG_STRING, NULL, "Output transcript file" }, { NULL, ARG_INT32, NULL, NULL } }; static ptmr_t *tm; static int32 tot_frames; #define MAX_TRANS_WORDS 4096 /* * Align a single utterance. Called by the generic driver ctl_process that processes * a control file. */ static void align_utt (void *data, char *uttfile, int32 sf, int32 ef, char *uttid) { char cepfile[4096], outfile[4096]; char *str; char *trans, *wd[MAX_TRANS_WORDS]; /* Transcript */ int32 nwd; int32 noalt, nosil, nofiller; glist_t wnet; /* The word net */ wnode_t *wstart, *wend; /* Dummy start and end nodes in word net */ int32 featwin; int32 nfr; int32 beam; int32 f, i; glist_t stseg, wdseg; /* Alignment result: state/word segmentation */ kb_t *kb; acoustic_t *am; int32 min_utt_frames; printf ("\n"); fflush (stdout); E_INFO("Utterance: %s\n", uttid); kb = (kb_t *) data; am = kb->am; featwin = feat_window_size(am->fcb); f = nfr = 0; wnet = NULL; kb->pnet = NULL; ptmr_reset (tm); ptmr_start (tm); /* Lookup transcript; create private copy and break it up into words */ trans = NULL; if ((str = corpus_lookup (kb->insent, uttid)) == NULL) { E_ERROR("%s: Missing or bad transcript\n", uttid); goto cleanup; } trans = ckd_salloc (str); if ((nwd = str2words (trans, wd, MAX_TRANS_WORDS)) < 0) { E_ERROR("%s: Transcript too long; increase MAX_TRANS_WORDS\n", uttid); goto cleanup; } noalt = *((int32 *) cmd_ln_access ("-noalt")); nosil = *((int32 *) cmd_ln_access ("-nosil")); nofiller = *((int32 *) cmd_ln_access ("-nofiller")); /* Build word net */ wnet = wdnet_build (kb->dict, wd, nwd, noalt, nosil, nofiller, &wstart, &wend); if (! wnet) { E_ERROR("%s: No word net\n", uttid); goto cleanup; } /* Build phone net */ kb->pnet = wnet2pnet (kb->mdef, kb->dict, wnet, wstart, wend, &(kb->pstart), &(kb->pend)); if (! kb->pnet) { E_ERROR("%s: No phone net\n", uttid); goto cleanup; } /* Build complete cepfile name and read cepstrum data */ ctl_infile (cepfile, (char *) cmd_ln_access ("-cepdir"), (char *) cmd_ln_access ("-cepext"), uttfile); if ((nfr = s2mfc_read (cepfile, sf, ef, featwin, am->mfc, S3_MAX_FRAMES)) < 0) { E_ERROR("%s: MFC read failed\n", uttid); goto cleanup; } E_INFO("%s: %d frames\n", uttid, nfr-(featwin<<1)); min_utt_frames = (featwin<<1) + 10; if (nfr < min_utt_frames) { E_ERROR("%s: Utterance shorter than %d frames; ignored\n", uttid, min_utt_frames, nfr); goto cleanup; } /* CMN/AGC */ str = (char *) cmd_ln_access ("-cmn"); if (strcmp (str, "current") == 0) cmn (am->mfc, nfr, feat_cepsize(am->fcb)); str = (char *) cmd_ln_access ("-agc"); if (strcmp (str, "max") == 0) agc_max (am->mfc, nfr); beam = logs3 (*((float64 *) cmd_ln_access ("-beam"))); /* Start search */ align_start (kb, uttid); /* Process each frame; f = running frame no. */ for (i = featwin, f = 0; i < nfr-featwin; i++, f++) { #if 0 if (glist_chkdup (kb->pactive)) E_FATAL("%s: frame %d: Duplicate entry in active pnode list\n", uttid, f); #endif kb->am->senscale[f] = acoustic_eval (kb->am, i); if (align_frame (kb, beam, f, uttid) < 0) break; } /* Obtain recognition result: state segmentation */ stseg = align_end (kb, f, uttid); if (stseg) { /* Output alignment as indicated; Sphinx-II format state segmentation (v8_seg) */ if ((str = (char *) cmd_ln_access ("-s2stsegdir")) != NULL) { ctl_outfile (outfile, str, (char *) cmd_ln_access ("-s2stsegext"), uttfile, uttid); align_write_s2stseg (kb, stseg, outfile, uttid); } /* Get word segmentation */ wdseg = align_st2wdseg (kb, stseg); assert (wdseg); if ((str = (char *) cmd_ln_access ("-wdsegdir")) != NULL) { ctl_outfile (outfile, str, (char *) cmd_ln_access ("-wdsegext"), uttfile, uttid); align_write_wdseg (kb, wdseg, outfile, uttid); } /* Output word transcript */ if (kb->outsentfp) align_write_outsent (kb, wdseg, kb->outsentfp, uttid); align_hypfree (wdseg); align_hypfree (stseg); } else E_ERROR("%s: Alignment failed\n", uttid); cleanup: if (kb->pnet) pnet_free (kb->pnet); if (wnet) wdnet_free (wnet); if (trans) ckd_free (trans); ptmr_stop (tm); f = nfr-(featwin<<1); if (f > 0) { printf ("TMR(%s): %5d frames; %.1fs CPU, %.2f xRT; %.1fs Elapsed, %.2f xRT\n", uttid, f, tm->t_cpu, tm->t_cpu*100.0/f, tm->t_elapsed, tm->t_elapsed*100.0/f); tot_frames += f; } else { printf ("TMR(%s): %5d frames; %.1fs CPU, %.2f xRT; %.1fs Elapsed, %.2f xRT\n", uttid, 0, 0.0, 0.0, 0.0, 0.0); } if (am->tot_mgau_eval > 0) E_INFO("Active components/mgau/frame = %.1f\n", am->tot_dist_valid/am->tot_mgau_eval); am->tot_mgau_eval = 0; am->tot_dist_valid = 0.0; } static void models_init (kb_t *kb) { feat_t *fcb; gauden_t *gau; senone_t *sen; char *str; int32 i; float64 mbeam; logs3_init ( *((float32 *) cmd_ln_access("-logbase")) ); fcb = feat_init ((char *) cmd_ln_access ("-feat")); str = (char *) cmd_ln_access ("-cmn"); if ((strcmp (str, "current") != 0) && (strcmp (str, "none") != 0)) E_FATAL("Unknown -cmn argument(%s); must be current or none\n"); str = (char *) cmd_ln_access ("-agc"); if ((strcmp (str, "max") != 0) && (strcmp (str, "none") != 0)) E_FATAL("Unknown -agc argument(%s); must be max or none\n"); kb->mdef = mdef_init ((char *) cmd_ln_access ("-mdeffn")); str = (char *) cmd_ln_access ("-compsep"); if ((str[0] != '\0') && (str[1] != '\0')) E_FATAL("Compound word separator(%s) must be a single character\n", str); kb->dict = dict_init (kb->mdef, (char *) cmd_ln_access ("-dictfn"), (char *) cmd_ln_access ("-fdictfn"), str[0]); gau = gauden_init ((char *) cmd_ln_access ("-meanfn"), (char *) cmd_ln_access ("-varfn"), *((float32 *) cmd_ln_access ("-varfloor")), TRUE); /* Verify Gaussian density feature type with front end */ if (feat_n_stream(fcb) != gauden_n_stream(gau)) E_FATAL("#Feature streams mismatch: feat(%d), gauden(%d)\n", feat_n_stream(fcb), gauden_n_stream(gau)); for (i = 0; i < feat_n_stream(fcb); i++) { if (feat_stream_len(fcb, i) != gauden_stream_len(gau, i)) E_FATAL("Feature streamlen[%d] mismatch: feat(%d), gauden(%d)\n", i, feat_stream_len(fcb, i), gauden_stream_len(gau, i)); } sen = senone_init ((char *) cmd_ln_access ("-mixwfn"), (char *) cmd_ln_access ("-senmgaufn"), *((float32 *) cmd_ln_access ("-mixwfloor"))); /* Verify senone parameters against gauden parameters */ if (senone_n_stream(sen) != feat_n_stream(fcb)) E_FATAL("#Feature mismatch: feat(%d), senone(%d)\n", feat_n_stream(fcb), senone_n_stream(sen)); if (senone_n_mgau(sen) != gauden_n_mgau(gau)) E_FATAL("#Mixture gaussians mismatch: senone(%d), gauden(%d)\n", senone_n_mgau(sen), gauden_n_mgau(gau)); /* Verify senone parameters against model definition parameters */ if (kb->mdef->n_sen != senone_n_sen(sen)) E_FATAL("#Senones mismatch: Model definition(%d) senone(%d)\n", kb->mdef->n_sen, senone_n_sen(sen)); kb->tmat = tmat_init ((char *) cmd_ln_access ("-tmatfn"), *((float32 *) cmd_ln_access ("-tmatfloor"))); /* Verify transition matrices parameters against model definition parameters */ if (kb->mdef->n_tmat != kb->tmat->n_tmat) E_FATAL("Model definition has %d tmat; but #tmat= %d\n", kb->mdef->n_tmat, kb->tmat->n_tmat); if (kb->mdef->n_emit_state != kb->tmat->n_state) E_FATAL("#Emitting states in model definition = %d, #states in tmat = %d\n", kb->mdef->n_emit_state, kb->tmat->n_state); mbeam = *((float64 *) cmd_ln_access ("-mgaubeam")); if ((kb->am = acoustic_init (fcb, gau, sen, mbeam, S3_MAX_FRAMES)) == NULL) E_FATAL("Acoustic models initialization failed\n"); kb->insent = corpus_load_tailid ((char *) cmd_ln_access ("-insentfn"), NULL, NULL); if (! kb->insent) E_FATAL("Corpus-load(%s) failed\n", (char *) cmd_ln_access ("-insentfn")); if ((str = (char *) cmd_ln_access ("-outsentfn")) != NULL) { if ((kb->outsentfp = fopen(str, "w")) == NULL) E_FATAL("fopen(%s,w) failed\n", str); } else kb->outsentfp = NULL; } main (int32 argc, char *argv[]) { kb_t kb; #if (! WIN32) { char buf[1024]; gethostname (buf, 1024); buf[1023] = '\0'; E_INFO ("%s: Executing on: %s\n", argv[0], buf); } #endif E_INFO("%s: COMPILED ON: %s, AT: %s\n\n", argv[0], __DATE__, __TIME__); cmd_ln_parse (arglist, argc, argv); unlimit (); models_init (&kb); /* Create process-timing object */ tm = (ptmr_t *) ckd_calloc (1, sizeof(ptmr_t)); tot_frames = 0; ctl_process ((char *) cmd_ln_access ("-ctlfn"), *((int32 *) cmd_ln_access ("-ctloffset")), *((int32 *) cmd_ln_access ("-ctlcount")), align_utt, &kb); if (kb.outsentfp) fclose (kb.outsentfp); printf ("\n"); if (tot_frames > 0) { printf ("EXEC SUMMARY: %d frames, %.2fs CPU, %.2f xRT; %.2fs ELAPSED, %.2f xRT\n", tot_frames, tm->t_tot_cpu, tm->t_tot_cpu*100.0/tot_frames, tm->t_tot_elapsed, tm->t_tot_elapsed*100.0/tot_frames); } else printf ("EXEC SUMMARY: 0 frames\n"); fflush (stdout); exit(0); } <file_sep>/archive_s3/s3.2/src/agc.h /* * agc.h -- Various forms of automatic gain control (AGC) * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 28-Apr-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Copied from previous version. */ #ifndef _S3_AGC_H_ #define _S3_AGC_H_ #include <libutil/libutil.h> /* * Apply AGC to the given mfc vectors (normalize all C0 mfc coefficients in the given * input such that the max C0 value is 0, by subtracting the input max C0 from all). * This function operates on an entire utterance at a time. Hence, the entire utterance * must be available beforehand (batchmode). */ void agc_max (float32 **mfc, /* In/Out: mfc[f] = cepstrum vector in frame f */ int32 n_frame); /* In: #frames of cepstrum vectors supplied */ #endif <file_sep>/archive_s3/s3.0/src/libmain/hyp.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * hyp.h -- Hypothesis structures. * * * HISTORY * * 27-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBMAIN_HYP_H_ #define _LIBMAIN_HYP_H_ typedef struct { int32 id; /* Could be s3wid_t, s3cipid_t, etc. To be interpreted only by the client. */ int32 sf, ef; /* Start/end frames, inclusive, for this segment */ int32 ascr; /* Segment acoustic score */ int32 lscr; /* LM score for transition to this segment (if applicable) */ int32 scr; /* Total segment score (ascr+lscr) */ } hyp_t; /* * Log the given hypothesis to the given file. (Kind of a hack! Might not be the right * interface for all situations.) */ void hyp_log (FILE *fp, /* In/Out: File to log to */ glist_t hyplist, /* In: glist of hyp nodes */ char *(*func)(void *kb, int32 id), /* In: Function that provides a string name for the ID in Viterbi history nodes. */ void *kb); /* In: Auxiliary data structure, if any, needed by the above func */ /* * Free the given glist of hyp nodes, including the hyp nodes themselves. */ void hyp_myfree (glist_t hyplist); #endif <file_sep>/archive_s3/s3.0/src/libmain/vithist.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * vithist.h -- Viterbi search history. * * * HISTORY * * 03-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added vithist_sort(). * * 25-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Modified vithist_append() interface to include lmhist. * * 24-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added lmhist field to vithist_t. * * 16-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBMAIN_VITHIST_H_ #define _LIBMAIN_VITHIST_H_ #include <libutil/libutil.h> #include "s3types.h" /* A single node in the Viterbi history */ typedef struct vithist_s { int32 id; /* Could be s3wid_t, s3cipid_t, or anything else; interpreted by the caller or client */ int32 frm; /* Frame at which this history ends */ int32 scr; /* Total path score for for this history */ struct vithist_s *hist; /* Predecessor history entry for backtracking */ struct vithist_s *lmhist; /* Auxiliary Viterbi history field; typically used for locating LM-visible history node if this node is a filler word node. (Recall that filler words are transparent to the LM.) */ } vithist_t; /* * Create a vithist node out of the given information and update the given Viterbi * history list. Return value: the updated history list of vithist_t nodes; i.e., * glist_t->data.ptr is of type (vithist_t *). (Note that the Viterbi history is * traced back via vithist_s.hist info in the glist data, not the glist itself. */ glist_t vithist_append (glist_t hlist, /* In/Out: History list to be updated */ int32 id, /* In: ID info in new history node */ int32 frm, /* In: Frame info in new history node */ int32 score, /* In: Score info in new history node */ vithist_t *hist,/* In: Viterbi predecessor for the new node */ vithist_t *lmhist); /* In: LM-visible history node, if any. If NULL, the lmhist field of the newly created vithist node points to itself. */ /* * Sort the given Viterbi nodes list in descending order of score. * Return value: A new sorted glist if successful; NULL if any error. The old list is not * altered. */ glist_t vithist_sort (glist_t vithist_list); /* In: Vithist nodes to sort by score */ /* * Backtrack through a Viterbi history starting from the given point, build a glist * of hyp_t nodes for the resulting path. * Return value: the glist of hyp_t nodes created. Caller is responsible for finally * freeing this list (using glist_free or glist_myfree(,sizeof(hyp_t))). */ glist_t vithist_backtrace (vithist_t *hist, int32 *senscale); /* * Log the entire Viterbi history to the given file. (Kind of a hack! Might not be the right * interface for all situations.) * Return value: #entries logged. */ int32 vithist_log (FILE *fp, /* In/Out: File to log to */ glist_t *vithist, /* In: vithist[f] = glist of history nodes created @fr f */ int32 nfr, /* #Frames valid in vithist[] */ char *(*func)(void *kb, int32 id), /* In: Function that provides a string name for the ID in Viterbi history nodes. */ void *kb); /* In: Auxiliary data structure, if any, needed by the above func */ #endif <file_sep>/SphinxTrain/src/libs/libcommon/itree.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: itree.c * * Traceability: * * Description: * * Author: * $Author$ *********************************************************************/ #include <s3/itree.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> itree_t * itree_new(uint32 n_cell_hint) { itree_t *new; uint32 i; new = ckd_calloc(1, sizeof(itree_t)); new->cell = ckd_calloc(n_cell_hint, sizeof(cell_t)); for (i = 0; i < n_cell_hint; i++) { new->cell[i].id = NO_ID; new->cell[i].sib = NULL_INDEX; new->cell[i].child = NULL_INDEX; } new->max_n_cell = n_cell_hint; return new; } cell_index_t itree_new_cell(itree_t *t) { assert(t->n_cell < t->max_n_cell); return t->n_cell++; } cell_index_t itree_find(itree_t *t, cell_index_t *end, cell_index_t start, cell_id_t id) { cell_t *cell; cell_index_t i, l = NO_ID, o; cell = t->cell; if (cell[start].id != NO_ID) { for (i = start; (i != NO_ID) && (cell[i].id != id); i = cell[i].sib) l = i; if (i != NO_ID) o = i; else o = NULL_INDEX; } else { o = NULL_INDEX; l = start; } *end = l; return o; } cell_index_t itree_add_sib(itree_t *t, cell_index_t end, cell_id_t id) { cell_index_t new; cell_t *cell; if (t->n_cell == t->max_n_cell) { E_FATAL("index cells exhausted (exceeded the allocated size %d)\n",t->max_n_cell); } new = itree_new_cell(t); cell = t->cell; if (new != 0) /* this is not the first cell, so link it w/ prior */ cell[end].sib = new; cell[new].id = id; cell[new].child = NULL_INDEX; cell[new].sib = NULL_INDEX; return new; } cell_index_t itree_add_child(itree_t *t, cell_index_t parent, cell_id_t id) { cell_index_t end; cell_index_t child; cell_index_t new; cell_t *cell; cell = t->cell; if (cell[parent].child == NO_ID) { new = itree_new_cell(t); cell[parent].child = new; cell[new].id = id; cell[new].sib = NULL_INDEX; cell[new].child = NULL_INDEX; child = new; } else { child = itree_find(t, &end, cell[parent].child, id); if (child == NULL_INDEX) { child = itree_add_sib(t, end, id); } } return child; } cell_index_t itree_find_tri(itree_t *t, cell_id_t left_context, cell_id_t right_context, cell_id_t posn) { cell_index_t end; cell_index_t parent; parent = itree_find(t, &end, 0, left_context); if (parent == NULL_INDEX) { return NULL_INDEX; } parent = itree_find(t, &end, t->cell[parent].child, right_context); if (parent == NULL_INDEX) { return NULL_INDEX; } parent = itree_find(t, &end, t->cell[parent].child, posn); if (parent == NULL_INDEX) { return NULL_INDEX; } return t->cell[parent].child; } cell_id_t itree_add_tri(itree_t *t, cell_id_t left_context, cell_id_t right_context, cell_id_t posn, cell_id_t tri_id) { cell_index_t end; cell_index_t parent; parent = itree_find(t, &end, 0, left_context); if (parent == NULL_INDEX) { parent = itree_add_sib(t, end, left_context); parent = itree_add_child(t, parent, right_context); parent = itree_add_child(t, parent, posn); t->cell[parent].child = tri_id; return parent; } parent = itree_find(t, &end, t->cell[parent].child, right_context); if (parent == NULL_INDEX) { parent = itree_add_sib(t, end, right_context); parent = itree_add_child(t, parent, posn); t->cell[parent].child = tri_id; return parent; } parent = itree_find(t, &end, t->cell[parent].child, posn); if (parent == NULL_INDEX) { parent = itree_add_sib(t, end, posn); t->cell[parent].child = tri_id; return parent; } return parent; } cell_index_t itree_child(itree_t *t, cell_index_t parent) { return t->cell[parent].child; } static itree_t *base = NULL; static cell_index_t left = NULL_INDEX; static cell_index_t right = NULL_INDEX; static cell_index_t posn = NULL_INDEX; cell_id_t itree_enum_init(itree_t *root) { base = root; left = 0; /* first left context */ right = base->cell[left].child; /* first right context, given left */ posn = base->cell[right].child; /* first word posn, given left and right */ return base->cell[posn].child; /* id of first (base left right posn) */ } cell_id_t itree_enum() { cell_index_t nxt; nxt = base->cell[posn].sib; /* get next posn (given left and right) */ if (nxt != NULL_INDEX) { /* exists, so set the posn leaf node to the next one */ posn = nxt; } else { /* no next posn (given left and right) */ /* therefore get the next right context if any */ nxt = base->cell[right].sib; if (nxt != NULL_INDEX) { /* found a next right context, so save it */ right = nxt; /* set the posn to the first position given the new right */ posn = base->cell[right].child; } else { /* no next right context exists */ /* therefore get a new left context if any */ nxt = base->cell[left].sib; if (nxt != NULL_INDEX) { /* a next left context exists so save it */ left = nxt; /* get the first right context given the left */ right = base->cell[left].child; /* get the first posn given the left and right */ posn = base->cell[right].child; } else { return NULL_INDEX; /* no more left contexts, so the whole tree for this base phone has been enumerated */ } } } /* if we arrive here, posn will reference the cell with the next triphone id */ return base->cell[posn].child; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.6 97/06/23 07:41:50 eht * Initialize a variable so compiler won't emit "potentially uninitialized" messages * * Revision 1.5 96/06/17 14:39:22 eht * Removed unused local variables * * Revision 1.4 1996/03/04 15:54:26 eht * Added ability to walk the index trees * * Revision 1.3 1995/10/09 20:56:36 eht * Changes needed for prim_type.h * * Revision 1.2 1995/10/09 15:02:03 eht * Changed ckd_alloc interface to get rid of __FILE__, __LINE__ arguments * * Revision 1.1 1995/06/02 14:52:54 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/wave2feat/fe_internal.h /* ==================================================================== * Copyright (c) 1996-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _FE_INTERNAL_H_ #define _FE_INTERNAL_H_ /** \file fe_internal.h \brief Signal processing functions */ #ifdef __cplusplus extern "C" { #endif #ifndef M_PI #define M_PI (3.14159265358979323846) #endif /* M_PI */ #define FORWARD_FFT 1 #define INVERSE_FFT -1 /** \struct complex \brief A structure to represent complex numbers */ typedef struct { float64 r, i; } complex; /** Build mel filters */ int32 fe_build_melfilters(melfb_t *MEL_FB /**< Input: A mel-frequency banks data structure */ ); /** Compute coefficients for mel cosine transform. The cosine transform is the last step in the cepstra computation. */ int32 fe_compute_melcosine(melfb_t *MEL_FB /**< Input: A mel-frequency bank data structure */ ); /** Convert a frequency in linear scale to mel scale */ float32 fe_mel(float32 x /**< Input: A frequency in linear scale */ ); /** Convert a frequency from mel scale to linear scale */ float32 fe_melinv(float32 x /**< Input: A frequency in mel-scale */ ); /** Add dither to an audio buffer. Dither is a 1/2 bit random number added to prevent zero energy frames, which happens when the audio is a sequence of zeros. */ int32 fe_dither(int16 *buffer, /**< Input: The audio buffer */ int32 nsamps /**< Input: the number of samples */ ); /** Perform pre-emphasis. The pre-emphasis filter is: y[n] = x[n] - factor * x[n-1] */ void fe_pre_emphasis(int16 const *in, /**< Input: The input vector */ float64 *out, /**< Output: The output vector */ int32 len, /**< Input: The length of the input vector in */ float32 factor, /**< Input: The preemphasis factor */ int16 prior /**< Input: The prior sample, either zero or the last sample from the previous buffer */ ); /** Create the hamming window, defined as: in[i] = 0.54 - 0.46 * cos (2 * PI * i / (in_len -1)) */ void fe_create_hamming(float64 *in, int32 in_len); /** Apply the hamming window to the incoming samples */ void fe_hamming_window(float64 *in, /**< Input: The input vector */ float64 *window, /**< Input: The precomputed window */ int32 in_len /**< Input: the length of the input vector in */ ); /** Compute the magnitude of a spectrum */ void fe_spec_magnitude(float64 const *data, /**< Input : The input data */ int32 data_len, /**< Input : The data length */ float64 *spec, /**< Input : The output spectrum */ int32 fftsize /**< Input: The FFT size */ ); /** Compute the feature (cepstrum) from frame (wave) */ int32 fe_frame_to_fea(fe_t *FE, /**< Input: A structure with the front end parameters */ float64 *in, /**< Input: The input audio data */ float64 *fea /**< Output: The output cepstral feature vector */ ); /** Compute the mel spectrum */ void fe_mel_spec(fe_t *FE, /**< Input: A structure with the front end parameters */ float64 const *spec, /**< Input: The spectrum vector */ float64 *mfspec /**< Output: A mel scale spectral vector */ ); /** Compute the mel cepstrum */ int32 fe_mel_cep(fe_t *FE, /**< Input: A structure with the front end parameters */ float64 *mfspec, /**< Input: mel scale spectral vector */ float64 *mfcep /**< Output: mel cepstral vector */ ); /** Fast Fourier Transform using complex numbers */ int32 fe_fft(complex const *in, /**< Input: The complex input vector */ complex *out, /**< Output: The complex output vector */ int32 N, /**< The FFT size */ int32 invert /**< direct FFT if 1 or inverse FFT if -1 */ ); /** Fast Fourier Transform (FFT) using real numbers */ int32 fe_fft_real(float64 *x, /**< Input/Output: The input vector in real numbers */ int n /**< Input: The FFT size */ ); /** Convert short to double. Audio is normally quantized as 2-byte integers. These are converted to floating point for processing. */ void fe_short_to_double(int16 const *in, /**< Input: audio as 2-byte integer */ float64 *out, /**< Output: audio as floating point */ int32 len /**< Input: Number of samples */ ); /** DUPLICATION! Front end specific memory allocation routine Create a 2D array. @return: a d1 x d2 array will be returned */ char **fe_create_2d(int32 d1, /** Input: first dimension*/ int32 d2, /** Input: second dimension*/ int32 elem_size /** Input : the element size */ ); /** DUPLICATION! Front end specific memory delallocation routine */ void fe_free_2d(void **arr /**Input: a 2d matrix to be freed */ ); /** Print the front end parameters used. */ void fe_print_current(fe_t const *FE /** Input: the front end parameters used. */ ); /**Parse parameters used by an application and copies into an internal structure. */ void fe_parse_general_params(param_t const *P, /**Input: front end parameters set by the application */ fe_t *FE /**Output: front end parameters used internally */ ); /**Parse mel frequency parameters from the structure used by the application. */ void fe_parse_melfb_params(param_t const *P, /**Input: front end parameters set by the application */ melfb_t *MEL /**Output: mel filter parameters used internally */ ); #ifdef __cplusplus } #endif #endif /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.14 2006/02/20 23:55:51 egouvea * Moved fe_dither() to the "library" side rather than the app side, so * the function can be code when using the front end as a library. * * Revision 1.13 2006/02/17 00:31:34 egouvea * Removed switch -melwarp. Changed the default for window length to * 0.025625 from 0.256 (so that a window at 16kHz sampling rate has * exactly 410 samples). Cleaned up include's. Replaced some E_FATAL() * with E_WARN() and return. * * Revision 1.12 2006/02/16 00:18:26 egouvea * Implemented flexible warping function. The user can specify at run * time which of several shapes they want to use. Currently implemented * are an affine function (y = ax + b), an inverse linear (y = a/x) and a * piecewise linear (y = ax, up to a frequency F, and then it "breaks" so * Nyquist frequency matches in both scales. * * Added two switches, -warp_type and -warp_params. The first specifies * the type, which valid values: * * -inverse or inverse_linear * -linear or affine * -piecewise or piecewise_linear * * The inverse_linear is the same as implemented by EHT. The -mel_warp * switch was kept for compatibility (maybe remove it in the * future?). The code is compatible with EHT's changes: cepstra created * from code after his changes should be the same as now. Scripts that * worked with his changes should work now without changes. Tested a few * cases, same results. * */ <file_sep>/SphinxTrain/src/programs/init_gau/init_gau.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: init_gau.c * * Description: * Initialize one Gaussian mixtures for each context independent * phone state. * * Author: * <NAME> *********************************************************************/ #include "init_gau.h" #include "accum.h" #include <s3/mk_sseq.h> #include <s3/ck_seg.h> #include <s3/prim_type.h> #include <s3/corpus.h> #include <s3/mk_wordlist.h> #include <s3/mk_phone_list.h> #include <s3/cvt2triphone.h> #include <s3/gauden.h> #include <s3/s3gau_io.h> #include <s3/vector.h> #include <s3/feat.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s3.h> /* ADDITION BY BHIKSHA, TO FACILITATE FEATURES OF ARBITRARY LENGTH, 7jan98 */ #include <s3/s2_param.h> /* END CHANGES BY BHIKSHA */ #include <sys_compat/file.h> #include <stdio.h> #include <assert.h> int init_gau(lexicon_t *lex, model_def_t *mdef) { char *trans = NULL; acmod_set_t *acmod_set; vector_t *mfcc = NULL; uint32 n_frame; uint32 feat_n_frame; uint32 framelen; uint32 tmp; uint16 *seg = NULL; uint32 *sseq = NULL; uint32 *ci_sseq = NULL; uint32 tick_cnt = 0; char **word = NULL; uint32 n_word; acmod_id_t *phone = NULL; uint32 n_phone; char *btw_mark = NULL; vector_t ***mean_acc = NULL; vector_t ***mean = NULL; vector_t ***var_acc = NULL; vector_t ****fullvar_acc = NULL; float32 ***dnom = NULL; const uint32 *veclen; uint32 n_ts; uint32 *r_veclen; uint32 r_n_ts; uint32 r_n_feat; uint32 r_n_density; vector_t **f = NULL; const char *meanfn; uint32 *del_b = NULL; uint32 *del_e = NULL; uint32 n_del = 0; char fn[MAXPATHLEN+1]; /* ADDITION BY BHIKSHA, TO CHECK FOR FEATURE LENGTH, 7 JAN 98 */ uint32 ceplen; /* END ADDITION BY BHIKSHA */ int32 var_is_full = cmd_ln_int32("-fullvar"); if (mdef) { acmod_set = mdef->acmod_set; n_ts = mdef->n_tied_state; } else { acmod_set = NULL; n_ts = 1; /* Global mean/var */ } meanfn = (char *)cmd_ln_access("-meanfn"); veclen = feat_vecsize(); if (meanfn == NULL) { E_INFO("Computing %ux%ux1 mean estimates\n", n_ts, feat_n_stream()); mean_acc = gauden_alloc_param(n_ts, feat_n_stream(), 1, veclen); var_acc = NULL; } else { assert(meanfn != NULL); E_INFO("Computing %ux%ux1 variance estimates\n", n_ts, feat_n_stream()); if (s3gau_read(meanfn, &mean, &r_n_ts, &r_n_feat, &r_n_density, (const uint32 **)&r_veclen) != S3_SUCCESS) { E_FATAL_SYSTEM("Unable to open %s for reading\n", meanfn); } mean_acc = NULL; if (var_is_full) fullvar_acc = gauden_alloc_param_full(n_ts, feat_n_stream(), 1, veclen); else var_acc = gauden_alloc_param(n_ts, feat_n_stream(), 1, veclen); } dnom = (float32 ***)ckd_calloc_3d(n_ts, feat_n_stream(), 1, sizeof(float32)); while (corpus_next_utt()) { if (mfcc) { free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } if (trans) { free(trans); trans = NULL; } if (seg) { free(seg); seg = NULL; } if (word) { ckd_free(word); word = NULL; } if (phone) { ckd_free(phone); phone = NULL; } if (btw_mark) { ckd_free(btw_mark); btw_mark = NULL; } if (ci_sseq) { ckd_free(ci_sseq); ci_sseq = NULL; } if (sseq) { ckd_free(sseq); sseq = NULL; } if (f) { feat_free(f); f = NULL; } if ((++tick_cnt % 100) == 0) { printf("[%u] ", tick_cnt); fflush(stdout); } if (mdef) { if (corpus_get_sent(&trans) != S3_SUCCESS) { E_FATAL("Unable to read word transcript for %s\n", corpus_utt_brief_name()); } if (corpus_get_seg(&seg, &n_frame) != S3_SUCCESS) { E_FATAL("Unable to read Viterbi state segmentation for %s\n", corpus_utt_brief_name()); } word = mk_wordlist(trans, &n_word); phone = mk_phone_list(&btw_mark, &n_phone, word, n_word, lex); /* check to see whether the word transcript and dictionary entries agree with the state segmentation */ if (ck_seg(acmod_set, phone, n_phone, seg, n_frame, corpus_utt()) != S3_SUCCESS) { continue; } /* make a tied state id sequence from the state segmentation and the phone list */ ci_sseq = mk_sseq(seg, n_frame, phone, n_phone, mdef); if (cvt2triphone(acmod_set, phone, btw_mark, n_phone) != S3_SUCCESS) { continue; } /* make a tied state id sequence from the state segmentation and the phone list */ sseq = mk_sseq(seg, n_frame, phone, n_phone, mdef); } /* CHANGE BY BHIKSHA; IF INPUT VECLEN != 13, THEN DO NOT USE THE REGULAR corpus_get_mfcc() WHICH REQUIRES INPUT DATA TO BE 13 DIMENSIONAL CEPSTRA. USE, INSTEAD, THE HACKED VERSION corpus_get_generic_featurevec() WHICH TAKES FEATURES OF ARBITRARY LENGTH 7 JAN 1998 */ ceplen = *(int32 *)cmd_ln_access("-ceplen"); if (ceplen == S2_CEP_VECLEN) { if (corpus_get_mfcc(&mfcc, &tmp, &framelen) != S3_SUCCESS) { E_FATAL("Unable to read MFCC data for %s\n", corpus_utt_brief_name()); } assert(framelen == ceplen); } else { if (corpus_get_generic_featurevec(&mfcc, &tmp, ceplen) < 0) { E_FATAL("Can't read input features\n"); } } /* END CHANGES BY BHIKSHA */ if (mdef == NULL) n_frame = tmp; if (tmp != n_frame) { E_FATAL("# frames in MFCC file inconsistent w/ seg file for utt %s.\n", corpus_utt_brief_name()); } feat_n_frame = n_frame; /* FIXME: This number is bogus, it ought to depend on the type of feature used. */ if (n_frame < 9) { E_WARN("utt %s too short\n", corpus_utt()); if (mfcc) { ckd_free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } continue; } f = feat_compute(mfcc, &feat_n_frame); if (feat_n_frame != n_frame) { E_FATAL("# frames compute != # frames of state seg\n"); } if (del_b) { ckd_free(del_b); } if (del_e) { ckd_free(del_e); } if (corpus_get_sildel(&del_b, &del_e, &n_del) != S3_SUCCESS) { E_ERROR("Unable to get silence deletions for %s\n", corpus_utt()); } if (mean_acc) { /* accumulate mean sums since no estimate given */ accum_state_mean(mean_acc, dnom, f, del_b, del_e, n_del, feat_n_stream(), veclen, sseq, ci_sseq, n_frame); } else if (var_acc) { /* accumulate var sums since mean estimate exists */ accum_state_var(var_acc, mean, dnom, f, del_b, del_e, n_del, feat_n_stream(), veclen, sseq, ci_sseq, n_frame); } else if (fullvar_acc) { /* accumulate var sums since mean estimate exists */ accum_state_fullvar(fullvar_acc, mean, dnom, f, del_b, del_e, n_del, feat_n_stream(), veclen, sseq, ci_sseq, n_frame); } } sprintf(fn, "%s/gauden_counts", (const char *)cmd_ln_access("-accumdir")); if (var_is_full) { if (s3gaucnt_write_full(fn, mean_acc, fullvar_acc, TRUE /* 2-pass variance */, dnom, n_ts, feat_n_stream(), 1, veclen) != 0) { exit(1); } } else { if (s3gaucnt_write(fn, mean_acc, var_acc, TRUE /* 2-pass variance */, dnom, n_ts, feat_n_stream(), 1, veclen) != 0) { exit(1); } } /* free the per utterance data structures from the last utt */ if (mfcc) { free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } if (trans) { free(trans); trans = NULL; } if (seg) { free(seg); seg = NULL; } if (word) { ckd_free(word); word = NULL; } if (phone) { ckd_free(phone); phone = NULL; } if (btw_mark) { ckd_free(btw_mark); btw_mark = NULL; } if (ci_sseq) { ckd_free(ci_sseq); ci_sseq = NULL; } if (sseq) { ckd_free(sseq); sseq = NULL; } if (f) { feat_free(f); f = NULL; } if (mean_acc) { gauden_free_param(mean_acc); } if (var_acc) { gauden_free_param(var_acc); } if (fullvar_acc) { gauden_free_param_full(fullvar_acc); } ckd_free_3d((void ***)dnom); return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2005/11/10 19:31:14 dhdfu * also prevent a double free() when the utt is too short * * Revision 1.6 2005/11/03 04:17:07 dhdfu * Make init_gau use the same (semi-arbitrary) lower bound on the size of * an utterance as bw does, with a comment that this is arbitrary. * Prevents segfaults. * * Revision 1.5 2005/09/27 02:02:47 arthchan2003 * Check whether utterance is too short in init_gau, bw and agg_seg. * * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 1996/08/06 14:13:56 eht * Included missing header files to define prototypes * * Revision 1.6 1996/04/02 17:04:53 eht * Include mk_sseq from libcommon rather than locally * * Revision 1.5 1996/03/25 15:43:07 eht * Deal w/ some memory leaks * * Revision 1.4 1996/02/02 17:33:32 eht * Added estimation of mean/var of CI states when only CD states are present. * * Revision 1.3 1996/01/30 17:11:23 eht * Check return status of read routines * * Revision 1.2 1995/12/14 20:01:53 eht * Yet another development version. Many changes * * Revision 1.1 1995/12/01 20:55:40 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/agg_seg/agg_phn_seg.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: agg_phn_seg.c * * Description: * * Author: * *********************************************************************/ #include "agg_phn_seg.h" #include "mk_seg.h" #include <s3/segdmp.h> #include <s3/corpus.h> #include <s3/mk_wordlist.h> #include <s3/mk_phone_list.h> #include <s3/ck_seg.h> #include <s3/cvt2triphone.h> #include <s3/ckd_alloc.h> #include <s3/feat.h> #include <stdio.h> #include <assert.h> int agg_phn_seg(lexicon_t *lex, acmod_set_t *acmod_set, segdmp_type_t type) { uint16 *seg; unsigned char *ccode; unsigned char *dcode; unsigned char *pcode; unsigned char *ddcode; vector_t *mfcc; vector_t **feat; uint32 n_coeff; uint32 n_frame; uint32 tmp; uint32 tick_cnt; acmod_id_t *phone; uint32 *start; uint32 *len; uint32 n_phone; uint32 s; char *btw_mark; char *trans; char **word; uint32 n_word; uint32 sv_feat = FALSE; uint32 sv_vq = FALSE; uint32 sv_mfcc = FALSE; uint32 n_stream; const uint32 *veclen; tick_cnt = 0; if (type == SEGDMP_TYPE_FEAT) { sv_feat = TRUE; n_stream = feat_n_stream(); veclen = feat_vecsize(); } else if (type == SEGDMP_TYPE_MFCC) { sv_mfcc = TRUE; } else if (type == SEGDMP_TYPE_VQ) { sv_vq = TRUE; } while (corpus_next_utt()) { if ((++tick_cnt % 500) == 0) { printf("[%u] ", tick_cnt); fflush(stdout); } if (corpus_get_sent(&trans) != S3_SUCCESS) { E_FATAL("Unable to read word transcript for %s\n", corpus_utt_brief_name()); } if (corpus_get_seg(&seg, &n_frame) != S3_SUCCESS) { E_FATAL("Unable to read Viterbi state segmentation for %s\n", corpus_utt_brief_name()); } word = mk_wordlist(trans, &n_word); phone = mk_phone_list(&btw_mark, &n_phone, word, n_word, lex); start = ckd_calloc(n_phone, sizeof(uint32)); len = ckd_calloc(n_phone, sizeof(uint32)); /* check to see whether the word transcript and dictionary entries agree with the state segmentation */ if (ck_seg(acmod_set, phone, n_phone, seg, n_frame, corpus_utt()) != S3_SUCCESS) { free(trans); /* alloc'ed using strdup, not ckd_*() */ free(seg); /* alloc'ed using malloc in areadshort(), not ckd_*() */ ckd_free(word); ckd_free(phone); E_ERROR("ck_seg failed"); continue; } if (cvt2triphone(acmod_set, phone, btw_mark, n_phone) != S3_SUCCESS) { free(trans); /* alloc'ed using strdup, not ckd_*() */ free(seg); /* alloc'ed using malloc in areadshort(), not ckd_*() */ ckd_free(word); ckd_free(phone); E_ERROR("cvt2triphone failed"); continue; } ckd_free(btw_mark); if (mk_seg(acmod_set, seg, n_frame, phone, start, len, n_phone) != S3_SUCCESS) { free(trans); free(seg); ckd_free(word); ckd_free(phone); E_ERROR("mk_seg failed"); continue; } if (corpus_provides_ccode()) { /* assume that if it provides ccode, it provides the remaining types */ corpus_get_ccode(&ccode, &tmp); assert(tmp == n_frame); corpus_get_dcode(&dcode, &tmp); assert(tmp == n_frame); corpus_get_pcode(&pcode, &tmp); assert(tmp == n_frame); corpus_get_ddcode(&ddcode, &tmp); assert(tmp == n_frame); for (s = 0; s < n_phone; s++) { segdmp_add_vq(phone[s], &ccode[start[s]], &dcode[start[s]], &pcode[start[s]], &ddcode[start[s]], len[s]); } free(ccode); free(dcode); free(pcode); free(ddcode); } else if (corpus_provides_mfcc()) { if (feat_id() != NO_ID) { corpus_get_mfcc(&mfcc, &n_frame, &n_coeff); feat_set_in_veclen(n_coeff); if (n_frame < 9) { E_WARN("utt %s too short\n", corpus_utt()); if (mfcc) { ckd_free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } continue; } feat = feat_compute(mfcc, &n_frame); for (s = 0; s < n_phone; s++) { segdmp_add_feat(phone[s], &feat[start[s]], len[s]); } feat_free(feat); free(&mfcc[0][0]); ckd_free(mfcc); } else { corpus_get_mfcc(&mfcc, &n_frame, &n_coeff); for (s = 0; s < n_phone; s++) { segdmp_add_mfcc(phone[s], &mfcc[start[s]], len[s], n_coeff); } free(&mfcc[0][0]); ckd_free(mfcc); } } else { E_FATAL("No data type specified\n"); } free(trans); /* alloc'ed using strdup, not ckd_*() */ free(seg); /* alloc'ed using malloc in areadshort(), not ckd_*() */ ckd_free(word); ckd_free(phone); ckd_free(start); ckd_free(len); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2005/09/27 02:02:47 arthchan2003 * Check whether utterance is too short in init_gau, bw and agg_seg. * * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * Revision 1.3 1996/07/29 16:02:57 eht * segdmp module gets n_stream and veclen parameters at initialization time. * No need to pass these as args. * * Revision 1.2 1996/03/25 15:45:23 eht * Development version * * */ <file_sep>/SphinxTrain/src/libs/libio/s3io.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3io.c * * Description: * File I/O functions for SPHINX-III binary files. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3io.h> #include <s3/swap.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define MAX_ATTRIB 128 static char *attrib[MAX_ATTRIB + 1] = { NULL }; static char *value[MAX_ATTRIB + 1] = { NULL }; static int32 alloc[MAX_ATTRIB]; static int32 n_attrib = 0; void s3clr_fattr() { int i; for (i = 0; attrib[i]; i++) { if (alloc[i]) { if (attrib[i]) { free(attrib[i]); } if (value[i]) { free(value[i]); } alloc[i] = FALSE; } } assert(i == n_attrib); n_attrib = 0; attrib[0] = value[0] = NULL; } char * s3get_gvn_fattr(char *a) { int i; for (i = 0; attrib[i] && strcmp(attrib[i], a) != 0; i++); /* value for sentinel is null as well */ assert((attrib[i] != NULL) || (value[i] == NULL)); return value[i]; } void s3get_fattr(char ***out_attrib, char ***out_value) { *out_attrib = attrib; *out_value = value; } void s3add_fattr(char *a, char *v, int dup) { if (n_attrib == MAX_ATTRIB) { E_FATAL("Too many file attributes, increase MAX_ATTRIB\n"); } if (dup) { attrib[n_attrib] = strdup(a); value[n_attrib] = strdup(v); } else { attrib[n_attrib] = a; value[n_attrib] = v; } alloc[n_attrib] = dup; ++n_attrib; attrib[n_attrib] = NULL; value[n_attrib] = NULL; } static int rd_attr_val(FILE *fp, char *attr, char *val) { fscanf(fp, "%s", attr); if (strcmp(attr, "endhdr") == 0) { fgetc(fp); /* throw away newline */ val[0] = '\0'; return 0; } fscanf(fp, " %[^\n]", val); return 1; } static int rd_bin_hdr(FILE *fp, uint32 *swap) { char id[32]; char attrib[256]; char value[8192]; if (fscanf(fp, "%31s", id) != 1) { E_ERROR_SYSTEM("Unable to read the file ID"); return S3_ERROR; } if (strcmp(id, "s3") == 0) { } else { E_ERROR("No SPHINX-III file ID at beginning of file\n"); return S3_ERROR; } s3clr_fattr(); while (rd_attr_val(fp, attrib, value)) { s3add_fattr(attrib, value, TRUE); } switch (swap_check(fp)) { case -1: E_ERROR("Error reading byte order magic number\n"); return S3_ERROR; case 1: *swap = TRUE; break; case 0: *swap = FALSE; break; default: E_FATAL("unexpected result from swap_check()\n"); break; } return S3_SUCCESS; } static int wr_bin_hdr(FILE *fp) { uint32 i; long padding; int ret; if (fprintf(fp, "s3\n") != 3) { E_ERROR_SYSTEM("Error while writing SPHINX-III ID\n"); goto error_loc; } for (i = 0; attrib[i]; i++) { ret = fprintf(fp, "%s %s\n", attrib[i], value[i]); if (ret != (strlen(attrib[i]) + strlen(value[i]) + 2)) { E_ERROR_SYSTEM("Error while attrib/value pair\n"); goto error_loc; } } /* Align to an 8-byte boundary (guarantees natural alignment for * whatever follows) */ padding = ftell(fp) + strlen("endhdr\n"); padding = 8 - (padding & 7); if (padding != 8) { fwrite(" ", 1, padding, fp); } ret = fprintf(fp, "endhdr\n"); if (ret != strlen("endhdr\n")) { E_ERROR_SYSTEM("Error while endhdr marker\n"); goto error_loc; } if (swap_stamp(fp) != S3_SUCCESS) { goto error_loc; } return S3_SUCCESS; error_loc: return S3_ERROR; } int s3close(FILE *fp) { s3clr_fattr(); return fclose(fp); } FILE * s3open(const char *file_name, const char *mode, uint32 *swap) { FILE *fp = NULL; if (mode[0] == 'r' && mode[1] == 'b') { /* Read a binary file */ fp = fopen(file_name, mode); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for reading", file_name); return NULL; } if (rd_bin_hdr(fp, swap) != S3_SUCCESS) { E_ERROR("Error reading header for %s\n", file_name); goto error_loc; } return fp; } else if (mode[0] == 'w' && mode[1] == 'b') { /* Write a binary file */ fp = fopen(file_name, mode); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for writing", file_name); goto error_loc; } if (wr_bin_hdr(fp) != S3_SUCCESS) { goto error_loc; } return fp; } else if (mode[0] == 'a' && mode[1] == 'b') { /* Append to a binary file. */ fp = fopen(file_name, mode); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for appending", file_name); goto error_loc; } if (ftell(fp) == 0) { /* Write a header when no data */ if (wr_bin_hdr(fp) != S3_SUCCESS) { goto error_loc; } } return fp; } error_loc: if (fp) fclose(fp); return NULL; } size_t s3read(void *pointer, size_t size, size_t num_items, FILE *stream, uint32 swap, uint32 *chksum) { size_t ret; size_t i; unsigned char *i8; uint16 *i16; uint32 *i32; uint32 sum; int q,d,r; char *char_pointer = (char *) pointer; /* big reads accross NFS may fail to allow increment reads */ for (d=0,q=num_items; d < num_items; d+=r,q-=r) { r = fread(char_pointer+(d*size), size, (q > 256) ? 256 : q, stream); if (r <= 0) return r; } ret = d; if (swap) { switch (size) { case 1: /* nothing to do */ break; case 2: for (i = 0, i16 = (uint16 *)pointer; i < ret; i++) SWAP_INT16(&i16[i]); break; case 4: for (i = 0, i32 = (uint32 *)pointer; i < ret; i++) SWAP_INT32(&i32[i]); break; default: E_FATAL("Unimplemented size %u for swapping\n", size); } } sum = *chksum; /* update checksum */ switch (size) { case 1: for (i = 0, i8 = (unsigned char *)pointer; i < ret; i++) { sum = (sum << 5 | sum >> 27) + i8[i]; } break; case 2: for (i = 0, i16 = (uint16 *)pointer; i < ret; i++) { sum = (sum << 10 | sum >> 22) + i16[i]; } break; case 4: for (i = 0, i32 = (uint32 *)pointer; i < ret; i++) { sum = (sum << 20 | sum >> 12) + i32[i]; } break; default: E_WARN("Unimplemented size %u for checksum\n", size); } *chksum = sum; return ret; } int s3read_3d(void ****arr, size_t e_sz, uint32 *d1, uint32 *d2, uint32 *d3, FILE *fp, uint32 swap, uint32 *chksum) { uint32 l_d1; uint32 l_d2; uint32 l_d3; uint32 n; void *raw; size_t ret; ret = s3read(&l_d1, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } ret = s3read(&l_d2, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } ret = s3read(&l_d3, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } if (s3read_1d(&raw, e_sz, &n, fp, swap, chksum) != S3_SUCCESS) { return S3_ERROR; } assert(n == l_d1 * l_d2 * l_d3); *arr = ckd_alloc_3d_ptr(l_d1, l_d2, l_d3, raw, e_sz); *d1 = l_d1; *d2 = l_d2; *d3 = l_d3; return S3_SUCCESS; } int s3read_intv_3d(void ****arr, size_t e_sz, uint32 s, uint32 e, uint32 *d1, uint32 *d2, uint32 *d3, FILE *fp, uint32 swap, uint32 *chksum) { uint32 l_d1; uint32 l_d2; uint32 l_d3; uint32 s_d1; uint32 n; void *raw; size_t ret; ret = s3read(&l_d1, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } if ((s >= l_d1) || (e >= l_d1)) { if (s >= l_d1) { E_ERROR("Start, %u, is outside the interval [0 %u]\n", s, l_d1-1); } if (e >= l_d1) { E_ERROR("End, %u, is outside the interval [0 %u]\n", e, l_d1-1); } exit(-1); } ret = s3read(&l_d2, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } ret = s3read(&l_d3, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_3d"); } return S3_ERROR; } /* # of rows in subinterval */ s_d1 = e - s + 1; if (fseek(fp, (long)(s*l_d2*l_d3*e_sz + sizeof(uint32)), SEEK_CUR) < 0) { E_FATAL_SYSTEM("Can't seek in file"); } n = s_d1 * l_d2 * l_d3; raw = ckd_calloc(n, sizeof(float32)); if (s3read(raw, e_sz, n, fp, swap, chksum) != n) { E_FATAL_SYSTEM("Can't read"); } *arr = ckd_alloc_3d_ptr(s_d1, l_d2, l_d3, raw, e_sz); *d1 = s_d1; *d2 = l_d2; *d3 = l_d3; return S3_SUCCESS; } int s3read_2d(void ***arr, size_t e_sz, uint32 *d1, uint32 *d2, FILE *fp, uint32 swap, uint32 *chksum) { uint32 l_d1, l_d2; uint32 n; size_t ret; void *raw; ret = s3read(&l_d1, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_2d"); } return S3_ERROR; } ret = s3read(&l_d2, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_2d"); } return S3_ERROR; } if (s3read_1d(&raw, e_sz, &n, fp, swap, chksum) != S3_SUCCESS) return S3_ERROR; assert(n == l_d1*l_d2); *d1 = l_d1; *d2 = l_d2; *arr = ckd_alloc_2d_ptr(l_d1, l_d2, raw, e_sz); return S3_SUCCESS; } int s3read_1d(void **arr, size_t e_sz, uint32 *d1, FILE *fp, uint32 swap, uint32 *chksum) { uint32 l_d1; size_t ret; void *raw; ret = s3read(&l_d1, sizeof(uint32), 1, fp, swap, chksum); if (ret != 1) { if (ret == 0) { E_ERROR("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_1d"); } return S3_ERROR; } raw = ckd_calloc(l_d1, e_sz); ret = s3read(raw, e_sz, l_d1, fp, swap, chksum); if (ret != l_d1) { if (ret == 0) { E_ERROR("Unable to read complete data"); } else { E_ERROR_SYSTEM("OS error in s3read_1d"); } return S3_ERROR; } *d1 = l_d1; *arr = raw; return S3_SUCCESS; } size_t s3write(const void *pointer, size_t size, size_t num_items, FILE *stream, uint32 *chksum) { uint32 sum; unsigned char *i8; uint16 *i16; uint32 *i32; size_t i; size_t q,r,d; char *char_pointer = (char *)pointer; sum = *chksum; /* update checksum over the given data items */ switch (size) { case 1: for (i = 0, i8 = (unsigned char *)pointer; i < num_items; i++) { /* rotate prior checksum by 5 bits and add data */ sum = (sum << 5 | sum >> 27) + i8[i]; } break; case 2: for (i = 0, i16 = (uint16 *)pointer; i < num_items; i++) { /* rotate prior checksum by 10 bits and add data */ sum = (sum << 10 | sum >> 22) + i16[i]; } break; case 4: for (i = 0, i32 = (uint32 *)pointer; i < num_items; i++) { /* rotate prior checksum by 20 bits and add data */ sum = (sum << 20 | sum >> 12) + i32[i]; } break; default: E_WARN("Unimplemented size %u for checksum\n", size); } *chksum = sum; /* big writes may not work across NFS so allow for them incrementally */ for (q=num_items,d=0; q > 0; d+=r,q-=r) { r = fwrite(char_pointer+(d*size), size, (q > 256) ? 256 : q, stream); if (r <= 0) return r; } return num_items; } int s3write_3d(void ***arr, size_t e_sz, uint32 d1, uint32 d2, uint32 d3, FILE *fp, uint32 *chksum) { size_t ret; /* write out first dimension 1 */ ret = s3write(&d1, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_3d"); } return S3_ERROR; } /* write out first dimension 2 */ ret = s3write(&d2, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_3d"); } return S3_ERROR; } /* write out first dimension 3 */ ret = s3write(&d3, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_3d"); } return S3_ERROR; } /* write out the data in the array as one big block */ if (s3write_1d(arr[0][0], e_sz, d1*d2*d3, fp, chksum) != S3_SUCCESS) { return S3_ERROR; } return S3_SUCCESS; } int s3write_2d(void **arr, size_t e_sz, uint32 d1, uint32 d2, FILE *fp, uint32 *chksum) { size_t ret; ret = s3write(&d1, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_2d"); } return S3_ERROR; } ret = s3write(&d2, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_2d"); } return S3_ERROR; } if (s3write_1d(arr[0], e_sz, d1*d2, fp, chksum) != S3_SUCCESS) { return S3_ERROR; } return S3_SUCCESS; } int s3write_1d(void *arr, size_t e_sz, uint32 d1, FILE *fp, uint32 *chksum) { size_t ret; ret = s3write(&d1, sizeof(uint32), 1, fp, chksum); if (ret != 1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_1d"); } return S3_ERROR; } ret = s3write(arr, e_sz, d1, fp, chksum); if (ret != d1) { if (ret == 0) { E_ERROR_SYSTEM("Unable to write complete data"); } else { E_ERROR_SYSTEM("OS error in s3write_1d"); } return S3_ERROR; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.6 2003/11/30 06:26:49 egouvea * Undid last change * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/02/20 00:28:35 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/misc/vq.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * vq.c -- Vector quantization to quantize <mean,var> pairs of each dimension * of all codebooks put together. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 20-Aug-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ /* * To compile: * cc -O2 -o vq -I$S3/include -I$S3/src -L$S3/lib/alpha vq.c -lutil -lio -lm * where, $S3 is the s3 root directory. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <libutil/libutil.h> #include <libio/libio.h> static timing_t *tmg; static void vq_dump (float32 **cb, int32 vqsize, int32 veclen) { FILE *fp; int32 c, i; if ((fp = fopen("vq.out", "w")) == NULL) { E_ERROR("fopen(vq.out,w) failed\n"); return; } for (c = 0; c < vqsize; c++) { for (i = 0; i < veclen; i++) fprintf (fp, " %12.6e", cb[c][i]); fprintf (fp, "\n"); } fclose (fp); } /* * Create an initial quantization of pt[0..n_pt-1][0..veclen-1] into * cb[0..vqsize-1][0..veclen-1], by choosing vqsize distinct points from pt[][]. */ static void vq_init (float32 **pt, float32 **cb, int32 n_pt, int32 vqsize, int32 veclen) { int32 i, j, k, d, dd, **tmp; /* Choose a stride into pt[] for selecting the initial codebook points */ dd = n_pt / vqsize; dd -= (dd>>3); /* Choose a pseudo-random initial starting point */ tmp = (int32 **) pt; for (i = 0; i < n_pt; i++) { for (d = 0; (d < veclen) && (tmp[i][d] == 0); d++); if (d < veclen) break; } j = tmp[i][d] % 113; if (j < 0) j = -j; /* Select the vqsize initial VQ points */ for (i = 0; i < vqsize; i++) { for (; j < n_pt; j += dd) { /* Make sure the next point considered is not alredy in the VQ list */ for (k = 0; k < i; k++) { for (d = 0; d < veclen; d++) { if (cb[k][d] != pt[j][d]) break; } if (d >= veclen) /* This point already in VQ list */ break; } if (k >= i) /* This point not in VQ list; can be added */ break; } assert (j < n_pt); for (d = 0; d < veclen; d++) cb[i][d] = pt[j][d]; j += dd; } E_INFO("Initialization finished at %d out of %d\n", j, n_pt); } /* * Euclidean distance (squared) between two vectors. */ static float64 vecdist (float32 *v1, float32 *v2, int32 veclen) { float64 d; int32 i; d = 0.0; for (i = 0; i < veclen; i++) d += (v1[i] - v2[i]) * (v1[i] - v2[i]); return d; } /* * Quantize pt[0..n_pt-1][0..veclen-1] into cb[0..vqsize-1][0..veclen-1] (where * vqsize < n_pt, presumably). Do this with the following iterative procedure: * 1. Choose an initial VQ codebook by selecting vqsize random points from pt. * 2. Map each point in pt to the "nearest" codebook entry (currently based on * Euclidean distance. * 3. Re-estimate each VQ entry by taking the centroid of all pt entries mapped * to it in step 2. * 4. Repeat steps 2 and 3 until the "total error stabilizes". * In the end, replace each point in pt with the nearest VQ value. * Return value: final total error. */ static float64 vq (float32 **pt, float32 **cb, int32 n_pt, int32 vqsize, int32 veclen) { int32 p, c, i, iter, bestc, *pt2cb, *n_newcb; float64 d, bestdist, err, prev_err; float32 **newcb; E_INFO("Clustering %d points into %d\n", n_pt, vqsize); /* Allocate some temporary variables */ pt2cb = (int32 *) ckd_calloc (n_pt, sizeof(int32)); newcb = (float32 **)ckd_calloc_2d (vqsize, veclen, sizeof(float32)); n_newcb = (int32 *) ckd_calloc (vqsize, sizeof(int32)); /* Choose an initial codebook */ vq_init (pt, cb, n_pt, vqsize, veclen); for (iter = 0;; iter++) { timing_start (tmg); /* Map each point to closest codebook entry (using Euclidean distance metric) */ err = 0.0; for (p = 0; p < n_pt; p++) { bestdist = 1e+200; for (c = 0; c < vqsize; c++) { d = vecdist (pt[p], cb[c], veclen); if (d < bestdist) { bestdist = d; bestc = c; } } pt2cb[p] = bestc; err += bestdist; } /* Update codebook entries with centroid of mapped points */ for (c = 0; c < vqsize; c++) { for (i = 0; i < veclen; i++) newcb[c][i] = 0.0; n_newcb[c] = 0; } for (p = 0; p < n_pt; p++) { c = pt2cb[p]; for (i = 0; i < veclen; i++) newcb[c][i] += pt[p][i]; n_newcb[c]++; } for (c = 0; c < vqsize; c++) { if (n_newcb[c] == 0) E_ERROR("Nothing mapped to codebook entry %d; entry not updated\n", c); else { float64 t; t = 1.0 / n_newcb[c]; for (i = 0; i < veclen; i++) cb[c][i] = newcb[c][i] * t; } } timing_stop (tmg); E_INFO("%4d: Error = %e, %.2f sec CPU, %.2f sec elapsed\n", iter, err, tmg->t_cpu, tmg->t_elapsed); timing_reset (tmg); /* Check if VQ codebook converged */ if (iter > 10) { if ((err == 0.0) || ((prev_err - err)/prev_err < 0.002)) break; } prev_err = err; } /* Replace points with nearest VQ entries created */ for (p = 0; p < n_pt; p++) { c = pt2cb[p]; for (i = 0; i < veclen; i++) pt[p][i] = cb[c][i]; } ckd_free (pt2cb); ckd_free_2d ((void **) newcb); ckd_free (n_newcb); return err; } /* * gauden_param_read taken from s3/src/libfbs. * gauden_param_write modelled after gauden_param_read. */ #define GAUDEN_PARAM_VERSION "0.1" static int32 gauden_param_read(float32 *****out_param, int32 *out_n_mgau, int32 *out_n_feat, int32 *out_n_density, int32 **out_veclen, const char *file_name) { char version[1024], tmp; FILE *fp; int32 i, j, k, l, blk, n; int32 n_mgau; int32 n_feat; int32 n_density; int32 *veclen; int32 needs_reorder; float32 ****out; float32 *buf; E_INFO("Reading mixture gaussian parameter: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); if (fscanf(fp, "%s", version) != 1) E_FATAL("Unable to read version id\n"); if (strcmp(version, GAUDEN_PARAM_VERSION) != 0) E_FATAL("Version mismatch: %s, expecting %s\n", version, GAUDEN_PARAM_VERSION); if (bcomment_read(fp) != S3_SUCCESS) E_FATAL("bcomment_read() failed\n"); if ((needs_reorder = swap_check(fp)) < 0) E_FATAL("swap_check() failed\n"); /* #Codebooks */ if (fread_retry(&n_mgau, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #codebooks\n"); if (needs_reorder) { SWAP_INT32(&n_mgau); } *out_n_mgau = n_mgau; /* #Features/codebook */ if (fread_retry(&n_feat, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #features/codebook\n"); if (needs_reorder) { SWAP_INT32(&n_feat); } *out_n_feat = n_feat; /* #Gaussian densities/feature in each codebook */ if (fread_retry(&n_density, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #densities/codebook-feature\n"); if (needs_reorder) { SWAP_INT32(&n_density); } *out_n_density = n_density; /* #Dimensions in each feature stream */ veclen = ckd_calloc(n_feat, sizeof(uint32)); *out_veclen = veclen; if (fread_retry(veclen, sizeof(uint32), n_feat, fp) != n_feat) E_FATAL("Error reading feature vector lengths\n"); if (needs_reorder) { for (i = 0; i < n_feat; i++) SWAP_INT32(&veclen[i]); } /* blk = total vector length of all feature streams */ for (i = 0, blk = 0; i < n_feat; i++) blk += veclen[i]; /* #Floats to follow; for the ENTIRE SET of CODEBOOKS */ if (fread_retry(&n, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #floats\n"); if (needs_reorder) { SWAP_INT32(&n); } assert(n == n_mgau * n_density * blk); /* Allocate memory for mixture gaussian densities */ out = (float32 ****) ckd_calloc_3d (n_mgau, n_feat, n_density, sizeof(float32 *)); buf = (float32 *) ckd_calloc (n, sizeof(float)); for (i = 0, l = 0; i < n_mgau; i++) { for (j = 0; j < n_feat; j++) { for (k = 0; k < n_density; k++) { out[i][j][k] = &buf[l]; l += veclen[j]; } } } /* Read mixture gaussian densities data */ if (fread_retry (buf, sizeof(float32), n, fp) != n) E_FATAL("Error reading gaussian data\n"); if (needs_reorder) for (i = 0; i < n; i++) SWAP_FLOAT32(&buf[i]); E_INFO("%d codebook, %d feature, size", n_mgau, n_feat); for (i = 0; i < n_feat; i++) printf (" %dx%d", n_density, veclen[i]); printf ("\n"); if (fread (&tmp, 1, 1, fp) == 1) E_WARN("Non-empty file beyond end of data\n"); *out_param = out; fclose(fp); return 0; } static int32 gauden_param_write(float32 ****param, int32 n_mgau, int32 n_feat, int32 n_density, int32 *veclen, const char *file_name) { FILE *fp; int32 i, k, blk; E_INFO("Writing mixture gaussian parameter: %s\n", file_name); if ((fp = fopen(file_name, "wb")) == NULL) E_FATAL_SYSTEM("fopen(%s,wb) failed\n", file_name); fprintf (fp, "%s\n", GAUDEN_PARAM_VERSION); fprintf (fp, "*end_comment*\n"); k = (int32)BYTE_ORDER_MAGIC; fwrite (&k, sizeof(int32), 1, fp); /* #Codebooks */ k = n_mgau; fwrite (&k, sizeof(int32), 1, fp); /* #Features/codebook */ k = n_feat; fwrite (&k, sizeof(int32), 1, fp); /* #Gaussian densities/feature in each codebook */ k = n_density; fwrite (&k, sizeof(int32), 1, fp); /* #Dimensions in each feature stream */ fwrite (veclen, sizeof(int32), n_feat, fp); /* blk = total vector length of all feature streams */ for (i = 0, blk = 0; i < n_feat; i++) blk += veclen[i]; /* #Floats to follow; for the ENTIRE SET of CODEBOOKS */ k = n_mgau * n_density * blk; fwrite (&k, sizeof(int32), 1, fp); /* Read mixture gaussian densities data */ fwrite (&(param[0][0][0][0]), sizeof(float32), k, fp); fclose(fp); return 0; } /* * Read mean and variance S3-format files and cluster them as follows: * assume single feature vector * for each dimension of feature vector { * create list of <mean,var> pairs in the entire codebook set (for that dimension); * // HACK!! 0 vectors omitted from the above list * VQ cluster this list into the given number of vqsize points; * replace codebook entries with nearest clustered values (for that dimension); * // HACK!! 0 vectors remain untouched * } * write remapped codebooks to files "mean-vq" and "var-vq"; */ main (int32 argc, char *argv[]) { float32 ****mean, ****var; int32 n_cb, n_feat, n_den, *featlen; int32 i, j, c, w, dim, p, n_pt, vqsize; float32 **pt, **cb; float64 err; FILE *fp; if ((argc < 4) || (sscanf (argv[3], "%d", &vqsize) != 1)) E_FATAL("Usage: %s meanfile varfile vqsize\n", argv[0]); if (argc > 4) { if ((fp = fopen(argv[4], "w")) != NULL) { *stdout = *fp; *stderr = *fp; } else E_ERROR("fopen(%s,w) failed\n", argv[4]); } gauden_param_read (&mean, &n_cb, &n_feat, &n_den, &featlen, argv[1]); E_INFO("%s: %d x %d x %d ", argv[1], n_cb, n_feat, n_den); for (i = 0; i < n_feat; i++) printf (" %d", featlen[i]); printf ("\n"); gauden_param_read (&var, &n_cb, &n_feat, &n_den, &featlen, argv[2]); E_INFO("%s: %d x %d x %d ", argv[2], n_cb, n_feat, n_den); for (i = 0; i < n_feat; i++) printf (" %d", featlen[i]); printf ("\n"); assert (n_feat == 1); n_pt = n_cb * n_den; pt = (float32 **) ckd_calloc_2d (n_pt, 2, sizeof(float32)); cb = (float32 **) ckd_calloc_2d (vqsize, 2, sizeof(float32)); tmg = timing_new (); /* VQ each column of mean,var pair (assuming just one feature vector) */ for (dim = 0; dim < featlen[0]; dim++) { j = 0; for (c = 0; c < n_cb; c++) { for (w = 0; w < n_den; w++) { if ((mean[c][0][w][dim] != 0.0) || (var[c][0][w][dim] != 0.0)) { pt[j][0] = mean[c][0][w][dim]; pt[j][1] = var[c][0][w][dim]; j++; } } } err = vq (pt, cb, j, vqsize, 2); vq_dump (cb, vqsize, 2); j = 0; for (c = 0; c < n_cb; c++) { for (w = 0; w < n_den; w++) { if ((mean[c][0][w][dim] != 0.0) || (var[c][0][w][dim] != 0.0)) { mean[c][0][w][dim] = pt[j][0]; var[c][0][w][dim] = pt[j][1]; j++; } } } E_INFO("%d values quantized for dimension %d; error = %e\n", j, dim, err); } fflush (fp); gauden_param_write (mean, n_cb, n_feat, n_den, featlen, "mean-vq"); gauden_param_write (var, n_cb, n_feat, n_den, featlen, "var-vq"); fflush (fp); exit(0); } <file_sep>/SphinxTrain/src/libs/libio/s3acc_io.c /* ==================================================================== * Copyright (c) 1995-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3acc_io.c * * Description: * Reading routines for the accumulators. * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3acc_io.h> #include <s3/s3tmat_io.h> #include <s3/s3mixw_io.h> #include <s3/s3gau_io.h> #include <s3/matrix.h> #include <s3/s3io.h> #include <s3/gauden.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <sys_compat/misc.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> static int ck_readable(const char *fn) { FILE *fp; fp = fopen(fn, "rb"); if (fp != NULL) { fclose(fp); return TRUE; } else { return FALSE; } } int rdacc_tmat(const char *dir, float32 ****inout_tmat_acc, uint32 *inout_n_tmat, uint32 *inout_n_state_pm) { char fn[MAXPATHLEN+1]; float32 ***in_tmat_acc; float32 ***tmat_acc; uint32 n_tmat; uint32 n_state_pm; sprintf(fn, "%s/tmat_counts", dir); if (ck_readable(fn)) { if (s3tmat_read(fn, &in_tmat_acc, &n_tmat, &n_state_pm) != S3_SUCCESS) { return S3_ERROR; } tmat_acc = *inout_tmat_acc; if (tmat_acc == NULL) { *inout_tmat_acc = tmat_acc = in_tmat_acc; *inout_n_tmat = n_tmat; *inout_n_state_pm = n_state_pm; } else { int err = FALSE; if (*inout_n_tmat != n_tmat) { E_ERROR("# tmat in, %u != prior # tmat, %u\n", n_tmat, *inout_n_tmat); err = TRUE; } if (*inout_n_state_pm != n_state_pm) { E_ERROR("# tmat in, %u != prior # tmat, %u\n", n_state_pm, *inout_n_state_pm); err = TRUE; } if (err) return S3_ERROR; accum_3d(tmat_acc, in_tmat_acc, n_tmat, n_state_pm-1, n_state_pm); ckd_free_3d((void ***)in_tmat_acc); } } else { E_ERROR("Unable to access %s\n", fn); return S3_ERROR; } return S3_SUCCESS; } int rdacc_mixw(const char *dir, float32 ****inout_mixw_acc, uint32 *inout_n_mixw, uint32 *inout_n_stream, uint32 *inout_n_density) { char fn[MAXPATHLEN+1]; float32 ***in_mixw_acc; float32 ***mixw_acc; uint32 n_mixw; uint32 n_stream; uint32 n_density; sprintf(fn, "%s/mixw_counts", dir); if (ck_readable(fn)) { if (s3mixw_read(fn, &in_mixw_acc, &n_mixw, &n_stream, &n_density) != S3_SUCCESS) { return S3_ERROR; } mixw_acc = *inout_mixw_acc; if (mixw_acc == NULL) { *inout_mixw_acc = mixw_acc = in_mixw_acc; *inout_n_mixw = n_mixw; *inout_n_stream = n_stream; *inout_n_density = n_density; } else { int err = FALSE; if (*inout_n_mixw != n_mixw) { E_ERROR("# mixw in file %s (== %u) != prior # mixw (== %u)\n", fn, n_mixw, *inout_n_mixw); err = TRUE; } if (*inout_n_stream != n_stream) { E_ERROR("# stream in file %s (== %u) != prior # stream (== %u)\n", fn, n_stream, *inout_n_stream); err = TRUE; } if (*inout_n_density != n_density) { E_ERROR("# density comp/mix in file %s (== %u) != prior # density (== %u)\n", fn, n_density, *inout_n_density); err = TRUE; } if (err) return S3_ERROR; accum_3d(mixw_acc, in_mixw_acc, n_mixw, n_stream, n_density); ckd_free_3d((void ***)in_mixw_acc); } } else { E_ERROR("Unable to access %s\n", fn); return S3_ERROR; } return S3_SUCCESS; } int rdacc_den(const char *dir, vector_t ****inout_wt_mean, vector_t ****inout_wt_var, int32 *inout_pass2var, float32 ****inout_dnom, uint32 *inout_n_mgau, uint32 *inout_n_stream, uint32 *inout_n_density, const uint32 **inout_veclen) { char fn[MAXPATHLEN+1]; vector_t ***in_wt_mean; vector_t ***wt_mean; vector_t ***in_wt_var; vector_t ***wt_var; float32 ***in_dnom; float32 ***dnom; uint32 n_mgau; uint32 n_stream; uint32 n_density; const uint32 *veclen; const uint32 *in_veclen; int32 pass2var; int i; sprintf(fn, "%s/gauden_counts", dir); if (ck_readable(fn)) { if (s3gaucnt_read(fn, &in_wt_mean, &in_wt_var, &pass2var, &in_dnom, &n_mgau, &n_stream, &n_density, &in_veclen) != S3_SUCCESS) { fflush(stdout); perror(fn); return S3_ERROR; } wt_mean = *inout_wt_mean; wt_var = *inout_wt_var; dnom = *inout_dnom; veclen = *inout_veclen; if (wt_mean == NULL) { /* if a gauden_counts file exists, it will have reestimated means */ *inout_wt_mean = wt_mean = in_wt_mean; *inout_dnom = dnom = in_dnom; *inout_n_mgau = n_mgau; *inout_n_stream = n_stream; *inout_n_density = n_density; *inout_veclen = in_veclen; *inout_pass2var = pass2var; if (wt_var == NULL && in_wt_var != NULL) { *inout_wt_var = wt_var = in_wt_var; } } else { int err = FALSE; /* check if matrices are able to be added */ if (*inout_n_mgau != n_mgau) { E_ERROR("# mix. Gau. for file %s (== %u) != prior # mix. Gau. (== %u)\n", fn, n_mgau, *inout_n_mgau); err = TRUE; } if (*inout_n_stream != n_stream) { E_ERROR("# stream for file %s (== %u) != prior # stream (== %u)\n", fn, n_stream, *inout_n_stream); err = TRUE; } if (*inout_n_density != n_density) { E_ERROR("# density comp/mix for file %s (== %u) != prior # density, %u\n", fn, n_density, *inout_n_density); err = TRUE; } if (*inout_pass2var != pass2var) { E_ERROR("2 pass var %s in %s, but %s in others.\n", fn, (pass2var ? "true" : "false"), (*inout_pass2var ? "true" : "false")); err = TRUE; } for (i = 0; i < n_stream; i++) { if (veclen[i] != in_veclen[i]) { E_ERROR("vector length of stream %u (== %u) != prior length (== %u)\n", i, in_veclen[i], veclen[i]); err = TRUE; } } ckd_free((void *)in_veclen); if (err) return S3_ERROR; /* accumulate values */ accum_3d(dnom, in_dnom, n_mgau, n_stream, n_density); gauden_accum_param(wt_mean, in_wt_mean, n_mgau, n_stream, n_density, veclen); gauden_free_param(in_wt_mean); if (wt_var) { assert(in_wt_var); gauden_accum_param(wt_var, in_wt_var, n_mgau, n_stream, n_density, veclen); gauden_free_param(in_wt_var); } } } else { E_ERROR("Unable to access %s\n", fn); return S3_ERROR; } return S3_SUCCESS; } int rdacc_den_full(const char *dir, vector_t ****inout_wt_mean, vector_t *****inout_wt_var, int32 *inout_pass2var, float32 ****inout_dnom, uint32 *inout_n_mgau, uint32 *inout_n_stream, uint32 *inout_n_density, const uint32 **inout_veclen) { char fn[MAXPATHLEN+1]; vector_t ***in_wt_mean; vector_t ***wt_mean; vector_t ****in_wt_var; vector_t ****wt_var; float32 ***in_dnom; float32 ***dnom; uint32 n_mgau; uint32 n_stream; uint32 n_density; const uint32 *veclen; const uint32 *in_veclen; int32 pass2var; int i; sprintf(fn, "%s/gauden_counts", dir); if (ck_readable(fn)) { if (s3gaucnt_read_full(fn, &in_wt_mean, &in_wt_var, &pass2var, &in_dnom, &n_mgau, &n_stream, &n_density, &in_veclen) != S3_SUCCESS) { fflush(stdout); perror(fn); return S3_ERROR; } wt_mean = *inout_wt_mean; wt_var = *inout_wt_var; dnom = *inout_dnom; veclen = *inout_veclen; if (wt_mean == NULL) { /* if a gauden_counts file exists, it will have reestimated means */ *inout_wt_mean = wt_mean = in_wt_mean; *inout_dnom = dnom = in_dnom; *inout_n_mgau = n_mgau; *inout_n_stream = n_stream; *inout_n_density = n_density; *inout_veclen = in_veclen; *inout_pass2var = pass2var; if (wt_var == NULL && in_wt_var != NULL) { *inout_wt_var = wt_var = in_wt_var; } } else { int err = FALSE; /* check if matrices are able to be added */ if (*inout_n_mgau != n_mgau) { E_ERROR("# mix. Gau. for file %s (== %u) != prior # mix. Gau. (== %u)\n", fn, n_mgau, *inout_n_mgau); err = TRUE; } if (*inout_n_stream != n_stream) { E_ERROR("# stream for file %s (== %u) != prior # stream (== %u)\n", fn, n_stream, *inout_n_stream); err = TRUE; } if (*inout_n_density != n_density) { E_ERROR("# density comp/mix for file %s (== %u) != prior # density, %u\n", fn, n_density, *inout_n_density); err = TRUE; } if (*inout_pass2var != pass2var) { E_ERROR("2 pass var %s in %s, but %s in others.\n", fn, (pass2var ? "true" : "false"), (*inout_pass2var ? "true" : "false")); err = TRUE; } for (i = 0; i < n_stream; i++) { if (veclen[i] != in_veclen[i]) { E_ERROR("vector length of stream %u (== %u) != prior length (== %u)\n", i, in_veclen[i], veclen[i]); err = TRUE; } } ckd_free((void *)in_veclen); if (err) return S3_ERROR; /* accumulate values */ accum_3d(dnom, in_dnom, n_mgau, n_stream, n_density); gauden_accum_param(wt_mean, in_wt_mean, n_mgau, n_stream, n_density, veclen); gauden_free_param(in_wt_mean); if (wt_var) { assert(in_wt_var); gauden_accum_param_full(wt_var, in_wt_var, n_mgau, n_stream, n_density, veclen); gauden_free_param_full(in_wt_var); } } } else { E_ERROR("Unable to access %s\n", fn); return S3_ERROR; } return S3_SUCCESS; } <file_sep>/share/acoustic/tidigits/make-ascii-zip #!/bin/sh # Copyright 1999-2002 Carnegie Mellon University. # Portions Copyright 2002 Sun Microsystems, Inc. # Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. # All Rights Reserved. Use is subject to license terms. # # See the file "license.terms" for information on usage and # redistribution of this file, and for a DISCLAIMER OF ALL # WARRANTIES. # # Creates the ASCII form of the TIDIGITS acoustic model suitable # for use with Sphinx 4. TIDIGITS refers to: # # "NIST CD-ROM Version of the Texas Instruments-developed Studio Quality # Speaker-Independent Connected-Digit Corpus" # ASCII_ZIP=tidigits_8gau_13dCep_16k_40mel_130Hz_6800Hz.ascii.zip # where the WSJ acoustic model directory is, modify as you need MODEL_DIR=/lab/speech/sphinx4/data/tidigits_model PWD=`pwd` rm -f ${ASCII_ZIP} cd $MODEL_DIR zip -r ${ASCII_ZIP} README am.props license.terms unigram.lm unigram.lm.DMP dictionary fillerdict wd_dependent_phone.500.mdef wd_dependent_phone.cd_continuous_8gau/means.ascii wd_dependent_phone.cd_continuous_8gau/mixture_weights.ascii wd_dependent_phone.cd_continuous_8gau/transition_matrices.ascii wd_dependent_phone.cd_continuous_8gau/variances.ascii mv $ASCII_ZIP $PWD<file_sep>/SphinxTrain/include/s3/s3gau_io.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3gau_io.h * * Description: * * Author: * *********************************************************************/ #ifndef S3GAU_IO_H #define S3GAU_IO_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/vector.h> #define GAU_FILE_VERSION "1.0" #define GAUCNT_FILE_VERSION "1.0" #define GAUDNOM_FILE_VERSION "1.0" int s3gau_read(const char *fn, vector_t ****out, uint32 *out_n_mgau, uint32 *out_n_feat, uint32 *out_n_density, const uint32 **out_veclen); int s3gau_read_full(const char *fn, vector_t *****out, uint32 *out_n_mgau, uint32 *out_n_feat, uint32 *out_n_density, const uint32 **out_veclen); int s3gau_write(const char *fn, const vector_t ***out, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen); int s3gau_write_full(const char *fn, const vector_t ****out, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen); int s3gaucnt_read(const char *fn, vector_t ****out_wt_mean, vector_t ****out_wt_var, int32 *out_pass2var, float32 ****out_dnom, uint32 *out_n_mgau, uint32 *out_n_feat, uint32 *out_n_density, const uint32 **out_veclen); int s3gaucnt_write(const char *fn, vector_t ***wt_mean, vector_t ***wt_var, int32 pass2var, float32 ***dnom, uint32 n_cb, uint32 n_feat, uint32 n_density, const uint32 *veclen); int s3gaudnom_read(const char *fn, float32 ****out_dnom, uint32 *out_n_cb, uint32 *out_n_feat, uint32 *out_n_density); int s3gaucnt_read_full(const char *fn, vector_t ****out_wt_mean, vector_t *****out_wt_var, int32 *out_pass2var, float32 ****out_dnom, uint32 *out_n_cb, uint32 *out_n_feat, uint32 *out_n_density, const uint32 **out_veclen); int s3gaucnt_write_full(const char *fn, vector_t ***wt_mean, vector_t ****wt_var, int32 pass2var, float32 ***dnom, uint32 n_cb, uint32 n_feat, uint32 n_density, const uint32 *veclen); int s3gaudnom_write(const char *fn, float32 ***dnom, uint32 n_cb, uint32 n_feat, uint32 n_density); #ifdef __cplusplus } #endif #endif /* S3GAU_IO_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2004/07/22 00:16:13 egouvea * Roll back because of mistake in commit * * Revision 1.4 2004/07/21 17:46:10 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:39:10 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/mllr_transform/cmd_ln_defn.h /********************************************************************* * * $Header$ * * CMU ARPA Speech Project * * Copyright (c) 1998 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: cmd_ln_defn.h * * Description: * Command line argument definition * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/cmd_ln.h> #include <s3/err.h> #ifndef CMD_LN_DEFN_H const char helpstr[] = "Description: \n\ \n\ Given a set of MLLR transform, mllr_transform can transform \n\ the mean according to formulat y=Ax+b.\n \ \n \ The output and input files are specified by -outmeanfn and \n\ -inmeanfn respectively. You may also transform the context-\n\ dependent model using the option -cdonly. In that case you \n\ need to specify a model definition using -moddeffn."; const char examplestr[] = "Example: \n\ The simplest case: \n\ mllr_transform -inmeanfn inMeans -outmeanfn outMeans -mllrmat matrix \n\ \n\ Adapt only on CD phones: \n\ mllr_transform -inmeanfn inMeans -outmeanfn outMeans -mllrmat matrix -cdonly yes -moddeffn mdef \n\ \n\ Help and example: \n\ nmllr_transform -help yes -example yes "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-inmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Input Gaussian mean file name"}, { "-outmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output Gaussian mean file name"}, { "-ingaucntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Input Gaussian accumulation count file name"}, { "-outgaucntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output Gaussian accumulation count file name"}, { "-mllrmat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The MLLR matrix file"}, { "-cb2mllrfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".1cls.", "The codebook-to-MLLR class file. Override option -cdonly"}, { "-cdonly", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Use CD senones only. -moddeffn must be given."}, { "-inverse", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Apply the inverse transform (for speaker adaptive training)."}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model Definition file. "}, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Variance (baseline-var, or error-var) file (NOT USED!!!)"}, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1e-3", "Variance floor value (NOT USED!!!)"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; #define CMD_LN_DEFN_H #endif /* CMD_LN_DEFN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/08/07 20:41:00 arthchan2003 * texFormat.pl file to handle < and > * ======= * Revision 1.4 2004/08/07 19:51:52 arthchan2003 * Make compiler happy about the help messages * * Revision 1.3 2004/08/03 07:31:17 arthchan2003 * make the changes more latex friendly\n * * Revision 1.2 2004/08/03 07:23:12 arthchan2003 * Check in the code for usage and example of mllr_transform * * Revision 1.1 2004/07/26 05:04:20 arthchan2003 * mllr_transform committed, it is an adaptation of Sam Joo's mllr_adapt * * */ <file_sep>/SphinxTrain/src/programs/mllr_solve/parse_cmd_ln.c /********************************************************************* * * $Header$ * * Carnegie Mellon ARPA Speech Group * * Copyright (c) 1995 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: parse_cmd_ln.c * * Description: * Parse the command line for norm(1) * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; #include "cmd_ln_defn.h" cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.3 2004/11/29 01:43:51 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.2 2004/08/07 20:25:46 arthchan2003 * Add help and example string for mllr_solve. Fix help and example logic for mllr_solve and mllr_transfrom * * Revision 1.1 2004/07/27 12:09:26 arthchan2003 * Missing the whole directory of mllr_solve * * Revision 1.8 97/07/16 11:22:39 eht * Allow an inmixfn for those mixing weights that were unseen in the accumulators * * Revision 1.7 97/03/07 08:53:11 eht * - added -inmeanfn and -invarfn arguments for unseen means and vars * * */ <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/main.c /* ==================================================================== * Copyright (c) 2000 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * Desription: * Multi-function routine to generate mdef for context-independent * training, untied training, and all-triphones mdef for state tying. * Flow: * if (triphonelist) make CI phone list and CD phone list * if alltriphones mdef needed, make mdef * if (rawphonelist) Make ci phone list, * if cimdef needed, make mdef * Generate alltriphones list from dictionary * if alltriphones mdef needed, make mdef * if neither triphonelist or rawphonelist quit * Count triphones and triphone types in transcript * Adjust threshold according to min-occ and maxtriphones * Prune triphone list * Make untied mdef * * * Author: * <NAME> (<EMAIL>) * Date: 08 Dec. 2000 *********************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <s3/s3.h> #include <s3/cmd_ln.h> #include <s3/ckd_alloc.h> #include "parse_cmd_ln.h" #include "heap.h" #include "hash.h" #include "mk_untied.h" int main (int argc, char **argv) { heapelement_t **CDheap=NULL; hashelement_t **CDhash=NULL; phnhashelement_t **CIhash=NULL; dicthashelement_t **dicthash=NULL; int32 cilistsize=0, cdheapsize=0, threshold, tph_list_given, ncd; char *phnlist, *incimdef, *triphnlist, *incdmdef; char *lsnfile, *dictfn, *fillerdictfn, **CIlist=NULL; char *cimdeffn, *alltphnmdeffn, *untiedmdeffn, *countfn; parse_cmd_ln(argc,argv); /* Test all flags before beginning */ cimdeffn = (char *)cmd_ln_access("-ocimdef"); alltphnmdeffn = (char *)cmd_ln_access("-oalltphnmdef"); untiedmdeffn = (char *)cmd_ln_access("-ountiedmdef"); countfn = (char *)cmd_ln_access("-ocountfn"); if (cimdeffn) E_INFO("Will write CI mdef file %s\n",cimdeffn); if (alltphnmdeffn) E_INFO("Will write alltriphone mdef file %s\n",alltphnmdeffn); if (untiedmdeffn) E_INFO("Will write untied mdef file %s\n",untiedmdeffn); if (countfn) E_INFO("Will write triphone counts file %s\n",countfn); if (!cimdeffn && !alltphnmdeffn && !untiedmdeffn && !countfn) E_FATAL("No output mdef files or count files specified!\n"); dictfn = (char *)cmd_ln_access("-dictfn"); fillerdictfn = (char *)cmd_ln_access("-fdictfn"); lsnfile = (char*)cmd_ln_access("-lsnfn"); if ((untiedmdeffn || countfn) && (!lsnfile || !dictfn)) { E_WARN("Either dictionary or transcript file not given!\n"); if (untiedmdeffn) E_WARN("Untied mdef will not be made\n"); if (countfn) E_WARN("Phone counts will not be generated\n"); untiedmdeffn = countfn = NULL; } phnlist = (char *)cmd_ln_access("-phnlstfn"); triphnlist = (char *)cmd_ln_access("-triphnlstfn"); incimdef = (char *)cmd_ln_access("-inCImdef"); incdmdef = (char *)cmd_ln_access("-inCDmdef"); if (!incdmdef && !incimdef && !phnlist && !triphnlist) E_FATAL("No input mdefs or phone list given\n"); if (triphnlist) { if (phnlist) E_WARN("Both -triphnlist %s and -phnlist given.\n",triphnlist); E_WARN("Ignoring -phnlist %s\n",phnlist); phnlist = triphnlist; } tph_list_given = (triphnlist || incdmdef) ? 1 : 0; if (incdmdef) { if (incimdef || phnlist){ E_WARN("Using only input CD mdef %s!\n",incdmdef); E_WARN("Using only triphones from input CD mdef %s!\n",incdmdef); if (incimdef) E_WARN("CImdef %s will be ignored\n",incimdef); if (phnlist) E_WARN("phonelist %s will be ignored\n",phnlist); incimdef = phnlist = NULL; } make_ci_list_cd_hash_frm_mdef(incdmdef,&CIlist,&cilistsize, &CDhash,&ncd); } else{ if (phnlist) make_ci_list_cd_hash_frm_phnlist(phnlist,&CIlist, &cilistsize,&CDhash,&ncd); if (incimdef) { if (CIlist) ckd_free_2d((void**)CIlist); make_ci_list_frm_mdef(incimdef,&CIlist,&cilistsize); } } if (cimdeffn) make_mdef_from_list(cimdeffn,CIlist,cilistsize,NULL,0,argv[0]); if (!tph_list_given && !cimdeffn) { read_dict(dictfn, fillerdictfn, &dicthash); if (CDhash) freehash(CDhash); make_dict_triphone_list (dicthash, &CDhash); } if (alltphnmdeffn){ threshold = -1; make_CD_heap(CDhash,threshold,&CDheap,&cdheapsize); make_mdef_from_list(alltphnmdeffn,CIlist,cilistsize, CDheap,cdheapsize,argv[0]); } if (countfn || untiedmdeffn) count_triphones(lsnfile, dicthash, CDhash, &CIhash); if (countfn){ print_counts(countfn,CIhash,CDhash); } if (untiedmdeffn){ threshold = find_threshold(CDhash); make_CD_heap(CDhash,threshold,&CDheap,&cdheapsize); make_mdef_from_list(untiedmdeffn,CIlist,cilistsize, CDheap,cdheapsize,argv[0]); } return 0; } <file_sep>/archive_s3/s3/Makefile # ==================================================================== # Copyright (c) 1995-2002 Carnegie Mellon University. All rights # reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # # # Copyright (c) 1995 Carnegie Mellon University. ALL RIGHTS RESERVED. # # HISTORY # # 23-Aug-96 <NAME> (<EMAIL>) at Carnegie Mellon University. # Created. # # Before building: # setenv MACHINE alpha {or sun4, hp700_ux, linux, etc. as appropriate} # # Also, create the following directories if not already existing: # lib/$(MACHINE), # bin/$(MACHINE), # src/libutil/$(MACHINE), # src/libio/$(MACHINE), # src/libfeat/$(MACHINE), # src/libfbs/$(MACHINE), all: verify s3decode-anytopo s3align s3allphone s3dag s3astar s3nbestrescore verify: @if test x$(MACHINE) = x; then echo "Define MACHINE, e.g. \"make MACHINE=linux\""; exit 1; fi @if test x$(S3ROOT) = x; then echo "Define S3ROOT, e.g. \"make S3ROOT=\`pwd\`\""; exit 1; fi @if test ! -d lib; then mkdir lib; fi @if test ! -d lib/$(MACHINE); then mkdir lib/$(MACHINE); fi @if test ! -d bin; then mkdir bin; fi @if test ! -d bin/$(MACHINE); then mkdir bin/$(MACHINE); fi @if test ! -d src/libutil/$(MACHINE); then mkdir src/libutil/$(MACHINE); fi @if test ! -d src/libio/$(MACHINE); then mkdir src/libio/$(MACHINE); fi @if test ! -d src/libfeat/$(MACHINE); then mkdir src/libfeat/$(MACHINE); fi @if test ! -d src/libfbs/$(MACHINE); then mkdir src/libfbs/$(MACHINE); fi libutil: (cd src/libutil/$(MACHINE); make -f ../Makefile install) libio: (cd src/libio/$(MACHINE); make -f ../Makefile install) libfeat: (cd src/libfeat/$(MACHINE); make -f ../Makefile install) libutil-dbg: (cd src/libutil/$(MACHINE)-debug; make -f ../Makefile-debug install) libio-dbg: (cd src/libio/$(MACHINE)-debug; make -f ../Makefile-debug install) libfeat-dbg: (cd src/libfeat/$(MACHINE)-debug; make -f ../Makefile-debug install) s3decode: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile install) s3decode-dbg: libutil-dbg libio-dbg libfeat-dbg (cd src/libfbs/$(MACHINE)-debug; make -f ../Makefile-debug install) s3decode-anytopo: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-anytopo install) s3decode-anytopodbg: (cd src/libfbs/$(MACHINE)-debug; make -f ../Makefile-anytopodbg install) s3align: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-align install) s3allphone: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-allphone install) s3dag: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-dag install) s3astar: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-astar install) s3nbestrescore: libutil libio libfeat (cd src/libfbs/$(MACHINE); make -f ../Makefile-nbestrescore install) only-s3decode: (cd src/libfbs/$(MACHINE); make -f ../Makefile install) only-s3align: (cd src/libfbs/$(MACHINE); make -f ../Makefile-align install) only-s3allphone: (cd src/libfbs/$(MACHINE); make -f ../Makefile-allphone install) clean: verify -(cd src/libutil/$(MACHINE) && make -f ../Makefile clean) -(cd src/libio/$(MACHINE) && make -f ../Makefile clean) -(cd src/libfeat/$(MACHINE) && make -f ../Makefile clean) -(cd src/libfbs/$(MACHINE) && make -f ../Makefile clean) -(cd lib/$(MACHINE) && rm -f *.*) -(cd bin/$(MACHINE) && rm -f *.*) <file_sep>/pocketsphinx/test/unit/test_fsg2_search.c #include <pocketsphinx.h> #include <stdio.h> #include <string.h> #include <time.h> #include "pocketsphinx_internal.h" #include "fsg2_search.h" #include "test_macros.h" int main(int argc, char *argv[]) { ps_decoder_t *ps; cmd_ln_t *config; acmod_t *acmod; fsg2_search_t *fsgs; int32 score; TEST_ASSERT(config = cmd_ln_init(NULL, ps_args(), TRUE, "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k", "-fsg", DATADIR "/goforward.fsg", "-dict", MODELDIR "/lm/en_US/cmu07a.dic", "-bestpath", "no", "-input_endian", "little", "-samprate", "16000", NULL)); TEST_ASSERT(ps = ps_init(config)); acmod = ps->acmod; fsgs = (fsg2_search_t *)fsg2_search_init(config, acmod, ps->dict, ps->d2p); setbuf(stdout, NULL); { FILE *rawfh; int16 buf[2048]; size_t nread; int16 const *bptr; char const *hyp; int nfr; TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb")); TEST_EQUAL(0, acmod_start_utt(acmod)); fsg2_search_start(ps_search_base(fsgs)); while (!feof(rawfh)) { nread = fread(buf, sizeof(*buf), 2048, rawfh); bptr = buf; while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) { while (acmod->n_feat_frame > 0) { fsg2_search_step(ps_search_base(fsgs), acmod->output_frame); acmod_advance(acmod); } } } fsg2_search_finish(ps_search_base(fsgs)); hyp = fsg2_search_hyp(ps_search_base(fsgs), &score); printf("FSG: %s (%d)\n", hyp, score); TEST_ASSERT(acmod_end_utt(acmod) >= 0); fclose(rawfh); } TEST_EQUAL(0, strcmp("go forward ten meters", fsg2_search_hyp(ps_search_base(fsgs), &score))); ps_free(ps); return 0; } <file_sep>/SphinxTrain/src/libs/libio/read_line.c /* ==================================================================== * Copyright (c) 2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: read_line.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/read_line.h> #include <s3/err.h> #include <string.h> char * read_line(char *buf, size_t max_len, uint32 *n_read, FILE *fp) { char *out; int last; do { out = fgets(buf, max_len, fp); (*n_read)++; } while ((out != NULL) && (out[0] == '#')); if (strlen(buf) == (max_len-1)) { E_WARN("line %d may be truncated due to max_len==%d\n", *n_read, max_len); } if (out != NULL) { last = strlen(out)-1; if (out[last] == '\n') out[last] = '\0'; } return out; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/11/29 01:11:17 egouvea * Fixed license terms in some new files. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/vithist.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * vit_hist.c -- Viterbi search history. * * * HISTORY * * 03-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added vithist_sort(). * * 25-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Modified vithist_append() interface to include lmhist. * * 23-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <libutil/libutil.h> #include "vithist.h" #include "senone.h" #include "hyp.h" glist_t vithist_append (glist_t hlist, int32 id, int32 frm, int32 score, vithist_t *hist, vithist_t *lmhist) { vithist_t *h; h = (vithist_t *) mymalloc (sizeof(vithist_t)); h->id = id; h->frm = frm; h->scr = score; h->hist = hist; h->lmhist = lmhist ? lmhist : h; /* Self if none provided */ hlist = glist_add_ptr (hlist, (void *)h); return hlist; } glist_t vithist_backtrace (vithist_t *hist, int32 *senscale) { glist_t hyp; hyp_t *hypnode; hyp = NULL; for (; hist; hist = hist->hist) { hypnode = (hyp_t *) mymalloc (sizeof(hyp_t)); hypnode->id = hist->id; hypnode->ef = hist->frm; if (hist->hist) { hypnode->sf = hist->hist->frm+1; hypnode->ascr = hist->scr - hist->hist->scr; /* Still scaled */ } else { hypnode->sf = 0; hypnode->ascr = hist->scr; } /* Undo senone score scaling */ hypnode->ascr += senone_get_senscale (senscale, hypnode->sf, hypnode->ef); hypnode->lscr = 0; hypnode->scr = hypnode->ascr; hyp = glist_add_ptr (hyp, (void *)hypnode); } return hyp; } glist_t vithist_sort (glist_t vithist_list) { heap_t heap; gnode_t *gn; vithist_t *h; glist_t vithist_new; int32 ret, score; vithist_new = NULL; heap = heap_new(); for (gn = vithist_list; gn; gn = gnode_next(gn)) { h = (vithist_t *) gnode_ptr(gn); if (heap_insert (heap, (void *) h, h->scr) < 0) { E_ERROR("Panic: heap_insert() failed\n"); return NULL; } } /* * Note: The heap returns nodes with ASCENDING values; and glist_add adds new nodes to the * HEAD of the list. So we get a glist in the desired descending score order. */ while ((ret = heap_pop (heap, (void **)(&h), &score)) > 0) vithist_new = glist_add_ptr (vithist_new, (void *)h); if (ret < 0) { E_ERROR("Panic: heap_pop() failed\n"); return NULL; } heap_destroy (heap); return vithist_new; } int32 vithist_log (FILE *fp, glist_t *vithist, int32 nfr, char *(*func)(void *kb, int32 id), void *kb) { int32 f, n; gnode_t *gn; vithist_t *h; n = 0; for (f = 0; f < nfr; f++) { for (gn = vithist[f]; gn; gn = gnode_next(gn), n++) { h = (vithist_t *) gnode_ptr(gn); fprintf (fp, " %5d %5d %11d %s\n", h->hist ? h->hist->frm + 1 : h->frm, h->frm, h->scr - (h->hist ? h->hist->scr : 0), func ? (*func)(kb, h->id) : ""); } } fflush (fp); return n; } <file_sep>/archive_s3/s3.0/pgm/misc/cepdist-var.c /* * cepdist-var.c -- feature vector variances * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 16-May-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <s3.h> #include <libio/libio.h> #include <libfeat/libfeat.h> static int32 cepsize, featlen; static float32 **feat; static char *feattype; static void cepd1 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; } static void cepd2 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[1][i] - mfc[-1][i]; } static void cepd1_c0 (float32 **mfc, float32 *f) { int32 i; for (i = 1; i < cepsize; i++) f[i-1] = mfc[0][i]; for (i = 1; i < cepsize; i++) f[cepsize+i-2] = mfc[0][i] - mfc[-1][i]; } static void cepd1d2avg (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = 0.5 * ((mfc[0][i] - mfc[-1][i]) + (mfc[1][i] - mfc[0][i])); } static void cepd1d2 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] = mfc[1][i] - mfc[0][i]; } static void cep_d_dd (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] = mfc[1][i] - mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] -= f[cepsize+i]; } static int32 add_cepfile (char *cepfile) { int32 i, j, w, nfr, sf, ef, n_feat; float32 **mfc; if ((nfr = s2mfc_read (cepfile, 0, (int32)0x7fffffff, &mfc)) <= 0) { E_ERROR("MFC file read (%s) failed\n", cepfile); return; } w = feat_window_size (); sf = w; ef = nfr-w-2; n_feat = 0; if (strcmp (feattype, "cep") == 0) { for (i = sf; i <= ef; i++) { for (j = 0; j < featlen; j++) feat[n_feat][j] = mfc[i][j]; n_feat++; } } else if (strcmp (feattype, "d1") == 0) { for (i = sf; i <= ef; i++) { cepd1 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d2") == 0) { for (i = sf; i <= ef; i++) { cepd2 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1_c0") == 0) { for (i = sf; i <= ef; i++) { cepd1_c0 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1d2avg") == 0) { for (i = sf; i <= ef; i++) { cepd1d2avg (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1d2") == 0) { for (i = sf; i <= ef; i++) { cepd1d2 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d_dd") == 0) { for (i = sf; i <= ef; i++) { cep_d_dd (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "s3") == 0) { for (i = sf; i <= ef; i++) { feat_cep2feat (mfc+i, feat+n_feat); n_feat++; } } else E_FATAL("Unknown feattype: %s\n", feattype); return n_feat; } static void process_ctlfile (FILE *fp) { char cepfile[4096], uttid[4096]; float32 *sum, *sumsq, *lsum, *lsumsq, *mean, *var; int32 i, j, nfr, n_feat; sum = (float32 *) ckd_calloc (featlen, sizeof(float32)); sumsq = (float32 *) ckd_calloc (featlen, sizeof(float32)); lsum = (float32 *) ckd_calloc (featlen, sizeof(float32)); lsumsq = (float32 *) ckd_calloc (featlen, sizeof(float32)); mean = (float32 *) ckd_calloc (featlen, sizeof(float32)); var = (float32 *) ckd_calloc (featlen, sizeof(float32)); E_INFO("Computing means\n"); for (i = 0; i < featlen; i++) sum[i] = 0.0; nfr = 0; while (fscanf (fp, "%s", uttid) == 1) { sprintf (cepfile, "%s.mfc", uttid); n_feat = add_cepfile (cepfile); E_INFO("%5d feature vectors\n", n_feat); for (i = 0; i < featlen; i++) lsum[i] = 0.0; for (i = 0; i < n_feat; i++) { for (j = 0; j < featlen; j++) lsum[j] += feat[i][j]; } for (i = 0; i < featlen; i++) sum[i] += lsum[i]; nfr += n_feat; } rewind (fp); for (i = 0; i < featlen; i++) { mean[i] = sum[i]/(float64)nfr; printf (" %11.3e", mean[i]); } printf ("\n"); fflush (stdout); E_INFO("Computing variances\n"); for (i = 0; i < featlen; i++) sum[i] = 0.0; while (fscanf (fp, "%s", uttid) == 1) { sprintf (cepfile, "%s.mfc", uttid); n_feat = add_cepfile (cepfile); E_INFO("%5d feature vectors\n", n_feat); for (i = 0; i < featlen; i++) lsum[i] = 0.0; for (i = 0; i < n_feat; i++) { for (j = 0; j < featlen; j++) lsum[j] += (feat[i][j] - mean[j]) * (feat[i][j] - mean[j]); } for (i = 0; i < featlen; i++) sum[i] += lsum[i]; } for (i = 0; i < featlen; i++) { var[i] = sum[i]/(float64)nfr; printf (" %11.3e", var[i]); } printf ("\n"); } main (int32 argc, char *argv[]) { int32 *fl; /* temporary featlen */ char *ctlfile; int32 i, n_feat; FILE *ctlfp; if (argc < 3) E_FATAL("Usage: %s feattype ctlfile\n", argv[0]); feattype = argv[1]; ctlfile = argv[2]; feat_init ("s3_1x39"); cepsize = feat_cepsize (); n_feat = feat_featsize (&fl); assert ((n_feat == 1) && (fl[0] == 39)); if (strcmp (feattype, "cep") == 0) { featlen = 13; } else if (strcmp (feattype, "d1") == 0) { featlen = 26; } else if (strcmp (feattype, "d2") == 0) { featlen = 26; } else if (strcmp (feattype, "d1_c0") == 0) { featlen = 24; } else if (strcmp (feattype, "d1d2avg") == 0) { featlen = 26; } else if (strcmp (feattype, "d1d2") == 0) { featlen = 39; } else if (strcmp (feattype, "d_dd") == 0) { featlen = 39; } else if (strcmp (feattype, "s3") == 0) { featlen = fl[0]; } else E_FATAL("Unknown feattype: %s\n", feattype); feat = (float32 **) ckd_calloc_2d (S3_MAX_FRAMES, featlen, sizeof(float32)); if (strcmp (ctlfile, "-") != 0) { if ((ctlfp = fopen(ctlfile, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", ctlfile); } else ctlfp = stdin; process_ctlfile (ctlfp); exit(0); } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/ConfNodeWidget.java package edu.cmu.sphinx.tools.confdesigner; import org.netbeans.api.visual.widget.general.IconNodeWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.model.ObjectState; import org.netbeans.api.visual.laf.LookFeel; /** * DOCUMENT ME! * * @author <NAME> */ public class ConfNodeWidget extends IconNodeWidget { public ConfNodeWidget(Scene scene) { super(scene); } public ConfNodeWidget(Scene scene, TextOrientation orientation) { super(scene, orientation); } public void notifyStateChanged(ObjectState previousState, ObjectState state) { LookFeel lookFeel = getScene().getLookFeel(); setBorder(lookFeel.getBorder(state)); setForeground(lookFeel.getForeground(state)); } public void addThisPin(PortWidget portWidget) { addChild(portWidget); } } <file_sep>/CLP/include/Clustering.h //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _Clustering_h #define _Clustering_h #include "Cluster.h" #include "Lattice.h" #include "common_lattice.h" #include "Prons.h" #include "Similarities.h" typedef list<Cluster> ClusterList; typedef ClusterList::iterator ClusterListIt; typedef ClusterList::const_iterator ClusterListConstIt; class Clustering { public: Clustering(); Clustering(const Lattice*, const Prons&); int no_clusters() { return C.size();} int No_links() { return no_links;} // the number of word types in the list of clusters int no_words(); // add the word lists in each clusters void fill_words(); // sort the clusters in topological order void TopSort(); // print the consensus hypothesis and the confusion networks (with the words in decreasing order of their scores) void print_sausages_FSMformat(const string& outdir, const string& outfile, const string& infile, float lowEpsT, float highEpsT, float lowWordT, float highWordT, const Prons& P, bool output_fullpath); // print the list of clusters, specifying either only the links, or only words, or both void print(const Prons& P, bool print_links, bool print_words); // add a link "eps" to each cluster which has as prob the remaining probability mass (weighted by DELweight) void add_EPS(float DELweight); // cluster according to stage (intra-word or inter-word), mode (max, avg), in the constrained mode or not void go_cluster(const Prons& P, const int stage, const int mode, const bool constrained); private: const Lattice* lat_ptr; // the lattice the clusters are to be built from ClusterList C; // the list of clusters IntIntIntMap constraints; // the partial order on the clusters int no_links; // the number of links used to build the clusters (left after pruning) double compute_TIME_sim(ClusterListConstIt it1, ClusterListConstIt it2, IntIntDblMap& linkTimeSim, const int mode, const bool constrained); double compute_PHON_sim(ClusterListConstIt cit1, ClusterListConstIt cit2, Prons& P, IntIntDblMap& wordPhSim, const int mode, const bool use_phon_info,const bool constrained ); void DFS_visit(const unsigned, IdsMatrix& , IdsList& , IdsVector&); }; #endif <file_sep>/SphinxTrain/src/programs/param_cnt/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/s3.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ Find the number of times each of the triphones listed \n\ \n\ in a given model definition file (by -moddeffhn) occured in a set \n\ of transcription, specified by -lsnfn"; const char examplestr[] = "Example : \n\ param_cnt -moddeffn mdef -ts2cbfn .cont. -ctlfn controlfile -lsnfn \n\ transcripts -dictfn dict -fdictfn fillerdict -paramtype phone"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition file for the single density HMM's to initialize"}, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied-state-to-codebook mapping file"}, { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Control file of the training corpus"}, { "-part", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Identifies the corpus part number (range 1..NPART)" }, { "-npart", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Partition the corpus into this many equal sized subsets" }, { "-nskip", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of lines to skip in the control file"}, { "-runlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of lines to process in the control file (after any skip)"}, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "All word transcripts for the training corpus (consistent order w/ -ctlfn!)"}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary for the content words"}, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary for the filler words"}, { "-segdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the training corpus state segmentation files."}, { "-segext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "v8_seg", "Extension of the training corpus state segmentation files."}, { "-paramtype", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "state", "Parameter type to count {'state', 'cb', 'phone'}"}, { "-outputfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "If specified, write counts to this file"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ exit(1); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.8 2006/02/03 18:53:07 eht * Added -outputfn to the command line. * * When -outputfn <somefile> is present on the command line, the * parameter counts are written to the specified file <somefile>. * When no -outputfn argument is present on the command line, the * parameter counts are written to standard output as before this * change. * * Revision 1.7 2005/04/07 21:23:40 egouvea * Improved the documentation, making it easier to find pointers, fixed the setup script, and fixed some of the doxygen comments * * Revision 1.6 2004/11/29 01:43:51 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/08/09 02:31:59 arthchan2003 * param_cnt help and example * * Revision 1.4 2004/07/21 19:17:26 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.2 97/03/07 08:42:09 eht * Deal w/ new argument -ts2cbfn * * Revision 1.1 1996/03/25 15:21:20 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libs2io/read_seno_dtree.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: read_seno_dtree.c * * Description: * * Author: * *********************************************************************/ static char rcsid[] = "@(#)$Id$"; #include <s3/read_seno_dtree.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <string.h> #include <assert.h> static int read_header_line(uint32 *n_base, char *id, uint32 *n_cd, FILE *fp) { if (fscanf(fp, "%u:%s %u", n_base, id, n_cd) == 3) { return S3_SUCCESS; } else { return S3_ERROR; } } static int read_node_line(float32 *out_entropy, uint32 *out_key, uint32 *out_left_key, uint32 *out_right_key, char *q_str, FILE *fp) { int ret; ret = fscanf(fp, "%f %u %u %u", out_entropy, out_key, out_left_key, out_right_key); if (ret != 4) { if (ret < 0) return -1; else return 0; } fgets(q_str, 1024, fp); q_str[strlen(q_str)-1] = '\0'; return 1; } int read_seno_dtree_file(dtree_t **out_dt, const char *file_name) { uint32 n_base; uint32 n_cd; char tree_id[64]; float32 ent; uint32 key, l_key, r_key, n_key = 0, *k2q = NULL; char q_str[1024], *rem_q_str; FILE *fp; int i, j, n_quest; dtree_t *dt; bt_node_t *node; bt_t *tree; comp_quest_t *q; float32 *q2ent; *out_dt = dt = (dtree_t *)ckd_calloc(1, sizeof(dtree_t)); dt->tree = tree = bt_new(); fp = fopen(file_name, "r"); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for reading", file_name); return S3_ERROR; } for (n_quest = 0; fgets(q_str, 1024, fp) != NULL; n_quest++); --n_quest; /* account for header line */ dt->n_quest = n_quest; rewind(fp); read_header_line(&n_base, tree_id, &n_cd, fp); for (i = 0; read_node_line(&ent, &key, &l_key, &r_key, q_str, fp) > 0; i++) { if (n_key < l_key) n_key = l_key; if (n_key < r_key) n_key = r_key; } ++n_key; dt->n_key = n_key; rewind(fp); read_header_line(&n_base, tree_id, &n_cd, fp); E_INFO("Reading tree %s (%u base phones, %u CD phones, %u quest)\n", tree_id, n_base, n_cd, n_quest); dt->quest = q = (comp_quest_t *)ckd_calloc(n_quest, sizeof(comp_quest_t)); dt->k2q = k2q = (uint32 *)ckd_calloc(n_key, sizeof(uint32)); dt->q2ent = q2ent = (float32 *)ckd_calloc(n_quest, sizeof(float32)); for (i = 0; i < n_key; i++) { k2q[i] = NO_MAP; } for (i = 0; read_node_line(&ent, &key, &l_key, &r_key, q_str, fp) > 0; i++) { if (tree->root) { E_INFO("%u\n", key); node = bt_find_node(tree, key); if (node) { /* grow left and right children */ bt_add_left(node, l_key); bt_add_right(node, r_key); } else { E_FATAL("Find node w/ key %u failed\n", key); } } else { E_INFO("root %u\n", key); tree->root = bt_new_node(key); bt_add_left(tree->root, l_key); bt_add_right(tree->root, r_key); } k2q[key] = i; q2ent[i] = ent; parse_compound_q(&q[i], q_str); } assert(i == n_quest); return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:31 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 1996/03/26 15:16:26 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/mk_s2sendump/feat.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * feat.c -- Feature vector description and cepstra->feature computation. * * HISTORY * * 12-Jun-98 <NAME> (<EMAIL>) at Carnegie Mellon University * Major changes to accommodate arbitrary feature input types. Added * feat_read(), moved various cep2feat functions from other files into * this one. Also, made this module object-oriented with the feat_t type. * Changed definition of s2mfc_read to let the caller manage MFC buffers. * * 03-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added unistd.h include. * * 02-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added check for sf argument to s2mfc_read being within file size. * * 18-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added sf, ef parameters to s2mfc_read(). * * 10-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added feat_cepsize(). * Added different feature-handling (s2_4x, s3_1x39 at this point). * Moved feature-dependent functions to feature-dependent files. * * 09-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Moved constant declarations from feat.h into here. * * 04-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ /* * This module encapsulates different feature streams used by the Sphinx group. New * stream types can be added by augmenting feat_init() and providing an accompanying * compute_feat function. It also provides a "generic" feature vector definition for * handling "arbitrary" speech input feature types (see the last section in feat_init()). * In this case the speech input data should already be feature vectors; no computation, * such as MFC->feature conversion, is available or needed. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <assert.h> #if (! WIN32) #include <sys/file.h> #include <sys/errno.h> #include <sys/param.h> #include <unistd.h> #else #include <fcntl.h> #endif #include <s3/common.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3mixw_io.h> #include <s3/s3tmat_io.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s3/s2_read_map.h> #include <s3/s2_write_seno.h> #include <s3/cmd_ln.h> #include "s3/hash.h" typedef hash_t hash_table_t; #include "s3types.h" #include "another_s3types.h" #include "another_mdef.h" #include "another_senone.h" #include "s3types.h" #include "bio.h" #include "feat.h" #define FEAT_VERSION "1.0" int32 feat_readfile (feat_t *fcb, char *file, int32 sf, int32 ef, float32 ***feat, int32 maxfr) { FILE *fp; int32 i, l, k, nfr; int32 byteswap, chksum_present; uint32 chksum; char **argname, **argval; if ((sf == 0) && (ef < 0)) E_INFO("Reading feature file: '%s'\n", file); else E_INFO("Reading feature file: '%s'[%d..%d]\n", file, sf, ef); if ((ef <= sf) && ((sf != 0) || (ef >= 0))) { E_ERROR("%s: End frame (%d) <= Start frame (%d)\n", file, ef, sf); return -1; } assert (fcb); if ((fp = fopen(file, "rb")) == NULL) { E_ERROR("fopen(%s,rb) failed\n", file); return -1; } /* Read header */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) { E_ERROR("bio_readhdr(%s) failed\n", file); fclose (fp); return -1; } /* Parse header info (although nothing much is done with it) */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], FEAT_VERSION) != 0) E_WARN("%s: Version mismatch: %s, expecting %s\n", file, argval[i], FEAT_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* #Frames */ if (bio_fread (&nfr, sizeof(int32), 1, fp, byteswap, &chksum) != 1) { E_ERROR("%s: fread(#frames) failed\n", file); fclose (fp); return -1; } /* #Feature streams */ if ((bio_fread (&l, sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (l != feat_n_stream(fcb))) { E_ERROR("%s: Missing or bad #feature streams\n", file); fclose (fp); return -1; } /* Feature stream lengths */ k = 0; for (i = 0; i < feat_n_stream(fcb); i++) { if ((bio_fread (&l, sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (l != feat_stream_len (fcb, i))) { E_ERROR("%s: Missing or bad feature stream size\n", file); fclose (fp); return -1; } k += l; } /* Set endframe if not specified */ if (ef < 0) ef = nfr-1; else if (ef >= nfr) { E_ERROR("%s: End frame spec (%d) beyond EOF (%d frames); limited to EOF\n", file, ef, nfr); ef = nfr-1; } if ((sf < 0) || (sf >= nfr) || (ef < 0) || (ef < sf)) { E_ERROR("%s: Start/end frame spec (%d,%d) out of file size range (%d)\n", file, sf, ef, nfr); fclose (fp); return -1; } /* Check sf/ef specified */ if (sf > 0) { if (sf >= nfr) { E_ERROR("%s: Start frame (%d) beyond file size (%d)\n", file, sf, nfr); fclose (fp); return -1; } nfr -= sf; } /* Limit nfr as indicated by [sf..ef] */ if ((ef-sf+1) < nfr) nfr = (ef-sf+1); if (nfr > maxfr) { E_ERROR("%s: Feature buffer size(%d) too small; %d required\n", file, maxfr, nfr); fclose (fp); return -1; } /* Position at desired start frame and read feature data */ if (sf > 0) fseek (fp, sf * k * sizeof(float32), SEEK_CUR); if (bio_fread (feat[0][0], sizeof(float32), nfr*k, fp, byteswap, &chksum) != nfr*k) { E_ERROR("%s: fread(%dx%d) (feature data) failed\n", file, nfr, k); fclose (fp); return -1; } fclose (fp); /* NOTE: checksum NOT verified; we might read only part of file */ return nfr; } int32 feat_writefile (feat_t *fcb, char *file, float32 ***feat, int32 nfr) { FILE *fp; int32 i, k; E_INFO ("Writing feature file: '%s'\n", file); assert (fcb); if ((fp = fopen (file, "wb")) == NULL) { E_ERROR("fopen(%s,wb) failed\n", file); return -1; } /* Write header */ bio_writehdr_version (fp, FEAT_VERSION); fwrite (&nfr, sizeof(int32), 1, fp); fwrite (&(fcb->n_stream), sizeof(int32), 1, fp); k = 0; for (i = 0; i < feat_n_stream(fcb); i++) { fwrite (&(fcb->stream_len[i]), sizeof(int32), 1, fp); k += feat_stream_len(fcb, i); } /* Feature data is assumed to be in a single block, starting at feat[0][0][0] */ if (fwrite (feat[0][0], sizeof(float32), nfr*k, fp) != (size_t)nfr*k) { E_ERROR("%s: fwrite(%dx%d feature data) failed\n", file, nfr, k); fclose (fp); return -1; } fclose (fp); return 0; } #define FREAD_RETRY_COUNT 60 int32 fread_retry(void *pointer, int32 size, int32 num_items, FILE *stream) { char *data; uint32 n_items_read; uint32 n_items_rem; uint32 n_retry_rem; int32 loc; n_retry_rem = FREAD_RETRY_COUNT; data = pointer; loc = 0; n_items_rem = num_items; do { n_items_read = fread(&data[loc], size, n_items_rem, stream); n_items_rem -= n_items_read; if (n_items_rem > 0) { /* an incomplete read occurred */ if (n_retry_rem == 0) return -1; if (n_retry_rem == FREAD_RETRY_COUNT) { E_ERROR_SYSTEM("fread() failed; retrying...\n"); } --n_retry_rem; loc += n_items_read * size; #if (! WIN32) sleep(1); #endif } } while (n_items_rem > 0); return num_items; } #define STAT_RETRY_COUNT 10 int32 stat_retry (char *file, struct stat *statbuf) { int32 i; for (i = 0; i < STAT_RETRY_COUNT; i++) { if (stat (file, statbuf) == 0) return 0; if (i == 0) { E_ERROR_SYSTEM("stat(%s) failed; retrying...\n", file); } #if (! WIN32) sleep (10); #endif } return -1; } /* * Read specified segment [sf..ef] of Sphinx-II format mfc file read and return * #frames read. Return -1 if error. */ int32 s2mfc_read (char *file, int32 sf, int32 ef, int32 featpad, float32 **mfc, int32 maxfr) { FILE *fp; int32 n_float32; struct stat statbuf; int32 i, n, byterev, cepsize, spad, epad, n_read; if ((sf == 0) && (ef < 0)) E_INFO("Reading MFC file: '%s'\n", file); else E_INFO("Reading MFC file: '%s'[%d..%d]\n", file, sf, ef); if ((ef <= sf) && ((sf != 0) || (ef >= 0))) { E_ERROR("%s: End frame (%d) <= Start frame (%d)\n", file, ef, sf); return -1; } cepsize = 13; /* Hack!! hardwired constant */ /* Find filesize; HACK!! To get around intermittent NFS failures, use stat_retry */ if ((stat_retry (file, &statbuf) < 0) || ((fp = fopen(file, "rb")) == NULL)) { E_ERROR("stat_retry/fopen(%s) failed\n", file); return -1; } /* Read #floats in header */ if (fread_retry (&n_float32, sizeof(int32), 1, fp) != 1) { E_ERROR("%s: fread(#floats) failed\n", file); fclose (fp); return -1; } /* Check if n_float32 matches file size */ byterev = FALSE; if ((n_float32*sizeof(float32) + 4) != (size_t)statbuf.st_size) { n = n_float32; SWAP_INT32(&n); if ((n*sizeof(float32) + 4) != (size_t)statbuf.st_size) { E_ERROR("%s: Header size field: %d(%08x); filesize: %d(%08x)\n", file, n_float32, n_float32, statbuf.st_size, statbuf.st_size); fclose (fp); return -1; } n_float32 = n; byterev = TRUE; } if (n_float32 <= 0) { E_ERROR("%s: Header size field (#floats) = %d\n", file, n_float32); fclose (fp); return -1; } /* Convert n to #frames of input */ n = n_float32/cepsize; if (n * cepsize != n_float32) { E_ERROR("%s: Header size field: %d; not multiple of %d\n", file, n_float32, cepsize); fclose (fp); return -1; } /* Set endframe if not specified */ if (ef < 0) ef = n-1; else if (ef >= n) { E_ERROR("%s: End frame spec (%d) beyond EOF (%d frames); limited to EOF\n", file, ef, n); ef = n-1; } if ((sf < 0) || (sf >= n) || (ef < 0) || (ef < sf)) { E_ERROR("%s: Start/end frame spec (%d,%d) out of file size range (%d)\n", file, sf, ef, n); fclose (fp); return -1; } /* Account for the necessary padding */ sf -= featpad; ef += featpad; n_read = ef - sf + 1; if (n_read > maxfr) { E_ERROR("%s: MFC buffer size (%d) too small; %d required\n", file, maxfr, n_read); fclose (fp); return -1; } if (sf < 0) { spad = -sf; sf = 0; } else spad = 0; if (ef >= n) { epad = ef - (n-1); ef = n-1; } else epad = 0; /* Position at desired start frame and read MFC data */ if (sf > 0) fseek (fp, sf * cepsize * sizeof(float32), SEEK_CUR); n_float32 = (ef-sf+1) * cepsize; if ((i = fread (mfc[spad], sizeof(float32), n_float32, fp)) != n_float32) { E_ERROR("%s: fread(%d,%d) returned %d\n", file, sizeof(float32), n_float32, i); fclose (fp); return -1; } if (byterev) { for (i = 0; i < n_float32; i++) SWAP_FLOAT32(&(mfc[spad][i])); } fclose (fp); /* Add padding that could not be obtained from the MFC file itself */ if (spad > 0) { for (i = 0; i < spad; i++) memcpy ((void *)(mfc[i]), (void *)(mfc[spad]), cepsize*sizeof(float32)); } if (epad > 0) { for (i = 0; i < epad; i++) memcpy ((void *)(mfc[n_read-1-i]), (void *)(mfc[n_read-1-epad]), cepsize*sizeof(float32)); } return n_read; } static int32 feat_stream_len_sum (feat_t *fcb) { int32 i, k; k = 0; for (i = 0; i < feat_n_stream(fcb); i++) k += feat_stream_len (fcb, i); return k; } float32 **feat_vector_alloc (feat_t *fcb) { int32 i, k; float32 *data, **feat; assert (fcb); if ((k = feat_stream_len_sum(fcb)) <= 0) { E_ERROR("Sum(feature stream lengths) = %d\n", k); return NULL; } /* Allocate feature data array so that data is in one block from feat[0][0] */ feat = (float32 **) ckd_calloc (feat_n_stream(fcb), sizeof(float32 *)); data = (float32 *) ckd_calloc (k, sizeof(float32)); for (i = 0; i < feat_n_stream(fcb); i++) { feat[i] = data; data += feat_stream_len (fcb, i); } return feat; } float32 ***feat_array_alloc (feat_t *fcb, int32 nfr) { int32 i, j, k; float32 *data, ***feat; assert (fcb); assert (nfr > 0); if ((k = feat_stream_len_sum(fcb)) <= 0) { E_ERROR("Sum(feature stream lengths) = %d\n", k); return NULL; } /* Allocate feature data array so that data is in one block from feat[0][0][0] */ feat = (float32 ***) ckd_calloc_2d (nfr, feat_n_stream(fcb), sizeof(float32 *)); data = (float32 *) ckd_calloc (nfr*k, sizeof(float32)); for (i = 0; i < nfr; i++) { for (j = 0; j < feat_n_stream(fcb); j++) { feat[i][j] = data; data += feat_stream_len (fcb, j); } } return feat; } static void feat_s2_4x_cep2feat (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; int32 i, j; assert (fcb); assert (feat_cepsize (fcb) == 13); assert (feat_cepsize_used (fcb) == 13); assert (feat_n_stream (fcb) == 4); assert (feat_stream_len (fcb, 0) == 12); assert (feat_stream_len (fcb, 1) == 24); assert (feat_stream_len (fcb, 2) == 3); assert (feat_stream_len (fcb, 3) == 12); assert (feat_window_size (fcb) == 4); /* CEP; skip C0 */ memcpy (feat[0], mfc[0]+1, (feat_cepsize(fcb)-1) * sizeof(float32)); /* * DCEP(SHORT): mfc[2] - mfc[-2] * DCEP(LONG): mfc[4] - mfc[-4] */ w = mfc[2] + 1; /* +1 to skip C0 */ _w = mfc[-2] + 1; f = feat[1]; for (i = 0; i < feat_cepsize(fcb)-1; i++) /* Short-term */ f[i] = w[i] - _w[i]; w = mfc[4] + 1; /* +1 to skip C0 */ _w = mfc[-4] + 1; for (j = 0; j < feat_cepsize(fcb)-1; i++, j++) /* Long-term */ f[i] = w[j] - _w[j]; /* D2CEP: (mfc[3] - mfc[-1]) - (mfc[1] - mfc[-3]) */ w1 = mfc[3] + 1; /* Final +1 to skip C0 */ _w1 = mfc[-1] + 1; w_1 = mfc[1] + 1; _w_1 = mfc[-3] + 1; f = feat[3]; for (i = 0; i < feat_cepsize(fcb)-1; i++) { d1 = w1[i] - _w1[i]; d2 = w_1[i] - _w_1[i]; f[i] = d1 - d2; } /* POW: C0, DC0, D2C0; differences computed as above for rest of cep */ f = feat[2]; f[0] = mfc[0][0]; f[1] = mfc[2][0] - mfc[-2][0]; d1 = mfc[3][0] - mfc[-1][0]; d2 = mfc[1][0] - mfc[-3][0]; f[2] = d1 - d2; } static void feat_s3_1x39_cep2feat (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; int32 i; assert (fcb); assert (feat_cepsize (fcb) == 13); assert (feat_cepsize_used (fcb) == 13); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == 39); assert (feat_window_size (fcb) == 3); /* CEP; skip C0 */ memcpy (feat[0], mfc[0]+1, (feat_cepsize(fcb)-1) * sizeof(float32)); /* * DCEP: mfc[2] - mfc[-2]; */ f = feat[0] + feat_cepsize(fcb)-1; w = mfc[2] + 1; /* +1 to skip C0 */ _w = mfc[-2] + 1; for (i = 0; i < feat_cepsize(fcb)-1; i++) f[i] = w[i] - _w[i]; /* POW: C0, DC0, D2C0 */ f += feat_cepsize(fcb)-1; f[0] = mfc[0][0]; f[1] = mfc[2][0] - mfc[-2][0]; d1 = mfc[3][0] - mfc[-1][0]; d2 = mfc[1][0] - mfc[-3][0]; f[2] = d1 - d2; /* D2CEP: (mfc[3] - mfc[-1]) - (mfc[1] - mfc[-3]) */ f += 3; w1 = mfc[3] + 1; /* Final +1 to skip C0 */ _w1 = mfc[-1] + 1; w_1 = mfc[1] + 1; _w_1 = mfc[-3] + 1; for (i = 0; i < feat_cepsize(fcb)-1; i++) { d1 = w1[i] - _w1[i]; d2 = w_1[i] - _w_1[i]; f[i] = d1 - d2; } } static void feat_s3_cep (feat_t *fcb, float32 **mfc, float32 **feat) { assert (fcb); assert (feat_cepsize (fcb) == 13); assert ((feat_cepsize_used (fcb) <= 13) && (feat_cepsize_used(fcb) > 0)); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == feat_cepsize_used(fcb)); assert (feat_window_size (fcb) == 0); /* CEP */ memcpy (feat[0], mfc[0], feat_cepsize_used(fcb) * sizeof(float32)); } static void feat_s3_cep_dcep (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; int32 i; assert (fcb); assert (feat_cepsize (fcb) == 13); assert ((feat_cepsize_used (fcb) <= 13) && (feat_cepsize_used(fcb) > 0)); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == (feat_cepsize_used(fcb) * 2)); assert (feat_window_size (fcb) == 2); /* CEP */ memcpy (feat[0], mfc[0], feat_cepsize_used(fcb) * sizeof(float32)); /* * DCEP: mfc[2] - mfc[-2]; */ f = feat[0] + feat_cepsize_used(fcb); w = mfc[2]; _w = mfc[-2]; for (i = 0; i < feat_cepsize_used(fcb); i++) f[i] = w[i] - _w[i]; } feat_t *feat_init (char *type) { feat_t *fcb; int32 i, l, k; char wd[16384], *strp; E_INFO("Initializing feature stream to type: %s\n", type); fcb = (feat_t *) ckd_calloc (1, sizeof(feat_t)); fcb->name = (char *) ckd_salloc (type); if (strcmp (type, "s2_4x") == 0) { /* Sphinx-II format 4-stream feature (Hack!! hardwired constants below) */ fcb->cepsize = 13; fcb->cepsize_used = 13; fcb->n_stream = 4; fcb->stream_len = (int32 *) ckd_calloc (4, sizeof(int32)); fcb->stream_len[0] = 12; fcb->stream_len[1] = 24; fcb->stream_len[2] = 3; fcb->stream_len[3] = 12; fcb->window_size = 4; fcb->compute_feat = feat_s2_4x_cep2feat; } else if (strcmp (type, "s3_1x39") == 0) { /* 1-stream cep/dcep/pow/ddcep (Hack!! hardwired constants below) */ fcb->cepsize = 13; fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = 39; fcb->window_size = 3; fcb->compute_feat = feat_s3_1x39_cep2feat; } else if (strncmp (type, "cep_dcep", 8) == 0) { /* 1-stream cep/dcep (Hack!! hardwired constants below) */ fcb->cepsize = 13; /* Check if using only a portion of cep dimensions */ if (type[8] == ',') { if ((sscanf (type+9, "%d%n", &(fcb->cepsize_used), &l) != 1) || (type[l+9] != '\0') || (feat_cepsize_used(fcb) <= 0) || (feat_cepsize_used(fcb) > feat_cepsize(fcb))) E_FATAL("Bad feature type argument: '%s'\n", type); } else fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = feat_cepsize_used(fcb) * 2; fcb->window_size = 2; fcb->compute_feat = feat_s3_cep_dcep; } else if (strncmp (type, "cep", 3) == 0) { /* 1-stream cep (Hack!! hardwired constants below) */ fcb->cepsize = 13; /* Check if using only a portion of cep dimensions */ if (type[3] == ',') { if ((sscanf (type+4, "%d%n", &(fcb->cepsize_used), &l) != 1) || (type[l+4] != '\0') || (feat_cepsize_used(fcb) <= 0) || (feat_cepsize_used(fcb) > feat_cepsize(fcb))) E_FATAL("Bad feature type argument: '%s'\n", type); } else fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = feat_cepsize_used(fcb); fcb->window_size = 0; fcb->compute_feat = feat_s3_cep; } else { /* * Generic definition: Format should be %d,%d,%d,...,%d (i.e., comma separated * list of feature stream widths; #items = #streams). */ l = strlen(type); k = 0; for (i = 1; i < l-1; i++) if (type[i] == ',') { type[i] = ' '; k++; } k++; /* Presumably there are (#commas+1) streams */ fcb->n_stream = k; fcb->stream_len = (int32 *) ckd_calloc (k, sizeof(int32)); /* Scan individual feature stream lengths */ strp = type; i = 0; while (sscanf (strp, "%s%n", wd, &l) == 1) { strp += l; if ((i >= fcb->n_stream) || (sscanf (wd, "%d", &(fcb->stream_len[i])) != 1) || (fcb->stream_len[i] <= 0)) E_FATAL("Bad feature type argument\n"); i++; } if (i != fcb->n_stream) E_FATAL("Bad feature type argument\n"); /* Input is already the feature stream */ fcb->cepsize = -1; fcb->cepsize_used = -1; fcb->window_size = 0; fcb->compute_feat = NULL; } return fcb; } <file_sep>/share/acoustic/wsj/make-ascii-zip #!/bin/sh # Copyright 1999-2002 Carnegie Mellon University. # Portions Copyright 2002 Sun Microsystems, Inc. # Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. # All Rights Reserved. Use is subject to license terms. # # See the file "license.terms" for information on usage and # redistribution of this file, and for a DISCLAIMER OF ALL # WARRANTIES. # # Creates the ASCII form of the WSJ acoustic model suitable # for use with Sphinx 4. # ASCII_ZIP=wsj_8gau_13dCep_16k_40mel_130Hz_6800Hz.ascii.zip # where the WSJ acoustic model directory is, modify as you need MODEL_DIR=/lab/speech/sphinx4/data/wsj PWD=`pwd` rm -f ${ASCII_ZIP} cd $MODEL_DIR zip -r ${ASCII_ZIP} README am.props license.terms cd_continuous_8gau/*.ascii dict/cmudict.0.6d dict/*.dict dict/fillerdict etc mv $ASCII_ZIP $PWD<file_sep>/scons/audioCollector.py import platform import os import fnmatch Import('javapath') Import('common') srcDir = os.path.normpath('../tools/audioCollector/src/java') clientSrcDir = os.path.normpath(srcDir + '/edu/cmu/sphinx/tools/datacollection/client/') serverSrcDir = os.path.normpath(srcDir + '/edu/cmu/sphinx/tools/datacollection/server/') clientClassDir = os.path.normpath('../../scons_build/classes/audioCollector/client') serverClassDir = os.path.normpath('../../scons_build/classes/audioCollector/server') sphinx_store = os.path.normpath('../tools/audioCollector/build/sphinx_store') javaHome = os.path.normpath(os.environ['JAVA_HOME']) libpath = '..' + os.sep + 'tools' + os.sep + 'common' + os.sep + 'lib' + os.sep classpath = libpath + 'batch.jar' + os.pathsep classpath += libpath + 'dom4j-1.6.1.jar' + os.pathsep classpath += libpath + 'forms_rt_license.jar' + os.pathsep classpath += libpath + 'forms_rt.jar' + os.pathsep classpath += libpath + 'javolution.jar' + os.pathsep classpath += libpath + 'sphinx4.jar' + os.pathsep classpath += libpath + 'plugin.jar' + os.pathsep classpath += str(common[0]) print classpath envServer = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS='-source 1.5 -classpath ' + classpath) serverClasses = envServer.Java(target = serverClassDir, source = serverSrcDir ) Depends(serverClasses, common) serverJarFile = os.path.normpath('../../scons_build/jars/datacollection-server.jar') serverJar = envServer.Jar(target = serverJarFile, source = serverClassDir, JARCHDIR=serverClassDir) envClient = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS='-source 1.5 -classpath ' + classpath) clientClasses = envClient.Java(target = clientClassDir, source = clientSrcDir ) Depends(clientClasses, common) clientJarFile = os.path.normpath('../../scons_build/jars/datacollection-client.jar') clientJar = envServer.Jar(target = clientJarFile, source = clientClassDir, JARCHDIR=clientClassDir) # Add images to the class dir so they'll end up in the jar for root, dirs, files in os.walk(top=clientSrcDir, topdown=False): for name in files: if fnmatch.fnmatch(name, '*.gif') == True: f = Install(root.replace(srcDir,clientClassDir), os.path.join(root, name)) Depends(f, clientClasses) Depends(clientJar, f) shipDir = '../../scons_ship/audioCollector' shipAudioCollector = Alias('foo', shipDir) Install(shipDir + '/jsps', '../tools/audioCollector/src/jsps/audio_collector.jsp') Install(shipDir + '/jsps', '../tools/audioCollector/src/jsps/corpus_store.jsp') Install(shipDir + '/jsps', '../tools/audioCollector/src/jsps/login_process.jsp') Install(shipDir + '/jsps', '../tools/audioCollector/src/jsps/login.jsp') Install(shipDir + '/configs', '../tools/audioCollector/data/samples/recorder.config.xml') Install(shipDir + '/configs', '../tools/audioCollector/data/samples/subjects.xml') Install(shipDir + '/configs', '../tools/audioCollector/data/samples/transcripts_en_us.txt') Install(shipDir + '/configs', '../tools/audioCollector/data/samples/transcripts_zh.txt') #Install server jars Install(shipDir + '/WEB-INF', '../tools/audioCollector/data/configs/web.xml') loc = Install(shipDir + '/WEB-INF/lib', '../tools/common/lib/batch.jar') sign = envServer.Command('noSuchFile0', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir + '/WEB-INF/lib', '../tools/common/lib/javolution.jar') sign = envServer.Command('noSuchFile1', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir + '/WEB-INF/lib', '../tools/common/lib/sphinx4.jar') sign = envServer.Command('noSuchFile2', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir + '/WEB-INF/lib', serverJarFile) sign = envServer.Command('noSuchFile3', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = InstallAs(shipDir + '/WEB-INF/lib/corpus.jar', str(common[0])) sign = envServer.Command('noSuchFile4', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) #Install client jars & sign them loc = Install(shipDir, '../tools/common/lib/batch.jar') sign = envServer.Command('noSuchFile5', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir, '../tools/common/lib/javolution.jar') sign = envServer.Command('noSuchFile6', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir, '../tools/common/lib/sphinx4.jar') sign = envServer.Command('noSuchFile7', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = Install(shipDir, clientJarFile) sign = envServer.Command('noSuchFile8', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) loc = InstallAs(shipDir + '/corpus.jar', str(common[0])) sign = envServer.Command('noSuchFile9', loc, "jarsigner -keystore " + sphinx_store + " -storepass <PASSWORD> $SOURCE audiocollector") Depends(shipAudioCollector, sign) audioCollector = Alias('foo2', [serverJar, clientJar]) Export('audioCollector') Export('shipAudioCollector') <file_sep>/archive_s3/s3.0/src/libmisc/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../../Makefile.defines VPATH = .:.. TARGET = libmisc.a OBJS = logs3.o vector.o corpus.o dictmisc.o $(TARGET): $(OBJS) ar crv $@ $? ranlib $@ install: $(TARGET) cp $(TARGET) $(S3LIBDIR) vq_test : vector.c $(CC) $(CMDFLAGS) -D_VQ_TEST_=1 $(CFLAGS) -o $@ $> -lutil -lm clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/archive_s3/s3/doc/readme.html <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta name="Microsoft Theme 2.00" content="sumipntg 011"> <meta http-equiv=Content-Type content="text/html; charset=windows-1252"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 9"> <meta name=Originator content="Microsoft Word 9"> <link rel=File-List href="./readme_files/filelist.xml"> <link rel=Edit-Time-Data href="./readme_files/editdata.mso"> <!--[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--> <title>D:/SPHINX</title> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>RHoughton</o:Author> <o:LastAuthor>RHoughton</o:LastAuthor> <o:Revision>2</o:Revision> <o:TotalTime>79</o:TotalTime> <o:Created>2001-02-07T20:08:00Z</o:Created> <o:LastSaved>2001-02-07T20:08:00Z</o:LastSaved> <o:Pages>2</o:Pages> <o:Words>710</o:Words> <o:Characters>4049</o:Characters> <o:Company>MediaSite Inc.</o:Company> <o:Lines>33</o:Lines> <o:Paragraphs>8</o:Paragraphs> <o:CharactersWithSpaces>4972</o:CharactersWithSpaces> <o:Version>9.2720</o:Version> </o:DocumentProperties> </xml><![endif]--> <style> <!-- /* Font Definitions */ @font-face {font-family:Wingdings; panose-1:5 0 0 0 0 0 0 0 0 0; mso-font-charset:2; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:0 268435456 0 0 -2147483648 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} h1 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; page-break-after:avoid; mso-outline-level:1; font-size:24.0pt; font-family:Verdana; mso-bidi-font-family:Arial; color:#003366; mso-font-kerning:16.0pt; font-weight:normal; mso-bidi-font-weight:bold;} h2 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; page-break-after:avoid; mso-outline-level:2; font-size:18.0pt; font-family:Verdana; mso-bidi-font-family:Arial; color:#003366; font-weight:normal; mso-bidi-font-weight:bold; mso-bidi-font-style:italic;} h3 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; page-break-after:avoid; mso-outline-level:3; font-size:14.0pt; font-family:Verdana; mso-bidi-font-family:Arial; color:#003366; font-weight:normal; mso-bidi-font-weight:bold;} h4 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; page-break-after:avoid; mso-outline-level:4; font-size:12.0pt; font-family:Verdana; color:#003366; font-weight:normal; mso-bidi-font-weight:bold;} h5 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; mso-outline-level:5; font-size:10.0pt; font-family:Verdana; color:#003366; font-weight:normal; mso-bidi-font-weight:bold; mso-bidi-font-style:italic;} h6 {mso-style-next:Normal; margin-top:12.0pt; margin-right:0in; margin-bottom:3.0pt; margin-left:0in; mso-pagination:widow-orphan; mso-outline-level:6; font-size:8.0pt; font-family:Verdana; color:#003366; font-weight:normal; mso-bidi-font-weight:bold;} p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} p.MsoFooter, li.MsoFooter, div.MsoFooter {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} p.MsoTitle, li.MsoTitle, div.MsoTitle {margin:0in; margin-bottom:.0001pt; text-align:center; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066; font-weight:bold; font-style:italic;} p.MsoBodyTextIndent, li.MsoBodyTextIndent, div.MsoBodyTextIndent {margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:.5in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} p.MsoBodyTextIndent2, li.MsoBodyTextIndent2, div.MsoBodyTextIndent2 {margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:27.0pt; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} p.MsoBodyTextIndent3, li.MsoBodyTextIndent3, div.MsoBodyTextIndent3 {margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:.75in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:Verdana; mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; color:#000066;} a:link, span.MsoHyperlink {color:#3333CC; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {color:#666699; text-decoration:underline; text-underline:single;} @page Section1 {size:8.5in 11.0in; margin:.75in 1.0in .75in 1.0in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-footer:url("./readme_files/header.htm") f1; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:146824490; mso-list-type:hybrid; mso-list-template-ids:-546135298 67698689 67698691 67698693 67698689 67698691 67698693 67698689 67698691 67698693;} @list l0:level1 {mso-level-number-format:bullet; mso-level-text:\F0B7; mso-level-tab-stop:1.0in; mso-level-number-position:left; margin-left:1.0in; text-indent:-.25in; font-family:Symbol;} @list l1 {mso-list-id:705761286; mso-list-type:hybrid; mso-list-template-ids:-1056683582 67698689 67698691 67698693 67698689 67698691 67698693 67698689 67698691 67698693;} @list l1:level1 {mso-level-number-format:bullet; mso-level-text:\F0B7; mso-level-tab-stop:.5in; mso-level-number-position:left; text-indent:-.25in; font-family:Symbol;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} --> </style> <!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="2050"/> </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif]--> </head> <body bgcolor=white background="./readme_files/image001.jpg" lang=EN-US link="#3333cc" vlink="#666699" style='tab-interval:.5in'> <!--[if gte mso 9]><xml> <v:background id="_x0000_s1025" o:bwmode="white" o:targetscreensize="800,600"> <v:fill src="./readme_files/image001.jpg" o:title="sumtextb" type="frame"/> </v:background></xml><![endif]--> <div class=Section1> <p class=MsoTitle><a name="_top"></a><span style='font-size:10.0pt;mso-bidi-font-size: 12.0pt;font-style:normal'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoTitle><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt; font-style:normal'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoTitle><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt; font-style:normal'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoTitle align=left style='text-align:left'><span style='font-style: normal'>D:/SPHINX:<o:p></o:p></span></p> <p class=MsoTitle align=left style='text-align:left'><span style='font-style: normal'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoTitle align=left style='text-align:left'><span style='font-weight: normal;font-style:normal'>Under this directory lives most of the files on which I am working. The latest versions of everything are under here. This is also the location of most of my testing/evaluation. It also contains the acoustic and language models that I frequently use. It is designed to encompass everything.<o:p></o:p></span></p> <p class=MsoTitle align=left style='text-align:left'><span style='font-weight: normal;font-style:normal'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoNormal style='margin-left:.25in'><b>S3.3:<o:p></o:p></b></p> <p class=MsoBodyTextIndent2>This is the current working SPHINX III. 3.3 code base. It contains a front end that allows for stream processing. However 3.3 does not split nor parse the incoming audio data. It assumes it has been segmented already.<span style="mso-spacerun: yes">† </span>Various models under S3.3 are designed to deal with segmentation. (Note at this point there is not a WIN32 tool that will create a .ctl file, all segmentation performed at this time is done live.)</p> <p class=MsoNormal style='margin-left:.5in;tab-stops:list .5in'><span style='font-size:10.0pt;font-family:"Times New Roman";color:windowtext'><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_i1025" type="#_x0000_t75" style='width:11.25pt; height:11.25pt' o:bullet="t"> <v:imagedata src="./readme_files/image002.gif" o:title="sumbul1a"/> </v:shape><![endif]--><![if !vml]><img width=15 height=15 src="./readme_files/image002.gif" alt="*" v:shapes="_x0000_i1025"><![endif]><span style="mso-spacerun: yes">†</span></span><b>Src/<a name="Decode_audiofile">Decode_audiofile:</a></b><span style='mso-bookmark:Decode_audiofile'></span></p> <p class=MsoBodyTextIndent3>This is the current working directory for decoding audio files. As of 2/6/2001 it contains the most recent versions of everything. (This code base was developed from <a href="#Seg_ad">Seg_ad</a>.)</p> <p class=MsoBodyTextIndent3>This code decodes a raw audio file (ideally extracted from a media file via <a href="#ExtractAudio">ExtractAudio</a>). It performs segmentation and melcep computation in a live fashion. It is a single pass decode on the raw audio file. </p> <p class=MsoBodyTextIndent3>It takes as input a SPHINX III argument file, the raw audio filename and the output filename.</p> <p class=MsoBodyTextIndent3>It produces an output file consisting of each word recognized, its start and end frame (in speech frames, 10ms/frame), its acoustic score, its language model score and its type.</p> <p class=MsoBodyTextIndent3>See <a href="#CreateTRS">Perl/CreateTRS.pl</a> for a script that generates a format compatible with Claude Barras (DGA) and LDCís <a href="http://www.etca.fr/CTA/gip/Projets/Transcriber/">Transcriber</a> program.</p> <p class=MsoBodyTextIndent3>This file <a href="s3.html">S3.html</a> contains information regarding the parameters for the arguments file needed for SPHINX 3. </p> <p class=MsoNormal style='margin-left:.5in;tab-stops:list .5in'><span style='font-size:10.0pt;color:windowtext'><!--[if gte vml 1]><v:shape id="_x0000_i1026" type="#_x0000_t75" style='width:11.25pt;height:11.25pt' o:bullet="t"> <v:imagedata src="./readme_files/image002.gif" o:title="sumbul1a"/> </v:shape><![endif]--><![if !vml]><img border=0 width=15 height=15 src="./readme_files/image002.gif" alt="*" v:shapes="_x0000_i1026"><![endif]></span><span style='mso-bidi-font-size:10.0pt;color:windowtext'><span style="mso-spacerun: yes">†</span><b>Src/decodeaudiofile_broken:<o:p></o:p></b></span></p> <p class=MsoBodyTextIndent3 style='tab-stops:list .75in'>Contains working files on the first version of decoding a raw audio file. It is based on cont_seg. There is a bug in the distributed version of cont_seg that doesnít work correctly with files. (Cont_seg was designed to process audio from soundcard with single speaker.) This work has been replaced/updated with decode_audiofile.</p> <p class=MsoNormal style='margin-left:.5in;tab-stops:list .5in'><span style='font-size:10.0pt;color:windowtext'><!--[if gte vml 1]><v:shape id="_x0000_i1027" type="#_x0000_t75" style='width:11.25pt;height:11.25pt' o:bullet="t"> <v:imagedata src="./readme_files/image002.gif" o:title="sumbul1a"/> </v:shape><![endif]--><![if !vml]><img border=0 width=15 height=15 src="./readme_files/image002.gif" alt="*" v:shapes="_x0000_i1027"><![endif]><span style="mso-spacerun: yes">†</span></span><b>Src/live</b>:</p> <p class=MsoNormal style='margin-left:.75in'>This is where the live code is for running SPHINX III on audio captured from a sound card. It works, however it has barely<span style="mso-spacerun: yes">† </span>been tested.</p> <p class=MsoNormal style='margin-left:.5in;tab-stops:list .5in'><span style='font-size:10.0pt;color:windowtext'><!--[if gte vml 1]><v:shape id="_x0000_i1028" type="#_x0000_t75" style='width:11.25pt;height:11.25pt' o:bullet="t"> <v:imagedata src="./readme_files/image002.gif" o:title="sumbul1a"/> </v:shape><![endif]--><![if !vml]><img border=0 width=15 height=15 src="./readme_files/image002.gif" alt="*" v:shapes="_x0000_i1028"><![endif]><span style="mso-spacerun: yes">†</span></span><b><span style='mso-bidi-font-size: 10.0pt;color:windowtext'>Src/win32:<o:p></o:p></span></b></p> <p class=MsoNormal style='margin-left:.75in;tab-stops:list .75in'><span style='mso-bidi-font-size:10.0pt;color:windowtext'>Contains the Microsoft Visual Studio project for building SPHINX 3.3.</span><b><o:p></o:p></b></p> <p class=MsoNormal style='margin-left:.75in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoNormal style='margin-left:.5in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoNormal style='margin-left:.5in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoNormal style='margin-left:.25in'><a name="Seg_ad"><b>Seg_ad</b></a><b>:<o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>This directory contains my working files for a segmentation algorithm based solely on adc or raw data. This is mostly a working/testing directory; the files developed here were moved directly into s3.3/src/audiofile_decode. And more progress was made.</p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:.25in'><a name=ExtractAudio><b>ExtractAudio:</b></a><b><o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>Contains the code for using the filter that Darmesh wrote. The code is designed for extracting and converting the audio from a media file. The audio is extracted and downsampled to 16Khz, 16bit, mono. (I donít know which channel is extracted.)</p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:.25in'><b>Perl:<o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>This directory contains misc. Perl scripts for processing different things. Most of them are hacking scripts of little importance. If it seems useful, Iíll list it here.</p> <p class=MsoBodyTextIndent style='tab-stops:list 63.0pt'><span style='font-size:10.0pt;color:windowtext'><!--[if gte vml 1]><v:shape id="_x0000_i1029" type="#_x0000_t75" style='width:11.25pt;height:11.25pt' o:bullet="t"> <v:imagedata src="./readme_files/image002.gif" o:title="sumbul1a"/> </v:shape><![endif]--><![if !vml]><img border=0 width=15 height=15 src="./readme_files/image002.gif" alt="*" v:shapes="_x0000_i1029"><![endif]><span style='mso-tab-count:1'>††† </span></span><a name=CreateTRS><b><span style='mso-bidi-font-size:10.0pt;color:windowtext'>CreateTRS.pl</span></b></a><b><span style='mso-bidi-font-size:10.0pt;color:windowtext'>:<o:p></o:p></span></b></p> <p class=MsoBodyTextIndent style='margin-left:.75in'>This script takes the output of <a href="#Decode_audiofile">Decode_audiofile</a> and creates a .trs file that can be read by <a href="http://www.etca.fr/CTA/gip/Projets/Transcriber/">Transcriber</a>. This is very useful for checking alignment or quickly comparing the output of the decoder with the audio. (It is also possible to edit/manipulate word boundaries.)</p> <p class=MsoBodyTextIndent style='margin-left:.75in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:.25in'><b>HUB97_models:<o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>This directory contains the HUB97 continuous acoustic models (as well as a large BN language model). The documentation explaining the models and how they were trained is here: <a href="BN_AM_HUB97.doc">BN_AM_HUB97.doc</a> or <a href="BN_AM_HUB97.htm">BN_AM_HUB97.htm</a>. (The .doc may be more update to day purely due to laziness.)</p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:.25in'><b>Fastdecoder:<o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>This directory contains the s3.2 source code with MS Visual Studio projects for building. The project files make sure of the Intel Compiler for optimal performance. </p> <p class=MsoBodyTextIndent style='margin-left:.25in'><b>Fastdecoder_timing:<o:p></o:p></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>This directory contains the output of many different testing runs to compare speech/accuracy of different system tweaks. Also compared different hardware. (e.g PC133 CAS2 memory vs. RDRAM PC800 memory.)</p> <p class=MsoBodyTextIndent style='margin-left:0in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:0in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:0in'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent align=center style='margin-left:0in;text-align:center'><b><u><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt'>Some sources of SPHINX Documentation<o:p></o:p></span></u></b></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>Raviís talk on the Sphinx 3 transition to Sphinx 3.2 is here: <a href="s3-2.htm">HTML</a> or <a href="s3-2.ppt">PPT</a>.</p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>Raviís slides for his exit and codewalk talks are here: <a href="ravi_codewalk.html">HTML</a></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>Raviís Sphinx 3 decoder talk is here: <a href="s3.html">local HTML</a> </p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>Ritaís SPHINX training FAQ is here: <a href="rita_training.html">local HTML</a> or <a href="http://www.cs.cmu.edu/~rsingh/sphinxman/FAQ.html">remote HTML</a> (Remote promises to be more up to date.)</p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> <p class=MsoBodyTextIndent style='margin-left:27.0pt'>CMU Speech web page: <a href="http://www.speech.cs.cmu.edu/">www.speech.cs.cmu.edu</a> </p> </div> </body> </html> <file_sep>/SphinxTrain/src/programs/cdcn_train/store_distribution.c /* ==================================================================== * Copyright (c) 1994-2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <stdio.h> #include "header.h" int store_distribution(char *file, int Nmodes, int Ndim, float noisec, float *noisemean, float *noisevar, float *c, float **mean, float **var) { int i, j; FILE *outputfile; /* * We need to adjust for noise mode * Therefore, the actual number of modes in the distribution * (including the noise mode) is Nmodes + 1 at this point. */ if ((outputfile = fopen(file, "w")) == NULL) return (-1); fprintf(outputfile, "%d %d\n", Nmodes + 1, Ndim); fprintf(outputfile, "%f\n", noisec); for (j = 0; j < Ndim; ++j) fprintf(outputfile, "%f ", noisemean[j]); fprintf(outputfile, "\n"); for (j = 0; j < Ndim; ++j) fprintf(outputfile, "%f ", noisevar[j]); fprintf(outputfile, "\n"); /* * The variance is printed for each mode to maintain uniformity of * distribution file structure for other algorithms we use */ for (i = 0; i < Nmodes; ++i) { fprintf(outputfile, "%f\n", (1.0 - noisec) * c[i]); for (j = 0; j < Ndim; ++j) fprintf(outputfile, "%f ", mean[i][j]); fprintf(outputfile, "\n"); for (j = 0; j < Ndim; ++j) fprintf(outputfile, "%f ", var[i][j]); fprintf(outputfile, "\n"); } fclose(outputfile); printf("Wrote distribution to %s\n", file); fflush(stdout); return (0); } <file_sep>/archive_s3/s3/src/tests/an4/Makefile # ==================================================================== # # Sphinx III # # ==================================================================== TOP=`(cd ../../..; pwd)` DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = # LIVEDECSRCS = # MAINSRCS = # OTHERSRCS = main.c # LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile LIBNAME= tests BINDIR = $(TOP)/bin/$(MACHINE) ifeq ($(MODE),quick) MODEAFFIX = _quick else MODE = endif an4_words_unigram: rm -f gmake-an4_words_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_words_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_words.unigram.lm.DMP" >> ARGS.an4_words_unigram$(MODEAFFIX) echo "-ctlfn an4_words$(MODEAFFIX).ctl" >> ARGS.an4_words_unigram$(MODEAFFIX) echo "-matchfn an4_words_unigram$(MODEAFFIX).match" >> ARGS.an4_words_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_words_unigram$(MODEAFFIX) > gmake-an4_words_unigram$(MODEAFFIX).resultss $(BINDIR)/align -ref an4_words$(MODEAFFIX).ref -hyp an4_words_unigram$(MODEAFFIX).match > an4_words_unigram$(MODEAFFIX).align an4_spelling_unigram: rm -f gmake-an4_spelling_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_spelling_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_spelling.unigram.lm.DMP" >> ARGS.an4_spelling_unigram$(MODEAFFIX) echo "-ctlfn an4_spelling$(MODEAFFIX).ctl" >> ARGS.an4_spelling_unigram$(MODEAFFIX) echo "-matchfn an4_spelling_unigram$(MODEAFFIX).match" >> ARGS.an4_spelling_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_spelling_unigram$(MODEAFFIX) > gmake-an4_spelling_unigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_spelling$(MODEAFFIX).ref -hyp an4_spelling_unigram$(MODEAFFIX).match > an4_spelling_unigram$(MODEAFFIX).align an4_full_unigram: rm -f gmake-an4_full_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_full_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_full.unigram.lm.DMP" >> ARGS.an4_full_unigram$(MODEAFFIX) echo "-ctlfn an4_full$(MODEAFFIX).ctl" >> ARGS.an4_full_unigram$(MODEAFFIX) echo "-matchfn an4_full_unigram$(MODEAFFIX).match" >> ARGS.an4_full_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_full_unigram$(MODEAFFIX) > gmake-an4_full_unigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_full$(MODEAFFIX).ref -hyp an4_full_unigram$(MODEAFFIX).match > an4_full_unigram$(MODEAFFIX).align an4_words_flat_unigram: rm -f gmake-an4_words_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_words_flat_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_words.flat_unigram.lm.DMP" >> ARGS.an4_words_flat_unigram$(MODEAFFIX) echo "-ctlfn an4_words$(MODEAFFIX).ctl" >> ARGS.an4_words_flat_unigram$(MODEAFFIX) echo "-matchfn an4_words_flat_unigram$(MODEAFFIX).match" >> ARGS.an4_words_flat_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_words_flat_unigram$(MODEAFFIX) > gmake-an4_words_flat_unigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_words$(MODEAFFIX).ref -hyp an4_words_flat_unigram$(MODEAFFIX).match > an4_words_flat_unigram$(MODEAFFIX).align an4_spelling_flat_unigram: rm -f gmake-an4_spelling_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_spelling_flat_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_spelling.flat_unigram.lm.DMP" >> ARGS.an4_spelling_flat_unigram$(MODEAFFIX) echo "-ctlfn an4_spelling$(MODEAFFIX).ctl" >> ARGS.an4_spelling_flat_unigram$(MODEAFFIX) echo "-matchfn an4_spelling_flat_unigram$(MODEAFFIX).match" >> ARGS.an4_spelling_flat_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_spelling_flat_unigram$(MODEAFFIX) > gmake-an4_spelling_flat_unigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_spelling$(MODEAFFIX).ref -hyp an4_spelling_flat_unigram$(MODEAFFIX).match > an4_spelling_flat_unigram$(MODEAFFIX).align an4_full_flat_unigram: rm -f gmake-an4_full_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_full_flat_unigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_full.flat_unigram.lm.DMP" >> ARGS.an4_full_flat_unigram$(MODEAFFIX) echo "-ctlfn an4_full$(MODEAFFIX).ctl" >> ARGS.an4_full_flat_unigram$(MODEAFFIX) echo "-matchfn an4_full_flat_unigram$(MODEAFFIX).match" >> ARGS.an4_full_flat_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_full_flat_unigram$(MODEAFFIX) > gmake-an4_full_flat_unigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_full$(MODEAFFIX).ref -hyp an4_full_flat_unigram$(MODEAFFIX).match > an4_full_flat_unigram$(MODEAFFIX).align an4_words_bigram: rm -f gmake-an4_words_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_words_bigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_words.bigram.lm.DMP" >> ARGS.an4_words_bigram$(MODEAFFIX) echo "-ctlfn an4_words$(MODEAFFIX).ctl" >> ARGS.an4_words_bigram$(MODEAFFIX) echo "-matchfn an4_words_bigram$(MODEAFFIX).match" >> ARGS.an4_words_bigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_words_bigram$(MODEAFFIX) > gmake-an4_words_bigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_words$(MODEAFFIX).ref -hyp an4_words_bigram$(MODEAFFIX).match > an4_words_bigram$(MODEAFFIX).align an4_spelling_bigram: rm -f gmake-an4_spelling_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_spelling_bigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_spelling.bigram.lm.DMP" >> ARGS.an4_spelling_bigram$(MODEAFFIX) echo "-ctlfn an4_spelling$(MODEAFFIX).ctl" >> ARGS.an4_spelling_bigram$(MODEAFFIX) echo "-matchfn an4_spelling_bigram$(MODEAFFIX).match" >> ARGS.an4_spelling_bigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_spelling_bigram$(MODEAFFIX) > gmake-an4_spelling_bigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_spelling$(MODEAFFIX).ref -hyp an4_spelling_bigram$(MODEAFFIX).match > an4_spelling_bigram$(MODEAFFIX).align an4_full_bigram: rm -f gmake-an4_full_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_full_bigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_full.bigram.lm.DMP" >> ARGS.an4_full_bigram$(MODEAFFIX) echo "-ctlfn an4_full$(MODEAFFIX).ctl" >> ARGS.an4_full_bigram$(MODEAFFIX) echo "-matchfn an4_full_bigram$(MODEAFFIX).match" >> ARGS.an4_full_bigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_full_bigram$(MODEAFFIX) > gmake-an4_full_bigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_full$(MODEAFFIX).ref -hyp an4_full_bigram$(MODEAFFIX).match > an4_full_bigram$(MODEAFFIX).align an4_words_trigram: rm -f gmake-an4_words_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_words_trigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_words.trigram.lm.DMP" >> ARGS.an4_words_trigram$(MODEAFFIX) echo "-ctlfn an4_words$(MODEAFFIX).ctl" >> ARGS.an4_words_trigram$(MODEAFFIX) echo "-matchfn an4_words_trigram$(MODEAFFIX).match" >> ARGS.an4_words_trigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_words_trigram$(MODEAFFIX) > gmake-an4_words_trigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_words$(MODEAFFIX).ref -hyp an4_words_trigram$(MODEAFFIX).match > an4_words_trigram$(MODEAFFIX).align an4_spelling_trigram: rm -f gmake-an4_spelling_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_spelling_trigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_spelling.trigram.lm.DMP" >> ARGS.an4_spelling_trigram$(MODEAFFIX) echo "-ctlfn an4_spelling$(MODEAFFIX).ctl" >> ARGS.an4_spelling_trigram$(MODEAFFIX) echo "-matchfn an4_spelling_trigram$(MODEAFFIX).match" >> ARGS.an4_spelling_trigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_spelling_trigram$(MODEAFFIX) > gmake-an4_spelling_trigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_spelling$(MODEAFFIX).ref -hyp an4_spelling_trigram$(MODEAFFIX).match > an4_spelling_trigram$(MODEAFFIX).align an4_full_trigram: rm -f gmake-an4_full_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_full_trigram$(MODEAFFIX) echo "-lmfn /lab/speech/sphinx4/data/an4/lists/an4_full.trigram.lm.DMP" >> ARGS.an4_full_trigram$(MODEAFFIX) echo "-ctlfn an4_full$(MODEAFFIX).ctl" >> ARGS.an4_full_trigram$(MODEAFFIX) echo "-matchfn an4_full_trigram$(MODEAFFIX).match" >> ARGS.an4_full_trigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.an4_full_trigram$(MODEAFFIX) > gmake-an4_full_trigram$(MODEAFFIX).results $(BINDIR)/align -ref an4_full$(MODEAFFIX).ref -hyp an4_full_trigram$(MODEAFFIX).match > an4_full_trigram$(MODEAFFIX).align <file_sep>/archive_s3/s3.2/src/hyp.h /* * hyp.h -- Hypothesis structures. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Jun-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _S3_HYP_H_ #define _S3_HYP_H_ #include <libutil/libutil.h> typedef struct { int32 id; /* Token ID; could be s3wid_t, s3cipid_t... Interpreted by client. */ int32 vhid; /* Viterbi history (lattice) ID from which this entry created */ int32 sf, ef; /* Start/end frames, inclusive, for this segment */ int32 ascr; /* Segment acoustic score */ int32 lscr; /* LM score for transition to this segment (if applicable) */ int32 type; /* Uninterpreted data; see vithist_entry_t in vithist.h */ } hyp_t; #endif <file_sep>/SphinxTrain/include/s3/corpus.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: corpus.h * * Description: * * Author: * $Author$ *********************************************************************/ #ifndef CORPUS_H #define CORPUS_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/prim_type.h> #include <s3/vector.h> #include <s3/acmod_set_ds.h> #include <s3/s3phseg_io.h> #include <stdio.h> #include <stddef.h> /* MFCC directory/extension configuration functions */ int corpus_set_mfcc_dir(const char *root); int corpus_set_mfcc_ext(const char *ext); /* seg file configuration functions */ int corpus_set_seg_dir(const char *root); int corpus_set_seg_ext(const char *ext); /* phone seg configuration functions */ int corpus_set_phseg_dir(const char *dir); int corpus_set_phseg_ext(const char *ext); /* sent file configuration functions */ int corpus_set_sent_dir(const char *root); int corpus_set_sent_ext(const char *ext); /* Vector quantized feature functions */ int corpus_set_ccode_dir(const char *root); int corpus_set_ccode_ext(const char *ext); int corpus_set_dcode_dir(const char *root); int corpus_set_dcode_ext(const char *ext); int corpus_set_pcode_dir(const char *root); int corpus_set_pcode_ext(const char *ext); int corpus_set_ddcode_dir(const char *root); int corpus_set_ddcode_ext(const char *ext); void corpus_set_full_suffix_match(uint32 state); /* Corpus LSN file configuration functions */ int corpus_set_lsn_filename(const char *fn); /* Corpus silence frame deletion */ int corpus_set_sildel_filename(const char *fn); /* Per utterance MLLR transforms */ int corpus_set_mllr_filename(const char *fn); int corpus_set_mllr_dir(const char *fn); /* checkpoint the corpus module (i.e. write out offset and remaining run length) */ int corpus_ckpt(const char *fn); int corpus_set_ctl_host(char *host_port_spec); /* Control file configuration functions */ int corpus_set_ctl_filename(const char *filename); int corpus_set_interval(uint32 n_skip, uint32 run_len); /* set the offset and run length from a checkpoint file */ int corpus_ckpt_set_interval(const char *fn); int corpus_set_partition(uint32 r, uint32 of_s); uint32 corpus_get_begin(void); /* Initialization function to be called after configuration functions */ int corpus_init(void); /* After reaching the end of a (sub)corpus. This * call sets things up as they were after corpus_init() */ int corpus_reset(void); /* data access/info functions */ int corpus_next_utt(void); char * corpus_utt_full_name(void); char * corpus_utt_brief_name(void); char * corpus_utt(void); int32 corpus_provides_sent(void); int corpus_get_sent(char **trans); int corpus_has_xfrm(void); int corpus_get_xfrm(float32 *****out_a, float32 ****out_b, const uint32 **out_veclen, uint32 *out_n_mllrcls, uint32 *out_n_stream); int32 corpus_provides_mfcc(void); int corpus_get_mfcc(vector_t **mfc, uint32 *n_frame, uint32 *veclen); int corpus_get_generic_featurevec(vector_t **mfc, uint32 *n_frame, uint32 veclen); int corpus_get_sildel(uint32 **sf, uint32 **ef, uint32 *n_seg); int32 corpus_provides_seg(void); int corpus_get_seg(uint16 **seg, uint32 *n_frame); int32 corpus_provides_phseg(void); int corpus_get_phseg(acmod_set_t *acmod_set, s3phseg_t **out_phseg); int32 corpus_provides_ccode(void); int corpus_get_ccode(unsigned char **ccode, uint32 *n_frame); int32 corpus_provides_dcode(void); int corpus_get_dcode(unsigned char **dcode, uint32 *n_frame); int32 corpus_provides_pcode(void); int corpus_get_pcode(unsigned char **pcode, uint32 *n_frame); int32 corpus_provides_ddcode(void); int corpus_get_ddcode(unsigned char **ddcode, uint32 *n_frame); #ifdef __cplusplus } #endif #endif /* CORPUS_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2006/04/17 18:34:46 egouvea * Added s3phseg_io to the MS Dev .dsp file. Added missing function * prototypes to corpus.h. * * Revision 1.5 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.10 97/07/18 14:04:42 eht * Added corpus_reset() call * * Revision 1.9 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.8 1996/03/26 15:18:39 eht * Fix local function definition * * Revision 1.7 1996/03/25 15:50:59 eht * Added VQ code functions * * Revision 1.6 1996/03/05 14:22:29 eht * Added include of <stdio.h> so that FILE type is resolved * * Revision 1.5 1996/03/05 14:21:26 eht * Added ability to check whether the corpus module is * configured to provide each data type. * * Revision 1.4 1995/12/01 19:54:13 eht * Added prototype for corpus_get_seg() * * Revision 1.3 1995/12/01 17:59:57 eht * - Add ability to get state segmentation data for each utterance * - Add ability to skip certain data types if not interested in them * (e.g. a decoder is not necessarily interested in word transcript or * state segmentation data). * - Added corpus_utt() function to just get the utt id * * Revision 1.2 1995/10/10 13:10:34 eht * Changed to use <s3/prim_type.h> * * Revision 1.1 1995/10/09 21:04:24 eht * Initial revision * * Revision 1.4 1995/09/08 19:13:52 eht * Updated to remove references to pset module and add references * to acmod_set module * * Revision 1.3 1995/08/29 12:21:00 eht * Interface change (part 2) * * Revision 1.2 1995/08/29 12:16:43 eht * Interface change * * Revision 1.1 1995/08/15 13:44:14 eht * Initial revision * * */ <file_sep>/archive_s3/s3.2/src/kb.h /* * kb.h -- Knowledge bases, search parameters, and auxiliary structures for decoding * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 07-Jul-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added kb_t.ci_active. * * 02-Jun-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_KB_H_ #define _S3_KB_H_ #include <libutil/libutil.h> #include "kbcore.h" #include "lextree.h" #include "vithist.h" #include "ascr.h" #include "beam.h" /* * There can be several unigram lextrees. If we're at the end of frame f, we can only * transition into the roots of lextree[(f+1) % n_lextree]; same for fillertree[]. This * alleviates the problem of excessive Viterbi pruning in lextrees. */ typedef struct { kbcore_t *kbcore; /* Core model structures */ int32 n_lextree; /* See above comment about n_lextree */ lextree_t **ugtree; lextree_t **fillertree; int32 n_lextrans; /* #Transitions to lextree (root) made so far */ vithist_t *vithist; /* Viterbi history, built during search */ float32 ***feat; /* Feature frames */ int32 nfr; /* #Frames in feat in current utterance */ int32 *ssid_active; /* For determining the active senones in any frame */ int32 *comssid_active; int32 *sen_active; int32 bestscore; /* Best HMM state score in current frame */ int32 bestwordscore; /* Best wordexit HMM state score in current frame */ ascr_t *ascr; /* Senone and composite senone scores for one frame */ beam_t *beam; /* Beamwidth parameters */ char *uttid; int32 utt_hmm_eval; int32 utt_sen_eval; int32 utt_gau_eval; int32 *hmm_hist; /* Histogram: #frames in which a given no. of HMMs are active */ int32 hmm_hist_bins; /* #Bins in above histogram */ int32 hmm_hist_binsize; /* Binsize in above histogram (#HMMs/bin) */ ptmr_t tm_sen; ptmr_t tm_srch; int32 tot_fr; float64 tot_sen_eval; /* Senones evaluated over the entire session */ float64 tot_gau_eval; /* Gaussian densities evaluated over the entire session */ float64 tot_hmm_eval; /* HMMs evaluated over the entire session */ float64 tot_wd_exit; /* Words hypothesized over the entire session */ FILE *matchsegfp; } kb_t; #endif <file_sep>/archive_s3/s3.0/src/libutil/err.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * err.h -- Package for checking and catching common errors, printing out * errors nicely, etc. * * * 6/01/95 <NAME> CMU speech group */ #ifndef _LIBUTIL_ERR_H_ #define _LIBUTIL_ERR_H #include <stdarg.h> #include <errno.h> void _E__pr_header( const char *file, long line, const char *msg ); void _E__pr_info_header( char *file, long line, char *tag ); void _E__pr_warn( char *fmt, ... ); void _E__pr_info( char *fmt, ... ); void _E__die_error( char *fmt, ... ); void _E__abort_error( char *fmt, ... ); void _E__sys_error( char *fmt, ... ); void _E__fatal_sys_error( char *fmt, ... ); /* These three all abort */ /* core dump after error message */ #define E_ABORT _E__pr_header(__FILE__, __LINE__, "ERROR"),_E__abort_error /* exit with non-zero status after error message */ #define E_FATAL _E__pr_header(__FILE__, __LINE__, "FATAL_ERROR"),_E__die_error /* Print error text; Call perror(""); exit(errno); */ #define E_FATAL_SYSTEM _E__pr_header(__FILE__, __LINE__, "SYSTEM_ERROR"),_E__fatal_sys_error /* Print error text; Call perror(""); */ #define E_WARN_SYSTEM _E__pr_header(__FILE__, __LINE__, "SYSTEM_ERROR"),_E__sys_error /* Print error text; Call perror(""); */ #define E_ERROR_SYSTEM _E__pr_header(__FILE__, __LINE__, "SYSTEM_ERROR"),_E__sys_error /* Print logging information, warnings, or error messages; all to stderr */ #define E_INFO _E__pr_info_header(__FILE__, __LINE__, "INFO"),_E__pr_info #define E_WARN _E__pr_header(__FILE__, __LINE__, "WARNING"),_E__pr_warn #define E_ERROR _E__pr_header(__FILE__, __LINE__, "ERROR"),_E__pr_warn #endif /* !_ERR_H */ <file_sep>/SphinxTrain/src/programs/cdcn_train/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \nThis program computes a mixture gaussian distribution for a set of \nspeech cepstral files for use with CDCN. The first mode is computed on only\nthe silence portions of the speech to comply with the requirements of the \nalgorithm."; const char examplestr[]= "Example: \n\ \n\ cdcn_stats -cepext mfc \n\ -ctlfn stuff.ctl \n\ -outfn output.cdcn.dist \n\ -nmodes 32 \n\ -noisewidth 1.5 \n\ -tmpfn CDCN.tmp \n\ -ceplen 13 \n\ -stride 10 "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The control file name (enumerates utts in corpus)" }, { "-outfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output distribution file name" }, { "-cepdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the cepstrum files"}, { "-cepext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "mfc", "Extension of the cepstrum files"}, { "-maxframes", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "-1", "Maximum number of frames to read (or -1 for unlimited)"}, { "-cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A previous codebook to restart EM training from" }, { "-nmodes", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "32", "# of Gaussians to train"}, { "-noisewidth", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1.5", "Width of noise band"}, { "-ceplen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "13", "# of coefficients per cepstrum frame"}, { "-stride", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "Take every -stride'th frame when computing distribution" }, { "-vqiter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "5", "Max # of interations of VQ to get initial codebook"}, { "-vqthresh", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1e-6", "Convergence ratio for VQ"}, { "-emiter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "10", "# of interations of EM to estimate distributions"}, { "-emthresh", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1e-6", "Convergence ratio for EM"}, { "-tmpfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "CDCN.DIST.TEMP", "The temporary file name" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } <file_sep>/SphinxTrain/src/programs/init_gau/main.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * This routine uses a model definition file, a state parameter * definition file and a control file to create a set of initial * means and variance parameters for 1 density mixture Gaussian * context independent system. * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include "init_gau.h" #include "parse_cmd_ln.h" #include <s3/corpus.h> #include <s3/cmd_ln.h> #include <s3/lexicon.h> #include <s3/acmod_set.h> #include <s3/model_def_io.h> #include <s3/s3ts2cb_io.h> #include <s3/ts2cb.h> #include <s3/ckd_alloc.h> #include <s3/feat.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <string.h> static int initialize(lexicon_t **out_lex, model_def_t **out_mdef, int argc, char *argv[]) { lexicon_t *lex = NULL; model_def_t *mdef = NULL; const char *fdictfn; const char *dictfn; const char *ts2cbfn; uint32 n_ts; uint32 n_cb; /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); if (cmd_ln_access("-feat") != NULL) { feat_set(cmd_ln_str("-feat")); feat_set_in_veclen(cmd_ln_int32("-ceplen")); feat_set_subvecs(cmd_ln_str("-svspec")); } else { E_ERROR("Specify the feature extraction algorithm using -feat\n"); return S3_ERROR; } if (cmd_ln_access("-ldafn") != NULL) { if (feat_read_lda(cmd_ln_access("-ldafn"), cmd_ln_int32("-ldadim"))) { E_FATAL("Failed to read LDA matrix\n"); } } if (cmd_ln_access("-segdir")) corpus_set_seg_dir(cmd_ln_access("-segdir")); if (cmd_ln_access("-segext")) corpus_set_seg_ext(cmd_ln_access("-segext")); corpus_set_mfcc_dir(cmd_ln_access("-cepdir")); corpus_set_mfcc_ext(cmd_ln_access("-cepext")); if (cmd_ln_access("-lsnfn")) corpus_set_lsn_filename(cmd_ln_access("-lsnfn")); corpus_set_ctl_filename(cmd_ln_access("-ctlfn")); if ( cmd_ln_access("-nskip") && cmd_ln_access("-runlen") ) { corpus_set_interval(*(int32 *)cmd_ln_access("-nskip"), *(int32 *)cmd_ln_access("-runlen")); } else if (cmd_ln_access("-part") && cmd_ln_access("-npart")) { corpus_set_partition(*(uint32 *)cmd_ln_access("-part"), *(uint32 *)cmd_ln_access("-npart")); } if (corpus_init() != S3_SUCCESS) { return S3_ERROR; } if (cmd_ln_access("-moddeffn")) { E_INFO("Reading %s\n", cmd_ln_access("-moddeffn")); /* Read in the model definitions. Defines the set of CI phones and context dependent phones. Defines the transition matrix tying and state level tying. */ if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { return S3_ERROR; } ts2cbfn = (const char *)cmd_ln_access("-ts2cbfn"); if (strcmp(SEMI_LABEL, ts2cbfn) == 0) { mdef->cb = semi_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; n_cb = 1; } else if (strcmp(CONT_LABEL, ts2cbfn) == 0) { mdef->cb = cont_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; n_cb = mdef->n_tied_state; } else if (strcmp(PTM_LABEL, ts2cbfn) == 0) { mdef->cb = ptm_ts2cb(mdef); n_ts = mdef->n_tied_state; n_cb = mdef->acmod_set->n_ci; } else if (s3ts2cb_read(ts2cbfn, &mdef->cb, &n_ts, &n_cb) != S3_SUCCESS) { return S3_ERROR; } dictfn = cmd_ln_access("-dictfn"); if (dictfn == NULL) { E_FATAL("You must specify a content dictionary using -dictfn\n"); } E_INFO("Reading %s\n", dictfn); lex = lexicon_read(NULL, /* no lexicon to start */ dictfn, mdef->acmod_set); if (lex == NULL) return S3_ERROR; fdictfn = cmd_ln_access("-fdictfn"); if (fdictfn) { E_INFO("Reading %s\n", fdictfn); (void)lexicon_read(lex, /* add filler words content lexicon */ fdictfn, mdef->acmod_set); } } *out_mdef = mdef; *out_lex = lex; return S3_SUCCESS; } int main(int argc, char *argv[]) { lexicon_t *lex; model_def_t *mdef; if (initialize(&lex, &mdef, argc, argv) != S3_SUCCESS) { E_ERROR("errors initializing.\n"); return 1; } if (init_gau(lex, mdef) != S3_SUCCESS) { return 1; } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.9 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.8 96/08/06 14:15:15 eht * Define missing prototype * * Revision 1.7 1996/08/06 14:08:28 eht * Deal w/ new model definition structure which includes an acoustic model set * mapping structure * * Revision 1.6 1996/03/25 15:43:43 eht * Deal w setting the input feature vector length * Deal w/ -nskip and -runlen arguments * * Revision 1.5 1996/01/26 18:22:07 eht * Use the feat module. * * Revision 1.4 1995/12/14 20:00:17 eht * Added (void *) type cast for ckd_free() argument. * * Revision 1.3 1995/12/14 19:57:44 eht * Yet another interim development version * * Revision 1.2 1995/12/01 20:55:40 eht * interim development version * * Revision 1.1 1995/12/01 16:39:04 eht * Initial revision * * */ <file_sep>/tools/riddler/java/edu/cmu/sphinx/tools/riddler/shared/MetadataWrapper.java /** * Copyright 1999-2007 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * <p/> * User: <NAME> * Date: Mar 11, 2007 * Time: 6:50:17 PM */ package edu.cmu.sphinx.tools.riddler.shared; import java.util.HashMap; import java.util.Map; import java.io.Serializable; /** * HashMap wrapper class to work around the JAX-WS issue mentioned here: http://forums.java.net/jive/message.jspa?messageID=185244 * @author <NAME> */ public class MetadataWrapper implements Serializable { private Map<String, String> contents; public MetadataWrapper(Map<String, String> contents) { this.contents = contents; } public MetadataWrapper() { contents = new HashMap(); } public Map<String, String> getContents() { return contents; } public void setContents(Map<String, String> contents) { this.contents = contents; } public String toString() { return contents.toString(); } } <file_sep>/SphinxTrain/src/libs/libcommon/dtree.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: dtree.c * * Description: * State-tying decision tree routines. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/dtree.h> #include <s3/best_q.h> #include <s3/two_class.h> #include <s3/ckd_alloc.h> #include <s3/read_line.h> #include <s3/quest.h> #include <s3/div.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/cmd_ln.h> #include <assert.h> #include <stdio.h> #include <string.h> uint32 cnt_node(dtree_node_t *node) { if (!IS_LEAF(node)) { return cnt_node(node->y) + cnt_node(node->n) + 1; } else { return 1; } } uint32 reindex(dtree_node_t *node, uint32 *next_id) { node->node_id = (*next_id)++; if (!IS_LEAF(node)) { return reindex(node->y, next_id) + reindex(node->n, next_id) + 1; } else { return 1; } } dtree_node_t * get_node(dtree_node_t *node, uint32 id) { dtree_node_t *ret; if (node->node_id == id) return node; else if (!IS_LEAF(node)) { ret = get_node(node->y, id); if (ret != NULL) return ret; ret = get_node(node->n, id); return ret; } else { /* it is a leaf and it doesn't match */ return NULL; } } uint32 prune_lowentred(dtree_node_t *node, float32 entred_thr) { if (!IS_LEAF(node)) { /* Not a leaf node */ if (node->wt_ent < entred_thr) { return prune_subtrees(node); } else { return prune_lowentred(node->y, entred_thr) + prune_lowentred(node->n, entred_thr); } } else { return 0; } } uint32 prune_lowcnt(dtree_node_t *node, float32 cnt_thr) { if (!IS_LEAF(node)) { /* Not a leaf node */ if ((node->y->occ < cnt_thr) || (node->n->occ < cnt_thr)) { return prune_subtrees(node); } else { return prune_lowcnt(node->y, cnt_thr) + prune_lowcnt(node->n, cnt_thr); } } else { return 0; } } uint32 prune_subtrees(dtree_node_t *node) { uint32 n_pruned; if (!IS_LEAF(node)) { n_pruned = cnt_node(node->y) + cnt_node(node->n); prune_subtrees(node->y); node->y = NULL; prune_subtrees(node->n); node->n = NULL; return n_pruned; } else { /* it is a leaf node; nothing to do */ return 0; } } static void print_final_tree_recur(FILE *fp, dtree_node_t *node, pset_t *pset) { if (!IS_LEAF(node)) { fprintf(fp, "%u %u %u %e %e ", node->node_id, node->y->node_id, node->n->node_id, node->wt_ent_dec, node->occ); print_comp_quest(fp, pset, (comp_quest_t *)node->q); fprintf(fp, "\n"); print_final_tree_recur(fp, node->y, pset); print_final_tree_recur(fp, node->n, pset); } else { fprintf(fp, "%u - - %e %e\n", node->node_id, node->wt_ent, node->occ); } } void print_final_tree(FILE *fp, dtree_node_t *node, pset_t *pset) { fprintf(fp, "n_node %u\n", cnt_node(node)); print_final_tree_recur(fp, node, pset); } static void print_final_tree_recur_davinci(FILE *fp, dtree_node_t *node, pset_t *pset, uint32 *lvl) { uint32 i; (*lvl)++; if (!IS_LEAF(node)) { for (i = 0; i < *lvl * 4; i++) { fprintf(fp, " "); } fprintf(fp, "l(\"%u\",n(\"%u\",[a(\"OBJECT\",\"", node->node_id, node->node_id); print_comp_quest(fp, pset, (comp_quest_t *)node->q); fprintf(fp, "\")],\n"); for (i = 0; i < *lvl * 4; i++) { fprintf(fp, " "); } fprintf(fp, "[\n"); for (i = 0; i < *lvl * 4; i++) { fprintf(fp, " "); } fprintf(fp, "l(\"%u->%u\",e(\"\",[],\n", node->node_id, node->y->node_id); print_final_tree_recur_davinci(fp, node->y, pset, lvl); fprintf(fp, ")),\n"); for (i = 0; i < *lvl * 4; i++) { fprintf(fp, " "); } fprintf(fp, "l(\"%u->%u\",e(\"\",[],\n", node->node_id, node->n->node_id); print_final_tree_recur_davinci(fp, node->n, pset, lvl); fprintf(fp, "))]))\n"); } else { for (i = 0; i < *lvl * 4; i++) { fprintf(fp, " "); } fprintf(fp, "l(\"%u\",n(\"%u\",[a(\"OBJECT\",\"%u\")],[]))\n", node->node_id, node->node_id, node->clust); } (*lvl)--; } void print_final_tree_davinci(FILE *fp, dtree_node_t *node, pset_t *pset) { uint32 lvl = 0; fprintf(fp, "[\n"); print_final_tree_recur_davinci(fp, node, pset, &lvl); fprintf(fp, "]\n"); } dtree_t * read_final_tree(FILE *fp, pset_t *pset, uint32 n_pset) { dtree_t *out; dtree_node_t *node; uint32 n_node; char ln[4096], *s, str[128]; uint32 n_read, n_scan; uint32 i, node_id, node_id_y, node_id_n; comp_quest_t *q; float64 ent; float32 occ; int err; out = ckd_calloc(1, sizeof(dtree_t)); n_read = 0; read_line(ln, 4096, &n_read, fp); s = ln; sscanf(s, "%s%n", str, &n_scan); if (strcmp(str, "n_node") == 0) { s += n_scan; sscanf(s, "%u", &n_node); } else { E_FATAL("Format error; expecting n_node\n"); } out->n_node = n_node; out->node = node = ckd_calloc(n_node, sizeof(dtree_node_t)); for (i = 0; i < n_node; i++) node[i].node_id = i; err = FALSE; while (read_line(ln, 4096, &n_read, fp)) { s = ln; sscanf(s, "%u%n", &node_id, &n_scan); s += n_scan; sscanf(s, "%s%n", str, &n_scan); s += n_scan; if (strcmp(str, "-") == 0) { node_id_y = NO_ID; } else { node_id_y = atoi(str); } sscanf(s, "%s%n", str, &n_scan); s += n_scan; if (strcmp(str, "-") == 0) { node_id_n = NO_ID; } else { node_id_n = atoi(str); } sscanf(s, "%le%n", &ent, &n_scan); s += n_scan; sscanf(s, "%e%n", &occ, &n_scan); s += n_scan; if ((node_id_y != NO_ID) && (node_id_y != NO_ID)) { q = (comp_quest_t *)ckd_calloc(1, sizeof(comp_quest_t)); if (s3parse_comp_quest(pset, n_pset, q, s) != S3_SUCCESS) { err = TRUE; } node[node_id].q = q; } else node[node_id].q = NULL; /* ck if internal node */ if ((node_id_y != NO_ID) && (node_id_y != NO_ID)) node[node_id].wt_ent_dec = ent; else node[node_id].wt_ent = ent; node[node_id].occ = occ; if ((node_id_y != NO_ID) && (node_id_y != NO_ID)) { node[node_id].y = &node[node_id_y]; node[node_id].n = &node[node_id_n]; node[node_id_y].p = node[node_id_n].p = &node[node_id]; } else { node[node_id].y = NULL; node[node_id].n = NULL; } } if (err == TRUE) { free_tree(out); out = NULL; } return out; } void free_tree(dtree_t *tr) { uint32 i; dtree_node_t *node; for (i = 0; i < tr->n_node; i++) { node = &tr->node[i]; if (node->mixw_occ) ckd_free_3d((void ***)node->mixw_occ); if (node->means) ckd_free_3d((void ***)node->means); if (node->vars) ckd_free_3d((void ***)node->vars); if (node->id) ckd_free(node->id); /* node->q not freed because if tr is a simple tree, it points to the question in the master list of questions that needs to stick around */ } ckd_free(tr->node); ckd_free(tr); } void mk_disj(dtree_node_t *node, uint32 clust, comp_quest_t *q, quest_t *conj, uint32 c_idx, uint32 *d_idx) { if (IS_LEAF(node)) { if (node->clust == clust) { uint32 i; uint32 d; d = *d_idx; q->prod_len[d] = c_idx; q->conj_q[d] = (quest_t *)ckd_calloc(c_idx, sizeof(quest_t)); for (i = 0; i < c_idx; i++) { memcpy(&q->conj_q[d][i], &conj[i], sizeof(quest_t)); } ++(*d_idx); } else return; } else { quest_t *qu; qu = (quest_t *)node->q; conj[c_idx].ctxt = qu->ctxt; conj[c_idx].neg = qu->neg; conj[c_idx].pset = qu->pset; conj[c_idx].member = qu->member; conj[c_idx].posn = qu->posn; mk_disj(node->y, clust, q, conj, c_idx+1, d_idx); conj[c_idx].neg = !conj[c_idx].neg; mk_disj(node->n, clust, q, conj, c_idx+1, d_idx); return; } } uint32 cnt_class(dtree_node_t *node, uint32 *n_a, uint32 *n_b) { if (IS_LEAF(node)) { if (node->clust) ++(*n_a); else ++(*n_b); } else { cnt_class(node->y, n_a, n_b); cnt_class(node->n, n_a, n_b); } return 0; } uint32 prune_leaves(dtree_node_t *node, pset_t *pset) { dtree_node_t *y, *n; uint32 y_clust, n_clust; if (IS_LEAF(node)) return NO_CLUST; y = node->y; n = node->n; if (!IS_LEAF(y)) { y_clust = prune_leaves(y, pset); } else { y_clust = y->clust; } if (!IS_LEAF(n)) { n_clust = prune_leaves(n, pset); } else { n_clust = n->clust; } if ((y_clust != NO_CLUST) && (y_clust == n_clust)) { node->y = node->n = NULL; node->clust = y_clust; return y_clust; } return NO_CLUST; } uint32 leaf_mixw_occ(dtree_node_t *node, pset_t *pset, float32 ****mixw_occ, uint32 *node_id, uint32 n_state, uint32 n_stream, uint32 n_density, uint32 off) { uint32 i, j, k; if (IS_LEAF(node)) { node_id[off] = node->node_id; for (i = 0; i < n_state; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { mixw_occ[off][i][j][k] = node->mixw_occ[i][j][k]; } } } return ++off; } else { off = leaf_mixw_occ(node->y, pset, mixw_occ, node_id, n_state, n_stream, n_density, off); off = leaf_mixw_occ(node->n, pset, mixw_occ, node_id, n_state, n_stream, n_density, off); return off; } } /* ADDITION FOR CONTINUOUS_TREES */ uint32 leaf_mean_vars(dtree_node_t *node, pset_t *pset, float32 ****means, float32 ****vars, uint32 *node_id, uint32 n_state, uint32 n_stream, uint32 *veclen, uint32 off) { uint32 i, j, k; if (IS_LEAF(node)) { node_id[off] = node->node_id; for (i = 0; i < n_state; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < veclen[j]; k++) { means[off][i][j][k] = node->means[i][j][k]; vars[off][i][j][k] = node->vars[i][j][k]; } } } return ++off; } else { off = leaf_mean_vars(node->y, pset, means, vars, node_id, n_state, n_stream, veclen, off); off = leaf_mean_vars(node->n, pset, means, vars, node_id, n_state, n_stream, veclen, off); return off; } } /* END ADDITION FOR CONTINUOUS_TREES */ uint32 cnt_leaf(dtree_node_t *node) { if ((node->y == NULL) && (node->n == NULL)) { return 1; } else { return cnt_leaf(node->y) + cnt_leaf(node->n); } } uint32 label_leaves(dtree_node_t *node, uint32 *id) { if (IS_LEAF(node)) { node->clust = (*id)++; return 1; } else { return label_leaves(node->y, id) + label_leaves(node->n, id); } } uint32 tied_state(dtree_node_t *node, acmod_id_t b, acmod_id_t l, acmod_id_t r, word_posn_t wp, pset_t *pset) { uint32 dfeat[4]; dfeat[0] = (uint32)l; dfeat[1] = (uint32)b; dfeat[2] = (uint32)r; dfeat[3] = (uint32)wp; if (IS_LEAF(node)) { /* Got to a state cluster. Return the id */ return node->clust; } else { #ifdef HORRIBLY_VERBOSE print_comp_quest(stderr, pset, (comp_quest_t *)node->q); #endif if (eval_comp_quest((comp_quest_t *)node->q, dfeat, 4)) { #ifdef HORRIBLY_VERBOSE fprintf(stderr, " -> y\n"); #endif return tied_state(node->y, b, l, r, wp, pset); } else { #ifdef HORRIBLY_VERBOSE fprintf(stderr, " -> n\n"); #endif return tied_state(node->n, b, l, r, wp, pset); } } } /* * A "twig" is a node where both children are leaves */ uint32 cnt_twig(dtree_node_t *node) { if (IS_LEAF(node)) { return 0; } else if (IS_LEAF(node->y) && IS_LEAF(node->n)) { return 1; } else { if (IS_LEAF(node->y) && !IS_LEAF(node->n)) { return cnt_twig(node->n); } else if (!IS_LEAF(node->y) && IS_LEAF(node->n)) { return cnt_twig(node->y); } else return cnt_twig(node->y) + cnt_twig(node->n); } } void print_node(FILE *fp, dtree_node_t *node, pset_t *pset) { if (!IS_LEAF(node)) { print_quest(fp, pset, (quest_t *)node->q); fprintf(fp, " %.3e %.3e %.3e", /* DDDDBUG chk */ node->wt_ent, node->wt_ent_dec,node->occ); /**/ } else { fprintf(fp, "-"); fprintf(fp, " %.3e %u %u", node->wt_ent, node->n_id, node->clust); if (node->q) { fprintf(fp, " "); print_quest(fp, pset, (quest_t *)node->q); fprintf(fp, " %.3e", node->wt_ent_dec); /* DDDBUG for checks ..*/ fprintf(fp, " %.3e",node->occ); /**/ } } } void print_node_comp(FILE *fp, dtree_node_t *node, pset_t *pset) { if (!IS_LEAF(node)) { print_comp_quest(fp, pset, (comp_quest_t *)node->q); fprintf(fp, " %.3e %.3e", node->wt_ent, node->wt_ent_dec); } else { fprintf(fp, "-"); fprintf(fp, " %.3e [%u]", node->wt_ent, node->n_id); if (node->q) { fprintf(fp, " "); print_comp_quest(fp, pset, (comp_quest_t *)node->q); fprintf(fp, " %.3e", node->wt_ent_dec); } } } void print_tree(FILE *fp, char *label, dtree_node_t *node, pset_t *pset, uint32 lvl) { char i; fprintf(fp, "%s", label); for (i = 0; i < lvl*4; i++) { putc(' ', fp); } fprintf(fp, "( "); print_node(fp, node, pset); if (node->y && node->n) { fprintf(fp, "\n"); print_tree(fp, label, node->y, pset, lvl+1); fprintf(fp, "\n"); print_tree(fp, label, node->n, pset, lvl+1); } fprintf(fp, ")"); } void print_tree_comp(FILE *fp, char *label, dtree_node_t *node, pset_t *pset, uint32 lvl) { char i; fprintf(fp, "%s", label); for (i = 0; i < lvl*4; i++) { putc(' ', fp); } fprintf(fp, "( "); print_node_comp(fp, node, pset); if (node->y && node->n) { fprintf(fp, "\n"); print_tree_comp(fp, label, node->y, pset, lvl+1); fprintf(fp, "\n"); print_tree_comp(fp, label, node->n, pset, lvl+1); } fprintf(fp, ")"); } int mk_node(dtree_node_t *node, uint32 node_id, uint32 *id, uint32 n_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 18 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, float32 mwfloor) { float32 ***mixw_occ, **dist; uint32 mm, m, s, j, k; float64 *dnom, norm, wt_ent, s_wt_ent, occ; float32 mx_wt; uint32 *l_id; /* ADDITION FOR CONTINUOUS_TREES 19 May 98*/ float32 ***lmeans=0,***lvars=0; float32 varfloor=0; uint32 continuous, sumveclen; char* type; type = (char *)cmd_ln_access("-ts2cbfn"); if (strcmp(type,".semi.")!=0 && strcmp(type,".cont.") != 0) E_FATAL("Type %s unsupported; trees can only be built on types .semi. or .cont.\n",type); if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; if (continuous == 1) { varfloor = *(float32 *)cmd_ln_access("-varfloor"); /* Sumveclen is overallocation, but coding is simpler */ for (j=0,sumveclen=0; j < n_stream; j++) sumveclen += veclen[j]; lmeans = (float32 ***) ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); lvars = (float32 ***) ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); } /* END ADDITION FOR CONTINUOUS_TREES */ mixw_occ = (float32 ***)ckd_calloc_3d(n_state, n_stream, n_density, sizeof(float32)); dist = (float32 **)ckd_calloc_2d(n_stream, n_density, sizeof(float32)); dnom = (float64 *)ckd_calloc(n_stream, sizeof(float64)); /* MODIFICATION/ADDITIONS FOR CONTINUOUS_TREES; 19 May 98: merge means and vars too */ /* Merge distributions of all the elements in a cluster for combined distribution */ for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { float32 *lmeanvec=0, *lvarvec=0; if (continuous == 1) { lmeanvec = lmeans[s][j]; lvarvec = lvars[s][j]; } for (mm = 0; mm < n_id; mm++) { m = id[mm]; for (k = 0; k < n_density; k++) { mixw_occ[s][j][k] += mixw[m][s][j][k]; } /* For continuous hmms we have only one gaussian per state */ if (continuous == 1) { for (k = 0; k < veclen[j]; k++) { lmeanvec[k] += mixw[m][s][j][0] * means[m][s][j][k]; lvarvec[k] += mixw[m][s][j][0] * (vars[m][s][j][k] + means[m][s][j][k] * means[m][s][j][k]); } } } if (continuous == 1) { if (mixw_occ[s][j][0] != 0) { for (k = 0; k < veclen[j]; k++) { lmeanvec[k] /= mixw_occ[s][j][0]; lvarvec[k] = lvarvec[k]/mixw_occ[s][j][0] - lmeanvec[k]*lmeanvec[k]; if (lvarvec[k] < varfloor) lvarvec[k] = varfloor; } } else { for (k = 0; k < veclen[j]; k++) if (lmeanvec[k] != 0) E_FATAL("denominator = 0, but numerator = %f at k = %d\n",lmeanvec[k],k); } } } } /* END ADDITIONS FOR CONTINUOUS_TREES */ /* Find out which state is under consideration */ for (j = 0, mx_wt = 0, s = 0; s < n_state; s++) { if (stwt[s] > mx_wt) { mx_wt = stwt[s]; j = s; } } /* occ is the same for each independent feature, so just choose 0 */ for (k = 0, occ = 0; k < n_density; k++) { occ += mixw_occ[j][0][k]; } /* ADDITION/MODIFICATION FOR CONTINUOUS_TREES 19 May 98: USE MEANS AND VARIANCES IN THE CASE OF CONTINUOUS HMMs (RATHER THAN MIXWs) */ for (s = 0, wt_ent = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0, dnom[j] = 0; k < n_density; k++) { dnom[j] += mixw_occ[s][j][k]; } } for (j = 0, s_wt_ent = 0; j < n_stream; j++) { norm = 1.0 / dnom[j]; /* discrete_entropy for discrete case, continuous entropy for continuous HMMs */ if (continuous != 1) { for (k = 0; k < n_density; k++) { dist[j][k] = mixw_occ[s][j][k] * norm; if (dist[j][k] < mwfloor) dist[j][k] = mwfloor; } s_wt_ent += dnom[j] * ent_d(dist[j], n_density); } else { s_wt_ent += dnom[j] * ent_cont(lmeans[s][j], lvars[s][j], veclen[j]); } } wt_ent += stwt[s] * s_wt_ent; } /* END MODIFICATIONS / ADDITION FOR CONTINUOUS_TREES */ node->node_id = node_id; l_id = ckd_calloc(n_id, sizeof(uint32)); for (j = 0; j < n_id; j++) { l_id[j] = id[j]; } node->id = l_id; node->n_id = n_id; node->mixw_occ = mixw_occ; /* ADDITION FOR CONTINUOUS_TREES, 19 May 98 */ if (continuous == 1) { node->means = lmeans; node->vars = lvars; } /* END ADDITION FOR CONTINUOUS_TREES */ node->occ = occ; node->wt_ent = wt_ent; ckd_free_2d((void **)dist); ckd_free((void *)dnom); return S3_SUCCESS; } float64 set_best_quest(dtree_node_t *node, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 20 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, float32 mwfloor) { float32 ***dist; float64 norm; uint32 s, j, k; dist = (float32 ***)ckd_calloc_3d(n_state, n_stream, n_density, sizeof(float32)); /* COMMENT ADDED FOR CONTINUOUS_TREES */ /* Convert occ. counts to probabilities. norm now has total occ. count */ /* END ADDITION FOR CONTINUOUS_TREES */ for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { dist[s][j][k] = node->mixw_occ[s][j][k]; } } for (k = 0, norm = 0; k < n_density; k++) { norm += dist[s][0][k]; } norm = 1.0 / norm; for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { dist[s][j][k] *= norm; if (dist[s][j][k] < mwfloor) { dist[s][j][k] = mwfloor; } } } } /* MODIFICATION FOR CONTINUOUS_TREES; PASS MEAN, VAR, VECLEN AND THE WEIGHTED ENTROPY OF THE NODE ALSO */ node->wt_ent_dec = best_q(mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, dfeat, n_dfeat, all_q, n_all_q, pset, node->id, node->n_id, dist, node->wt_ent, (quest_t **)&node->q); /* END MODIFICATION FOR CONTINUOUS_TREES */ ckd_free_3d((void ***)dist); return node->wt_ent_dec; } void split_node_comp(dtree_t *tr, uint32 node_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, float32 mwfloor) { uint32 *id, n_id; uint32 *id_yes, n_yes; uint32 *id_no, n_no; dtree_node_t *node; uint32 node_id_yes; uint32 node_id_no; uint32 ii, i; node = &tr->node[node_id]; id = node->id; n_id = node->n_id; for (ii = 0, n_yes = 0, n_no = 0; ii < n_id; ii++) { i = id[ii]; if (eval_comp_quest((comp_quest_t *)node->q, dfeat[i], n_dfeat)) { ++n_yes; } else { ++n_no; } } #if 0 fprintf(stderr, "Comp Split: "); print_comp_quest(stderr, pset, (comp_quest_t *)node->q); fprintf(stderr, " %u/%u %.3e\n", n_yes, n_no, node->wt_ent_dec); #endif id_yes = ckd_calloc(n_yes, sizeof(uint32)); id_no = ckd_calloc(n_no, sizeof(uint32)); for (ii = 0, n_yes = 0, n_no = 0; ii < n_id; ii++) { i = id[ii]; if (eval_comp_quest((comp_quest_t *)node->q, dfeat[i], n_dfeat)) { id_yes[n_yes] = i; ++n_yes; } else { id_no[n_no] = i; ++n_no; } } node_id_yes = tr->n_node++; node_id_no = tr->n_node++; node->y = &tr->node[node_id_yes]; node->n = &tr->node[node_id_no]; node->y->p = node; node->n->p = node; /* MODIFICATION FOR CONTINUOUS_TREES; Additions for Continuous Hmm, pass means, vars, veclen */ mk_node(node->y, node_id_yes, id_yes, n_yes, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, mwfloor); node->y->q = (void *)mk_comp_quest(&(node->y->wt_ent_dec), mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, id_yes, n_yes, all_q, n_all_q, pset, n_base_phone, dfeat, n_dfeat, split_min, split_max, split_thr, mwfloor); mk_node(node->n, node_id_no, id_no, n_no, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, mwfloor); node->n->q = (void *)mk_comp_quest(&(node->n->wt_ent_dec), mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, id_no, n_no, all_q, n_all_q, pset, n_base_phone, dfeat, n_dfeat, split_min, split_max, split_thr, mwfloor); /* END MODIFICATIONS FOR CONTINUOUS_TREES */ } void split_node(dtree_t *tr, uint32 node_id, float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, float32 mwfloor) { uint32 *id, n_id; uint32 *id_yes, n_yes; uint32 *id_no, n_no; dtree_node_t *node; uint32 node_id_yes; uint32 node_id_no; uint32 ii, i; node = &tr->node[node_id]; id = node->id; n_id = node->n_id; for (ii = 0, n_yes = 0, n_no = 0; ii < n_id; ii++) { i = id[ii]; if (eval_quest((quest_t *)node->q, dfeat[i], n_dfeat)) { ++n_yes; } else { ++n_no; } } #if 0 fprintf(stderr, "Split: ("); print_quest(stderr, pset, (quest_t *)node->q); fprintf(stderr, ") %u/%u %.3e\n", n_yes, n_no, node->wt_ent_dec); #endif id_yes = ckd_calloc(n_yes, sizeof(uint32)); id_no = ckd_calloc(n_no, sizeof(uint32)); for (ii = 0, n_yes = 0, n_no = 0; ii < n_id; ii++) { i = id[ii]; if (eval_quest((quest_t *)node->q, dfeat[i], n_dfeat)) { id_yes[n_yes] = i; ++n_yes; } else { id_no[n_no] = i; ++n_no; } } node_id_yes = tr->n_node++; node_id_no = tr->n_node++; node->y = &tr->node[node_id_yes]; node->n = &tr->node[node_id_no]; node->y->p = node; node->n->p = node; /* MODIFICATION FOR CONTINUOUS_TREES; Pass means, vars and veclen also */ mk_node(node->y, node_id_yes, id_yes, n_yes, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, mwfloor); set_best_quest(node->y, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, all_q, n_all_q, pset, dfeat, n_dfeat, mwfloor); mk_node(node->n, node_id_no, id_no, n_no, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, mwfloor); set_best_quest(node->n, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, all_q, n_all_q, pset, dfeat, n_dfeat, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ } dtree_node_t * best_leaf_node(dtree_node_t *node) { dtree_node_t *cmp_y, *cmp_n, *ret; ret = NULL; if (IS_LEAF(node)) { ret = node; } else { cmp_y = best_leaf_node(node->y); cmp_n = best_leaf_node(node->n); if ((cmp_y == NULL || cmp_y->q == NULL) && (cmp_n == NULL || cmp_n->q == NULL)) { return NULL; } else if ((cmp_y == NULL) || (cmp_y->q == NULL)) { ret = cmp_n; } else if ((cmp_n == NULL) || (cmp_n->q == NULL)) { ret = cmp_y; } else if (cmp_y->wt_ent_dec > cmp_n->wt_ent_dec) { ret = cmp_y; } else { ret = cmp_n; } } return ret; } dtree_t * mk_tree_comp(float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 18 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, uint32 split_min_comp, uint32 split_max_comp, float32 split_thr_comp, float32 mwfloor) { dtree_t *comp_tree; dtree_node_t *root, *b_n; uint32 i; comp_tree = ckd_calloc(1, sizeof(dtree_t)); comp_tree->node = ckd_calloc(2*split_max_comp+1, sizeof(dtree_node_t)); comp_tree->n_node = 0; comp_tree->node[0].node_id = 0; comp_tree->n_node = 1; root = &comp_tree->node[0]; /* MODIFICATION FOR CONTINUOUS_TREES 18 May 98, pass means and var along with mixw */ mk_node(root, 0, id, n_id, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ /* MODIFICATION FOR CONTINUOUS_TREES 18 May 98, pass means and var along with mixw */ root->q = (void *)mk_comp_quest(&root->wt_ent_dec, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, id, n_id, all_q, n_all_q, pset, n_base_phone, dfeat, n_dfeat, split_min, split_max, split_thr, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ for (i = 0; i < split_max_comp; i++) { b_n = best_leaf_node(root); E_INFO("Comp split %u\n", i); if (b_n == NULL) { E_INFO("stop. leaf nodes are specific\n"); break; } if (b_n->wt_ent_dec <= 0) { E_INFO("stop. b_n->wt_ent_dec (%.3e) <= 0\n", b_n->wt_ent_dec); break; } if ((i > split_min_comp) && (b_n->wt_ent_dec < split_thr_comp * b_n->wt_ent)) { E_INFO("stop. b_n->wt_ent_dec <= split_thr_comp * b_n->wt_ent. %.3e <= %.3e\n", b_n->wt_ent_dec, split_thr_comp * b_n->wt_ent); break; } /* MODIFICATION FOR CONTINUOUS_TREES 18 May 98, pass means and var along with mixw */ split_node_comp(comp_tree, b_n->node_id, mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, all_q, n_all_q, pset, n_base_phone, dfeat, n_dfeat, split_min, split_max, split_thr, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ #if 0 printf("Comp Split %u:\n", i); print_tree_comp(stderr, "*", root, pset, 0); fprintf(stderr, "\n"); #endif } #if 0 E_INFO("Final Comp Tree %u:\n", i); print_tree_comp(stderr, "", root, pset, 0); fprintf(stderr, "\n"); #endif return comp_tree; } dtree_t * mk_tree(float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES, 20 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, float32 mwfloor) { dtree_t *s_tree; uint32 i; dtree_node_t *b_n, *root; s_tree = ckd_calloc(1, sizeof(dtree_t)); s_tree->node = ckd_calloc(2*split_max + 1, sizeof(dtree_node_t)); s_tree->n_node = 0; s_tree->node[0].node_id = 0; s_tree->n_node = 1; root = &s_tree->node[0]; mk_node(root, 0, id, n_id, mixw, /* ADDITION FOR CONTINUOUS_TREES; 20 May 98; passing means, vars, veclen */ means, vars, veclen, /* END ADDITION FOR CONTINUOUS_TREES */ n_model, n_state, n_stream, n_density, stwt, mwfloor); set_best_quest(root, mixw, /* ADDITION FOR CONTINUOUS_TREES; 20 May 98; passing means, vars and veclen */ means, vars, veclen, /* END ADDITION FOR CONTINUOUS_TREES */ n_model, n_state, n_stream, n_density, stwt, all_q, n_all_q, pset, dfeat, n_dfeat, mwfloor); if (root->q == NULL) { /* No question found that is able to split node; can't go any further */ free_tree(s_tree); return NULL; } for (i = 0; i < split_max; i++) { b_n = best_leaf_node(root); if (b_n == NULL) { E_INFO("stop. leaf nodes are specific\n"); break; } /* DDDDDBUG The following criteria will fail if we use only likelihood and no likelihood increase */ if (b_n->wt_ent_dec <= 0) { E_INFO("stop. b_n->wt_ent_dec (%.3e) <= 0\n", b_n->wt_ent_dec); break; } if ((i > split_min) && (b_n->wt_ent_dec < split_thr * b_n->wt_ent)) { E_INFO("stop. b_n->wt_ent_dec (%.3e) < split_thr * b_n->wt_ent (%.3e)\n", b_n->wt_ent_dec, b_n->wt_ent * split_thr); break; } split_node(s_tree, b_n->node_id, mixw, /* ADDITION FOR CONTINUOUS_TREES; 20 May 98; passing means, vars and veclen */ means, vars, veclen, /* END ADDITION FOR CONTINUOUS_TREES */ n_model, n_state, n_stream, n_density, stwt, all_q, n_all_q, pset, dfeat, n_dfeat, mwfloor); } #if 1 E_INFO("Final simple tree\n"); print_tree(stderr, "|", root, pset, 0); fprintf(stderr, "\n"); #endif return s_tree; } comp_quest_t * tree2quest(dtree_t *tr, pset_t *pset, uint32 split_max, uint32 clust, uint32 disj_len) { quest_t *tmp_conj; comp_quest_t *q; uint32 d_idx; tmp_conj = (quest_t *)ckd_calloc(split_max, sizeof(quest_t)); q = (comp_quest_t *)ckd_calloc(1, sizeof(comp_quest_t)); q->sum_len = disj_len; q->prod_len = ckd_calloc(disj_len, sizeof(uint32)); q->conj_q = ckd_calloc(disj_len, sizeof(quest_t *)); d_idx = 0; mk_disj(&tr->node[0], clust, q, tmp_conj, 0, &d_idx); ckd_free(tmp_conj); return q; } void cluster_leaves(dtree_t *tr, /* ADDITION FOR CONTINUOUS_TREES */ uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ float64 *wt_ent_dec, uint32 *out_n_a, uint32 *out_n_b, pset_t *pset, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, float32 mwfloor) { uint32 n_leaf; float32 ****mixw_occ; uint32 *clust, n_a, n_b; uint32 *node_id; dtree_node_t *root; uint32 i; /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means=0; float32 ****vars=0; char* type; uint32 continuous, sumveclen; type = (char *)cmd_ln_access("-ts2cbfn"); if (strcmp(type,".semi.")!=0 && strcmp(type,".cont.") != 0) E_FATAL("Type %s unsupported; trees can only be built on types .semi. or .cont.\n",type); if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; /* END ADDITIONS FOR CONTINUOUS_TREES */ root = &tr->node[0]; /* determine the # of leaf nodes in the simple tree */ n_leaf = cnt_leaf(root); /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { for (i=0,sumveclen=0; i < n_stream; i++) sumveclen += veclen[i]; means = (float32 ****)ckd_calloc_4d(n_leaf, n_state, n_stream, sumveclen, sizeof(float32)); vars = (float32 ****)ckd_calloc_4d(n_leaf, n_state, n_stream, sumveclen, sizeof(float32)); } /* END ADDITIONS FOR CONTINUOUS_TREES */ /* Alloc space for: * - leaf node distribution array * - leaf node cluster id array * - leaf node id array */ mixw_occ = (float32 ****)ckd_calloc_4d(n_leaf, n_state, n_stream, n_density, sizeof(float32)); clust = (uint32 *)ckd_calloc(n_leaf, sizeof(uint32)); node_id = (uint32 *)ckd_calloc(n_leaf, sizeof(uint32)); /* compute the density occupancies of the leaves */ leaf_mixw_occ(root, pset, mixw_occ, node_id, n_state, n_stream, n_density, 0); /* MODIFICATION FOR CONTINUOUS_TREES; ACT ACCORDING TO TYPE */ if (continuous == 1) { /* compute means and variances of the leaves */ leaf_mean_vars(root, pset, means, vars, node_id, n_state, n_stream, veclen, 0); } /* END MODIFICATION FOR CONTINUOUS_TREES */ /* MODIFICATION FOR CONTINUOUS_TREES; Pass means, vars and veclen also */ /* Cluster the leaf nodes into two classes */ *wt_ent_dec = two_class(mixw_occ, means, vars, veclen, n_leaf, n_state, n_stream, n_density, stwt, clust, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ for (i = 0; i < n_leaf; i++) { tr->node[node_id[i]].clust = clust[i]; } /* Simplify the tree based on the two classes * (i.e. if siblings belong to the same class, * delete the node) */ prune_leaves(root, pset); /* Determine how many leaf nodes in class A and B * in the simplified tree */ n_a = n_b = 0; cnt_class(root, &n_a, &n_b); #if 0 fprintf(stderr, "Pruned tree %u/%u:\n", n_a, n_b); print_tree(stderr, "|", root, pset, 1); fprintf(stderr, "\n"); #endif *out_n_a = n_a; *out_n_b = n_b; } comp_quest_t * mk_comp_quest(float64 *wt_ent_dec, float32 ****mixw, /* ADDITIONS FOR CONTINUOUS_TREES, 19 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *id, uint32 n_id, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 n_base_phone, uint32 **dfeat, uint32 n_dfeat, uint32 split_min, uint32 split_max, float32 split_thr, float32 mwfloor) { dtree_t *tr; uint32 n_a, n_b; comp_quest_t *q; /* MODIFICATION FOR CONTINUOUS_TREES, 20 May 98; Pass mean, var and varlen also */ tr = mk_tree(mixw, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, id, n_id, all_q, n_all_q, pset, dfeat, n_dfeat, split_min, split_max, split_thr, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ if (tr == NULL) { *wt_ent_dec = 0; return NULL; } print_tree(stderr, "s>", &tr->node[0], pset, 1); /* COMMENT FOR CONTINUOUS_TREES, 20 May 89 */ /* Note that the tree now contains both mixw and mean and var info so they no longer need to be passed */ /* END COMMENT FOR CONTINUOUS_TREES */ /* MODIFICATION FOR CONTINUOUS_TREES,20 May 98; Pass veclen; tree already has mean and var */ cluster_leaves(tr, veclen, wt_ent_dec, &n_a, &n_b, pset, n_state, n_stream, n_density, stwt, mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ /* Build the disjunction w/ the fewest terms */ if (n_b > n_a) { q = tree2quest(tr, pset, split_max, 1, n_a); } else { q = tree2quest(tr, pset, split_max, 0, n_b); } free_tree(tr); if (simplify_comp_quest(q, n_base_phone)) { } return q; } #include <s3/heap.h> int ins_twigs(dtree_node_t *node, uint32 phnid, uint32 state, float32 *twig_heap, uint32 *twig_hkey, uint32 *phnidlst, uint32 *statelst, uint32 *nidlst, uint32 *free_key) { if (IS_LEAF(node)) { return S3_SUCCESS; } else if (IS_LEAF(node->y) && IS_LEAF(node->n)) { uint32 fk; fk = *free_key; phnidlst[fk] = phnid; statelst[fk] = state; nidlst[fk] = node->node_id; heap32b_ins(twig_heap, twig_hkey, fk, node->wt_ent_dec, fk, heap32b_min_comp); (*free_key)++; return S3_SUCCESS; } else if (IS_LEAF(node->y) && !IS_LEAF(node->n)) { return ins_twigs(node->n, phnid, state, twig_heap, twig_hkey, phnidlst, statelst, nidlst, free_key); } else if (!IS_LEAF(node->y) && IS_LEAF(node->n)) { return ins_twigs(node->y, phnid, state, twig_heap, twig_hkey, phnidlst, statelst, nidlst, free_key); } else { ins_twigs(node->y, phnid, state, twig_heap, twig_hkey, phnidlst, statelst, nidlst, free_key); return ins_twigs(node->n, phnid, state, twig_heap, twig_hkey, phnidlst, statelst, nidlst, free_key); } assert(FALSE); } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2005/07/14 13:41:07 dhdfu * Bug 633610 (<NAME>): If the data set is very small, we may call * prune_leaves() with a leaf node. Don't try to descend into subnodes * in that case! * * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.6 97/07/23 10:49:21 eht * - Got rid of extraneous function * - Added get_node() call to get a tree node with a given id * * Revision 1.5 97/07/17 15:25:41 eht * Fix bug where prune_subtrees() was giving incorrect count. * * Revision 1.4 97/07/17 14:28:37 eht * Added prune_lowcnt() function to allow low occupancy states to be pruned. * * Revision 1.3 97/07/16 12:17:25 eht * Fix bug in tied_state(); order of dfeat is l, b, r not b, l, r * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 97/07/07 10:53:10 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/liblapack_lite/config.h #define EPSILON 1.1102230246252e-16 #define SAFEMINIMUM 2.2250738585072e-308 #define PRECISION 2.2204460492503e-16 #define BASE 2.000000 <file_sep>/SphinxTrain/src/libs/libcommon/ck_seg.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: ck_seg.c * * Description: * Check to see whether a seg file agrees with a given dictionary * and word transcription. * * Author: * <NAME> *********************************************************************/ #include <s3/ck_seg.h> #include <s3/s2_param.h> #include <s3/acmod_set.h> #include <s3/s3.h> int ck_seg(acmod_set_t *acmod_set, acmod_id_t *phone, uint32 n_phone, uint16 *seg, uint32 n_frame, const char *utt_name) { uint32 phone_i; uint32 seg_ci; acmod_id_t trans_ci; uint32 f; uint32 n_state = S2_N_STATE-1; /* # of emitting states/model */ if (n_phone == 0) { if (n_frame == 0) return S3_SUCCESS; else { E_ERROR("utt %s: No phones, but non-empty seg exists\n"); return S3_ERROR; } } if ((seg[0] & 0x8000) == 0) { E_ERROR("utt %s: Expected beginning of phone indicator for at frame %u\n", utt_name, 0); return S3_ERROR; } phone_i = 0; f = 0; seg_ci = (seg[f++] & 0x7FFF) / n_state; trans_ci = acmod_set_base_phone(acmod_set, phone[phone_i++]); /* skip over non-begin frames */ for (; ((f < n_frame) && ((seg[f] & 0x8000) == 0)); f++); while ((seg_ci == trans_ci) && (f < n_frame) && (phone_i < n_phone)) { seg_ci = (seg[f++] & 0x7FFF) / n_state; trans_ci = acmod_set_base_phone(acmod_set, phone[phone_i++]); /* skip over non-begin frames */ for (; ((f < n_frame ) && ((seg[f] & 0x8000) == 0)); f++); } if (seg_ci != trans_ci) { E_ERROR("utt %s: phone %u, %s, in transcript does not match phone %s in seg at frame %u\n", utt_name, phone_i-1, acmod_set_id2name(acmod_set, trans_ci), acmod_set_id2name(acmod_set, seg_ci), f-1); return S3_ERROR; } if ((phone_i < n_phone) && (f == n_frame)) { /* i.e. got to end of seg sequence before end of phone seq */ E_ERROR("utt_name %s: seg phone seq shorter than given phone seq\n", utt_name); return S3_ERROR; } if ((phone_i == n_phone) && (f < n_frame)) { /* i.e. got to end of phone sequence before end of seg seq */ E_ERROR("utt_name %s: seg phone seq longer than given phone seq\n", utt_name); return S3_ERROR; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 96/06/17 14:32:40 eht * Fixed bug in error output for frame 0 * * Revision 1.2 1996/03/04 15:53:58 eht * Made into a common subroutine * * Revision 1.1 1996/02/27 16:41:19 eht * Initial revision * * Revision 1.1 1995/12/14 19:54:26 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/bw/forward.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: forward.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #define ACHK 10 #include <s3/model_inventory.h> #include <s3/s3phseg_io.h> #include <s3/vector.h> #include <s3/ckd_alloc.h> #include <s3/gauden.h> #include <s3/state.h> #include <s3/feat.h> #include <s3/s3.h> #include <s3/profile.h> #include <assert.h> #include <math.h> #include <string.h> #define FORWARD_DEBUG 0 #define INACTIVE 0xffff /********************************************************************* * * Function: * forward * * Description: * This function computes the scaled forward variable, alpha. * * In order to conserve memory for long utterances, only the * active (i.e. non-zero) alpha values are stored. * * Function Inputs: * float64 **active_alpha - * On the successful return of this function, * this array contains the scaled alpha variable for * active states for all input observations. For any * input observation at time t (t >= 0 && t < n_obs), the number * of active states can be found by accessing * n_active_astate[t]. So for some time t, the active * scaled alpha values are active_alpha[t][i] where * i >= 0 and i < n_active_astate[t]. For some valid t and * i, the sentence HMM state id can be found by accessing * active_astate[t][i]. * * uint32 **active_astate - * On the successful return of this function, * this array contains the mapping of active state indexes * into sentence HMM indexes (i.e. indexes into the state_seq[] * array). The active states of the sentence HMM may be * enumerated by accessing active_astate[t][i] over all * t (t >= 0 && t < n_obs) and i * (i >= 0 && i < n_active_astate[t]). * * uint32 *n_active_astate - * On the successful return of this function, * this array contains the number of active states for all * t (t >= 0 && t < n_obs). * * float64 *scale - * On the successful return of this function, * this variable contains the scale factor applied to the * alpha variable for all t (t >= 0 && t < n_obs). * * vector_t **feature - * This variable contains the input observation vectors. * The value feature[t][f] must be valid for * t >= 0 && t < n_obs and f >= 0 && f < n_feat) where * n_feat is the # of assumed statistically independent * feature streams to be modelled. * * uint32 **bp - * On the successful return of this function, * this array contains backtrace pointers for active states * for all input observations except the first timepoint. * As in active_alpha[], the sentence HMM state id can be * found by accessing active_astate[t][i]. NOTE! * This is a "raw" backpointer array and as such, it contains * pointers to non-emitting states. These pointers refer to * the current frame rather than the previous one. Thus, * the state id of the backpointer is either * active_astate[t-1][bp[t][i]] (for normal states) or * active_astate[t][bp[t][i]] (for non-emitting states). * * uint32 n_obs - * This variable contains the number of input observation * vectors seen given the model. * * state_t *state_seq - * This is a list of model state structures which define * the sentence HMM for this observation sequence. * * uint32 n_state - * The total # of states in the sentence HMM for this * utterance. * * model_inventory_t *inv - * This structure contains the inventory of initial acoustic * model parameters. * * float64 beam - * A pruning beam to apply to the evaluation of the alpha * variable. * * s3phseg_t *phseg - * An optional phone segmentation to use to constrain the * forward lattice. * * Global Inputs: * None * * Return Values: * * S3_SUCCESS * The alpha variable was completed successfully for this * observation sequence and model. * * S3_ERROR * Some error was detected that prevented the computation of the * variable. * * Global Outputs: * None * * Errors: * - Initial alpha value < epsilon * - If semi-continuous models, unable to normalize input frame * - Output liklihood underflow * - Alpha variable < epsilon for all active states * *********************************************************************/ int32 forward(float64 **active_alpha, uint32 **active_astate, uint32 *n_active_astate, uint32 **bp, float64 *scale, float64 **dscale, vector_t **feature, uint32 n_obs, state_t *state_seq, uint32 n_state, model_inventory_t *inv, float64 beam, s3phseg_t *phseg) { uint32 i, j, s, t, u; uint32 l_cb; uint32 *active_a; uint32 *active_b; uint32 *active; uint32 *active_l_cb; uint32 n_active; uint32 n_active_l_cb; uint32 n_sum_active; uint32 *next_active; uint32 n_next_active; uint32 aalpha_alloc; uint16 *amap; uint32 *next; float32 *tprob; float64 prior_alpha; float32 ***mixw; gauden_t *g; acmod_set_t *as; float64 x; float64 pthresh = 1e-300; float64 balpha; float64 ***now_den; uint32 ***now_den_idx; uint32 retval = S3_SUCCESS; uint32 n_l_cb; int32 *acbframe; /* Frame in which a codebook was last active */ timing_t *gau_timer = NULL; float64 *outprob; /* Can we prune this frame using phseg? */ int can_prune_phseg; float64 *best_pred = NULL; /* Get the CPU timer associated with mixture Gaussian evaluation */ gau_timer = timing_get("gau"); /* # of distinct codebooks referenced by this utterance */ n_l_cb = inv->n_cb_inverse; /* active codebook frame index */ acbframe = ckd_calloc(n_l_cb, sizeof(*acbframe)); g = inv->gauden; as = inv->mdef->acmod_set; /* density values and indices (for top-N eval) for some time t */ now_den = (float64 ***)ckd_calloc_3d(n_l_cb, gauden_n_feat(g), gauden_n_top(g), sizeof(float64)); now_den_idx = (uint32 ***)ckd_calloc_3d(n_l_cb, gauden_n_feat(g), gauden_n_top(g), sizeof(uint32)); /* Mixing weight array */ mixw = inv->mixw; /* Scratch area for output probabilities at some time t */ outprob = (float64 *)ckd_calloc(n_state, sizeof(float64)); /* Active state lists for time t and t+1 */ active_a = ckd_calloc(n_state, sizeof(uint32)); active_b = ckd_calloc(n_state, sizeof(uint32)); /* Active (local) codebooks for some time t */ active_l_cb = ckd_calloc(n_state, sizeof(uint32)); /* Mapping from sentence HMM state index to active state list index * for currently active time. */ amap = ckd_calloc(n_state, sizeof(uint16)); /* set up the active and next_active lists and associated counts */ active = active_a; next_active = active_b; n_active = 0; n_active_l_cb = 0; n_sum_active = 0; n_next_active = 0; /* Initialize the active state map such that all states are inactive */ for (i = 0; i < n_state; i++) amap[i] = INACTIVE; /* * The following section computes the output liklihood of * the initial state for t == 0 and puts the initial state * in the active state list. */ /* compute alpha for the initial state at t == 0 */ if (gau_timer) timing_start(gau_timer); /* Compute the component Gaussians for state 0 mixture density */ gauden_compute_log(now_den[state_seq[0].l_cb], now_den_idx[state_seq[0].l_cb], feature[0], g, state_seq[0].cb, NULL); active_l_cb[0] = state_seq[0].l_cb; dscale[0] = gauden_scale_densities_fwd(now_den, now_den_idx, active_l_cb, 1, g); /* Compute the mixture density value for state 0 time 0 */ outprob[0] = gauden_mixture(now_den[state_seq[0].l_cb], now_den_idx[state_seq[0].l_cb], mixw[state_seq[0].mixw], g); if (gau_timer) timing_stop(gau_timer); if (outprob[0] <= MIN_IEEE_NORM_POS_FLOAT32) { E_ERROR("Small output prob (== %.2e) seen at frame 0 state 0\n", outprob[0]); retval = S3_ERROR; goto cleanup; } /* * Allocate space for the initial state in the alpha * and active state arrays */ active_alpha[0] = ckd_calloc(1, sizeof(float64)); active_astate[0] = ckd_calloc(1, sizeof(uint32)); if (bp) bp[0] = ckd_calloc(1, sizeof(uint32)); /* Unused, actually */ aalpha_alloc = 1; /* * Allocate the bestscore array for embedded Viterbi */ if (bp) best_pred = ckd_calloc(1, sizeof(float64)); /* Compute scale for t == 0 */ scale[0] = 1.0 / outprob[0]; /* set the scaled alpha variable for the initial state */ active_alpha[0][0] = 1.0; /* put the initial state in the active state array for t == 0 */ active_astate[0][0] = 0; /* Only one initial state (for now) */ n_active_astate[0] = 1; /* insert the initial state in the active list */ active[n_active] = 0; n_active++; /* Compute scaled alpha over all remaining time in the utterance */ for (t = 1; t < n_obs; t++) { /* Find active phone for this timepoint. */ if (phseg) { /* Move the pointer forward if necessary. */ if (t > phseg->ef) phseg = phseg->next; } n_active_l_cb = 0; /* assume next active state set about the same size as current; adjust to actual size as necessary later */ active_alpha[t] = (float64 *)ckd_calloc(n_active, sizeof(float64)); if (bp) { bp[t] = (uint32 *)ckd_calloc(n_active, sizeof(uint32)); /* reallocate the best score array and zero it out */ if (n_active > aalpha_alloc) best_pred = (float64 *)ckd_realloc(best_pred, n_active * sizeof(float64)); memset(best_pred, 0, n_active * sizeof(float64)); } aalpha_alloc = n_active; /* For all active states at the previous frame, activate their successors in this frame and compute codebooks. */ /* (these are pre-computed so they can be scaled to avoid underflows) */ for (s = 0; s < n_active; s++) { i = active[s]; #if FORWARD_DEBUG E_INFO("At time %d, In Gaussian computation, active state %d\n",t, i); #endif /* get list of states adjacent to active state i */ next = state_seq[i].next_state; /* activate them all, computing their codebook densities if necessary */ for (u = 0; u < state_seq[i].n_next; u++) { j = next[u]; #if FORWARD_DEBUG E_INFO("In Gaussian computation, active state %d, next state %d\n", i,j); #endif if (state_seq[j].mixw != TYING_NON_EMITTING) { if (amap[j] == INACTIVE) { l_cb = state_seq[j].l_cb; if (acbframe[l_cb] != t) { /* Component density values not yet computed */ if (gau_timer) timing_start(gau_timer); gauden_compute_log(now_den[l_cb], now_den_idx[l_cb], feature[t], g, state_seq[j].cb, /* Preinitializing topn only really makes a difference for semi-continuous (n_l_cb == 1) models. */ n_l_cb == 1 ? now_den_idx[l_cb] : NULL); active_l_cb[n_active_l_cb++] = l_cb; acbframe[l_cb] = t; if (gau_timer) timing_stop(gau_timer); } /* Put next state j into the active list */ amap[j] = n_next_active; /* Initialize the alpha variable to zero */ active_alpha[t][n_next_active] = 0; /* Map active state list index to sentence HMM index */ next_active[n_next_active] = j; ++n_next_active; if (n_next_active == aalpha_alloc) { /* Need to reallocate the active_alpha array */ aalpha_alloc += ACHK; active_alpha[t] = ckd_realloc(active_alpha[t], sizeof(float64) * aalpha_alloc); /* And the backpointer array */ if (bp) { bp[t] = ckd_realloc(bp[t], sizeof(uint32) * aalpha_alloc); /* And the best score array */ best_pred = (float64 *)ckd_realloc(best_pred, sizeof(float64) * aalpha_alloc); /* Make sure the new stuff is zero */ memset(bp[t] + aalpha_alloc - ACHK, 0, sizeof(uint32) * ACHK); memset(best_pred + aalpha_alloc - ACHK, 0, sizeof(float64) * ACHK); } } } } } } /* Cope w/ numerical issues by dividing densities by max density */ dscale[t] = gauden_scale_densities_fwd(now_den, now_den_idx, active_l_cb, n_active_l_cb, g); /* Now, for all active states in the previous frame, compute alpha for all successors in this frame. */ for (s = 0; s < n_active; s++) { i = active[s]; #if FORWARD_DEBUG E_INFO("At time %d, In real state alpha update, active state %d\n",t, i); #endif /* get list of states adjacent to active state i */ next = state_seq[i].next_state; /* get the associated transition probs */ tprob = state_seq[i].next_tprob; /* the scaled alpha value for i at t-1 */ prior_alpha = active_alpha[t-1][s]; /* For all emitting states j adjacent to i, update their * alpha values. */ for (u = 0; u < state_seq[i].n_next; u++) { j = next[u]; #if FORWARD_DEBUG E_INFO("In real state update, active state %d, next state %d\n", i,j); #endif l_cb = state_seq[j].l_cb; if (state_seq[j].mixw != TYING_NON_EMITTING) { /* Next state j is an emitting state */ outprob[j] = gauden_mixture(now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], g); /* update backpointers bp[t][j] */ x = prior_alpha * tprob[u]; if (bp) { if (x > best_pred[amap[j]]) { #if FORWARD_DEBUG E_INFO("In real state update, backpointer %d => %d updated from %e to (%e * %e = %e)\n", i, j, best_pred[amap[j]], prior_alpha, tprob[u], x); #endif best_pred[amap[j]] = x; bp[t][amap[j]] = s; } } /* update the unscaled alpha[t][j] */ active_alpha[t][amap[j]] += x * outprob[j]; } else { /* already done below in the prior time frame */ } } } #if FORWARD_DEBUG if (bp) { for (s = 0; s < n_next_active; ++s) { j = next_active[s]; E_INFO("After real state update, best path to %d(%d) = %d(%d)\n", j, amap[j], active[bp[t][s]], bp[t][s]); } } #endif /* Now, for all active states in this frame, consume any following non-emitting states (multiplying in their transition probabilities) */ for (s = 0; s < n_next_active; s++) { i = next_active[s]; /* find the successor states */ next = state_seq[i].next_state; tprob = state_seq[i].next_tprob; for (u = 0; u < state_seq[i].n_next; u++) { j = next[u]; /* for any non-emitting ones */ if (state_seq[j].mixw == TYING_NON_EMITTING) { #if FORWARD_DEBUG E_INFO("In non-emitting state update, active state %d, next state %d\n",i,j); #endif x = active_alpha[t][s] * tprob[u]; #if FORWARD_DEBUG E_INFO("In non-emitting state update, active_alpha[t][s]: %f,tprob[u]: %f\n",active_alpha[t][s],tprob[u]); #endif /* activate this state if necessary */ if (amap[j] == INACTIVE) { amap[j] = n_next_active; active_alpha[t][n_next_active] = 0; next_active[n_next_active] = j; ++n_next_active; if (n_next_active == aalpha_alloc) { aalpha_alloc += ACHK; active_alpha[t] = ckd_realloc(active_alpha[t], sizeof(float64) * aalpha_alloc); if (bp) { bp[t] = ckd_realloc(bp[t], sizeof(uint32) * aalpha_alloc); best_pred = (float64 *)ckd_realloc(best_pred, sizeof(float64) * aalpha_alloc); memset(bp[t] + aalpha_alloc - ACHK, 0, sizeof(uint32) * ACHK); memset(best_pred + aalpha_alloc - ACHK, 0, sizeof(float64) * ACHK); } } if (bp) { /* Give its backpointer a default value */ bp[t][amap[j]] = s; best_pred[amap[j]] = x; } } /* update backpointers bp[t][j] */ if (bp && x > best_pred[amap[j]]) { bp[t][amap[j]] = s; best_pred[amap[j]] = x; } /* update its alpha value */ active_alpha[t][amap[j]] += x; } } } #if FORWARD_DEBUG for (s = 0; s < n_next_active; ++s) { j = next_active[s]; if (bp && state_seq[j].mixw == TYING_NON_EMITTING) { E_INFO("After non-emitting state update, best path to %d(%d) = %d(%d)\n", j, amap[j], next_active[bp[t][s]], bp[t][s]); /* Assumptions about topology that might not be valid * but are useful for debugging. */ assert(next_active[bp[t][s]] <= j); assert(j - next_active[bp[t][s]] <= 2); } } #endif /* find best alpha value in current frame for pruning and scaling purposes */ balpha = 0; /* also take the argmax to find the best backtrace */ for (s = 0; s < n_next_active; s++) { if (balpha < active_alpha[t][s]) { balpha = active_alpha[t][s]; } } /* cope with some pathological case */ if (balpha == 0.0 && n_next_active > 0) { E_ERROR("All %u active states,", n_next_active); for (s = 0; s < n_next_active; s++) { if (state_seq[next_active[s]].mixw != TYING_NON_EMITTING) fprintf(stderr, " %u", state_seq[next_active[s]].mixw); else fprintf(stderr, " N(%u,%u)", state_seq[next_active[s]].tmat, state_seq[next_active[s]].m_state); } fprintf(stderr, ", zero at time %u\n", t); fflush(stderr); retval = S3_ERROR; break; } /* and some related pathological cases */ if (balpha < 1e-300) { E_ERROR("Best alpha < 1e-300\n"); retval = S3_ERROR; break; } if (n_next_active == 0) { E_ERROR("No active states at time %u\n", t); retval = S3_ERROR; break; } /* compute the scale factor */ scale[t] = 1.0 / balpha; /* compute the pruning threshold based on the beam */ if (log10(balpha) + log10(beam) > -300) { pthresh = balpha * beam; } else { /* avoiding underflow... */ pthresh = 1e-300; } /* DEBUG XXXXX */ /* pthresh = 0.0; */ /* END DEBUG */ /* Determine if phone segmentation-based pruning would leave * us with an empty active list (that would be bad!) */ can_prune_phseg = 0; if (phseg) { for (s = 0; s < n_next_active; ++s) if (acmod_set_base_phone(as, state_seq[next_active[s]].phn) == acmod_set_base_phone(as, phseg->phone)) break; can_prune_phseg = !(s == n_next_active); #if FORWARD_DEBUG if (!can_prune_phseg) { E_INFO("Will not apply phone-based pruning at timepoint %d " "(%d != %d) (%s != %s)\n", t, state_seq[next_active[s]].phn, phseg->phone, acmod_set_id2name(inv->mdef->acmod_set, state_seq[next_active[s]].phn), acmod_set_id2name(inv->mdef->acmod_set, phseg->phone) ); } #endif } /* Prune active states for the next frame and rescale their alphas. */ active_astate[t] = ckd_calloc(n_next_active, sizeof(uint32)); for (s = 0, n_active = 0; s < n_next_active; s++) { /* "Snap" the backpointers for non-emitting states, so that they don't point to bogus indices (we will use amap to recover them). */ if (bp && state_seq[next_active[s]].mixw == TYING_NON_EMITTING) { #if FORWARD_DEBUG E_INFO("Snapping backpointer for %d, %d => %d\n", next_active[s], bp[t][s], next_active[bp[t][s]]); #endif bp[t][s] = next_active[bp[t][s]]; } /* If we have a phone segmentation, use it instead of the beam. */ if (phseg && can_prune_phseg) { if (acmod_set_base_phone(as, state_seq[next_active[s]].phn) == acmod_set_base_phone(as, phseg->phone)) { active_alpha[t][n_active] = active_alpha[t][s] * scale[t]; active[n_active] = active_astate[t][n_active] = next_active[s]; if (bp) bp[t][n_active] = bp[t][s]; amap[next_active[s]] = n_active; n_active++; } else { amap[next_active[s]] = INACTIVE; } } else { if (active_alpha[t][s] > pthresh) { active_alpha[t][n_active] = active_alpha[t][s] * scale[t]; active[n_active] = active_astate[t][n_active] = next_active[s]; if (bp) bp[t][n_active] = bp[t][s]; amap[next_active[s]] = n_active; n_active++; } else { amap[next_active[s]] = INACTIVE; } } } /* Now recover the backpointers for non-emitting states. */ for (s = 0; s < n_active; ++s) { if (bp && state_seq[active[s]].mixw == TYING_NON_EMITTING) { #if FORWARD_DEBUG E_INFO("Snapping backpointer for %d, %d => %d(%d)\n", active[s], bp[t][s], amap[bp[t][s]], active[amap[bp[t][s]]]); #endif bp[t][s] = amap[bp[t][s]]; } } /* And finally deactive all states. */ for (s = 0; s < n_active; ++s) { amap[active[s]] = INACTIVE; } n_active_astate[t] = n_active; n_next_active = 0; n_sum_active += n_active; } printf(" %u ", n_sum_active / n_obs); cleanup: ckd_free(active_a); ckd_free(active_b); ckd_free(amap); ckd_free(active_l_cb); ckd_free(acbframe); ckd_free(outprob); ckd_free(best_pred); ckd_free_3d((void ***)now_den); ckd_free_3d((void ***)now_den_idx); return retval; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.5 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.13 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.12 1996/07/29 16:15:18 eht * - gauden_compute call arguments made (hopefully) more rational * - change alpha and scale rep to float64 from float32 * - smaller den and den_idx structures * * Revision 1.11 1996/03/26 13:51:08 eht * - Deal w/ beam float32 -> float64 bug * - Deal w/ case when # densities referenced in an utterance is much fewer than the * total # of densities to train. * - Deal w/ adflag[] not set bug * * Revision 1.10 1996/03/04 15:58:56 eht * added more cpu time counters * * Revision 1.9 1996/02/02 17:39:53 eht * - Uncomment pruning. * - Allow a list of active Gaussians to be evaluated rather than all. * * Revision 1.8 1995/12/14 19:49:26 eht * - Add code to only normalize gaussian densities when 1 tied mixture is used. O/W don't do. * - Add code to warn about zero output probability for emitting states. * * Revision 1.7 1995/10/12 18:30:22 eht * Made state.h a "local" header file * * Revision 1.6 1995/10/10 12:43:50 eht * Changed to use <s3/prim_type.h> * * Revision 1.5 1995/10/09 14:55:33 eht * Change interface to new ckd_alloc routines * * Revision 1.4 1995/09/14 14:19:36 eht * reformatted slightly * * Revision 1.3 1995/08/09 20:17:41 eht * hard code the beam for now * * Revision 1.2 1995/07/07 11:57:54 eht * Changed formatting and content of verbose output and * make scale sum of alphas for a given time rather than * max alpha to make SPHINX-II comparison easier. * * Revision 1.1 1995/06/02 20:41:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/pgm/misc/rc.c /* * rc.c -- Right context transformations * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 08-Apr-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * Input lines of the form: * 354 .PERIOD => (TD) p ih r iy ax dd () * 9 IN => (S) [[ AX => IX ]] n (F) * 6 HELP PAY => (AX) hh eh l [[ => PD ]] p ey (F) * Output last phone transformations only. */ #include <libutil/libutil.h> #define MAX_WORDS 4092 main (int32 argc, char *argv[]) { char line[16384], **wptr; int32 i, n, k; if (argc > 1) { E_INFO("Usage: %s < <result-of-pronerralign>\n", argv[0]); exit(0); } wptr = (char **) ckd_calloc (MAX_WORDS, sizeof(char *)); while (fgets (line, sizeof(line), stdin) != NULL) { if ((n = str2words (line, wptr, MAX_WORDS)) < 0) E_FATAL("str2words(%s) failed; increase %d(?)\n", line, MAX_WORDS); /* Read first (count) field */ if (n == 0) continue; if (sscanf (wptr[0], "%d", &k) != 1) E_FATAL("First field not a count: %s\n", wptr[0]); /* Find => separator after word list */ for (i = 0; (i < n) && (strcmp (wptr[i], "=>") != 0); i++); i++; /* Hopefully at (lc) */ /* Must have at least: (lc) p1 p2 (rc) */ if (n-i <= 3) continue; assert (i > 2); assert (wptr[i][0] == '('); /* (lc) */ assert (wptr[n-1][0] == '('); /* (rc) */ if ((strcmp (wptr[n-2], "]]") != 0) && (strcmp (wptr[n-3], "]]") != 0)) { /* No error */ printf ("%6d %-5s %-5s %-5s %s\n", k, wptr[n-3], wptr[n-2], wptr[n-1], wptr[1]); } else if (strcmp (wptr[n-2], "]]") == 0) { /* * Last phone got transformed. Look for: * (lc) p [[ => ee ]] (rc), * (lc) p [[ ee => ]] (rc), or * (lc) p [[ pp => ee ]] (rc) */ if (n-i <= 6) continue; /* Not enough fields */ if ((strcmp (wptr[n-4], "=>") == 0) && (strcmp (wptr[n-5], "[[") == 0) && (strcmp (wptr[n-6], "]]") != 0)) { printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-6], wptr[n-3], wptr[n-1], "--", wptr[1]); } else if ((strcmp (wptr[n-3], "=>") == 0) && (strcmp (wptr[n-5], "[[") == 0) && (strcmp (wptr[n-6], "]]") != 0)) { printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-6], "--", wptr[n-1], wptr[n-4], wptr[1]); } else if ((strcmp (wptr[n-4], "=>") == 0) && (strcmp (wptr[n-6], "[[") == 0) && (strcmp (wptr[n-7], "]]") != 0) && (n-i > 7)) { printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-7], wptr[n-3], wptr[n-1], wptr[n-5], wptr[1]); } } } } <file_sep>/archive_s3/s3.0/pgm/misc/erreg.c /* * erreg.c -- Extract error regions * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-May-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #define MAX_WORDS 4092 main (int32 argc, char *argv[]) { char line[16384], **wptr; int32 i, n, lineno; if (argc > 1) { E_INFO("Usage: %s < <filtered-dp-output>\n", argv[0]); exit(0); } wptr = (char **) ckd_calloc (MAX_WORDS, sizeof(char *)); lineno = 0; while (fgets (line, sizeof(line), stdin) != NULL) { lineno++; if ((n = str2words (line, wptr, MAX_WORDS)) < 0) E_FATAL("str2words(%s) failed; increase %d(?)\n", line, MAX_WORDS); for (i = 0; (i < n) && (strcmp (wptr[i], "<<") != 0); i++); if (i >= n) E_FATAL("Bad line (#%d)\n", lineno); n = i-1; for (i = 0; i < n; i++) { if (strcmp (wptr[i], "[[") == 0) { printf ("%s\t", wptr[n]); if (i > 0) printf ("%s", wptr[i-1]); else printf ("<s>"); for (; (i < n) && (strcmp (wptr[i], "]]") != 0); i++) printf (" %s", wptr[i]); assert (i < n); printf (" ]]"); if (i < n-1) printf (" %s", wptr[i+1]); else printf (" </s>"); printf ("\n"); } } } } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/actions/RemoveNodeFromSceneAction.java package edu.cmu.sphinx.tools.confdesigner.actions; import edu.cmu.sphinx.tools.confdesigner.ConfigScene; import org.netbeans.api.visual.widget.Widget; import javax.swing.*; import java.awt.event.ActionEvent; /** * DOCUMENT ME! * * @author <NAME> */ public class RemoveNodeFromSceneAction extends AbstractAction { private Widget myWidget; public RemoveNodeFromSceneAction(Widget widget) { myWidget = widget; putValue(NAME, "Remove Node"); } public void actionPerformed(ActionEvent e) { ConfigScene scene = (ConfigScene) myWidget.getScene(); // scene.setSelectedObjects(new HashSet<Object>(Arrays.asList(myWidget))); scene.removeSelectedObjects(); // scene.removeNode((ConfNode) scene.findObject(myWidget)); } } <file_sep>/pocketsphinx/src/libpocketsphinx/fsg2_search.h /* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file fsg2_search.h * @brief New FSG search * @author <NAME> <<EMAIL>> */ #ifndef __FSG2_SEARCH_H__ #define __FSG2_SEARCH_H__ /* SphinxBase headers. */ #include <fsg_model.h> /* Local headers. */ #include "pocketsphinx_internal.h" #include "hmm.h" #include "glextree.h" #include "tokentree.h" /** * Implementation of updated FSG search */ typedef struct fsg2_search_s { ps_search_t base; hmm_context_t *hmmctx; /**< HMM context. */ fsg_model_t *fsg; /**< Currently active FSG */ jsgf_t *jsgf; /**< Active JSGF grammar file. */ hash_table_t *vocab; /**< Set of active vocabulary words. */ glextree_t *lextree; /**< Tree lexicon for search */ tokentree_t *toktree; /**< Token tree (lattice/history) */ int16 frame; /**< Current frame. */ uint8 final; /**< Decoding is finished for this utterance. */ uint8 bestpath; /**< Whether to run bestpath search and confidence annotation at end. */ } fsg2_search_t; /** * Create, initialize and return a search module. */ ps_search_t *fsg2_search_init(cmd_ln_t *config, acmod_t *acmod, dict_t *dict, dict2pid_t *d2p); /** * Deallocate search structure. */ void fsg2_search_free(ps_search_t *search); /** * Update FSG search module for new or updated FSGs. */ int fsg2_search_reinit(ps_search_t *fsgs, dict_t *dict, dict2pid_t *d2p); /** * Prepare the FSG search structure for beginning decoding of the next * utterance. */ int fsg2_search_start(ps_search_t *search); /** * Step one frame forward through the Viterbi search. */ int fsg2_search_step(ps_search_t *search, int frame_idx); /** * Windup and clean the FSG search structure after utterance. */ int fsg2_search_finish(ps_search_t *search); /** * Get hypothesis string from the FSG search. */ char const *fsg2_search_hyp(ps_search_t *search, int32 *out_score); #endif <file_sep>/archive_s3/s3.0/pgm/sensprd/Makefile # # Makefile # # HISTORY # # 07-Jan-97 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../Makefile.defines VPATH = .:.. OBJS = ../../libmain/$(MACHINE)/misc.o \ ../../libmain/$(MACHINE)/gauden.o \ ../../libmain/$(MACHINE)/senone.o \ ../../libmain/$(MACHINE)/am.o \ ../../libmain/$(MACHINE)/mdef.o \ ../../libmain/$(MACHINE)/dict.o \ ../../libmain/$(MACHINE)/cmn.o \ ../../libmain/$(MACHINE)/agc.o \ ../../libmain/$(MACHINE)/logs3.o \ ../../libmain/$(MACHINE)/vector.o sensprd : sensprd.o $(CC) $(S3DEBUG) $(CFLAGS) -o $@ $> $(OBJS) -lfeat -lio -lutil -lm <file_sep>/SphinxTrain/src/libs/libs2io/int32_io.c /* ==================================================================== * Copyright (c) 1996-2000 Car<NAME>ellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * 32-bit int I/O routines * */ #include <s3/int32_io.h> #include <stdio.h> int32 read_int32 (FILE *stream) { int c; int32 word; c = getc (stream); if (c == EOF) return -1; word = c; c = getc (stream); if (c == EOF) return -1; word = word << 8 | c; c = getc (stream); if (c == EOF) return -1; word = word << 8 | c; c = getc (stream); if (c == EOF) return -1; return word << 8 | c; } int write_int32 (FILE *stream, int32 word) { if (putc (word >> 24, stream) == EOF) return -1; if (putc (word >> 16, stream) == EOF) return -1; if (putc (word >> 8, stream) == EOF) return -1; if (putc (word, stream) == EOF) return -1; return 0; } int read_int32_array (FILE *stream, int32 *base, int length) { #ifdef sun return fread ((char *) base, length * 4, 1, stream) != 1 ? -1 : 0; #else int counter; int32 *ptr; counter = length; ptr = base; while (--counter >= 0) { int c; int32 word; c = getc (stream); if (c == EOF) return -1; word = c; c = getc (stream); if (c == EOF) return -1; word = word << 8 | c; c = getc (stream); if (c == EOF) return -1; word = word << 8 | c; c = getc (stream); if (c == EOF) return -1; *ptr++ = word << 8 | c; } return 0; #endif } int write_int32_array (FILE *stream, int32 *base, int length) { #ifdef sun return fwrite((char *) base, length * 4, 1, stream) != 1 ? -1 : 0; #else int counter; int32 *ptr; counter = length; ptr = base; while (--counter >= 0) { int32 word; word = *ptr++; if (putc (word >> 24, stream) == EOF) return -1; if (putc (word >> 16, stream) == EOF) return -1; if (putc (word >> 8, stream) == EOF) return -1; if (putc (word, stream) == EOF) return -1; } return 0; #endif } <file_sep>/SphinxTrain/src/programs/mk_s3gau/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * Command line parser for mk_s3gau * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <stdlib.h> #include "s3/cmd_ln.h" #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ Conversion from sphinx 2 codebook to sphinx3 means and variances"; const char examplestr[]= "Example: \n\ mk_s3gau -meanfn s3mean -varfn s3var -cbdir s2dir "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A SPHINX-III mean density parameter file name" }, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A SPHINX-III variance density parameter file name" }, { "-cbdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".", "A directory containing SPHINX-II 1PD codebooks" }, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "Minimum variance value" }, { "-cepcb", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "cep.256", "Basename of the cepstrum codebook" }, { "-dcepcb", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "d2cep.256", "Basename of the difference cepstrum codebook" }, { "-powcb", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "p3cep.256", "Basename of the power codebook" }, { "-2dcepcb", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "xcep.256", "Basename of the 2nd order difference cepstrum codebook" }, { "-meanext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "vec", "Mean codebook extension" }, { "-varext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "var", "Variance codebook extension" }, { "-fixpowvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "false", "Fix the power variance to the SPHINX-II standards" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/11/29 01:43:50 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.3 2004/11/29 01:11:35 egouvea * Fixed license terms in some new files. * * Revision 1.2 2004/08/10 08:31:55 arthchan2003 * s2 to s3 conversion tools * * Revision 1.1 2004/06/17 19:39:50 arthchan2003 * add back all command line information into the code * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/02/20 00:28:35 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/03/07 08:56:51 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/r_agc_noise.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: r_agc_noise.c * * Description: * * Author: * faa *********************************************************************/ /* static char rcsid[] = "@(#)$Id$";*/ #include <s3/r_agc_noise.h> #include <s3/prim_type.h> /* defines int32, etc. */ #include <s3/s3.h> /* defines TRUE and FALSE */ #include <stdio.h> #include <string.h> static float agc_thresh = 0.2; void real_agc_noise (float *cep, /* The cepstrum data */ uint32 fcnt, /* Number of cepstrum frame availiable */ uint32 cf_cnt) /* Number of coeff's per frame */ { float *p; /* Data pointer */ float min_energy; /* Minimum log-energy */ float noise_level; /* Average noise_level */ uint32 i; /* frame index */ uint32 noise_frames;/* Number of noise frames */ /* Determine minimum log-energy in utterance */ min_energy = *cep; for (i = 0, p = cep; i < fcnt; i++, p += cf_cnt) { if (*p < min_energy) min_energy = *p; } /* Average all frames between min_energy and min_energy + agc_thresh */ noise_frames = 0; noise_level = 0.0; min_energy += agc_thresh; for (i = 0, p = cep; i < fcnt; i++, p += cf_cnt) { if (*p < min_energy) { noise_level += *p; noise_frames++; } } noise_level /= noise_frames; printf ("%6.3f = AGC NOISE\n", noise_level); /* Subtract noise_level from all log_energy values */ for (i = 0, p = cep; i < fcnt; i++, p += cf_cnt) *p -= noise_level; } void agc_set_threshold (float threshold) { agc_thresh = threshold; } uint32 find_peak (uint32 *buf, uint32 cnt) { uint32 i, max, maxi, maxcnt; uint32 hyst; /* hysteriesus band */ maxcnt = 0; for (i = 0; i < cnt; i++) if (maxcnt < buf[i]) maxcnt = buf[i]; /* * Peak must exceed 20% of the max count. */ hyst = 0.20 * maxcnt; max = 0; maxi = 0; for (i = 0; i < cnt; i++) { if (buf[i] > max) { max = buf[i]; maxi = i; } if (buf[i] < (max - hyst)) break; } return (maxi); } float histo_noise_level (float *cep, /* The cepstrum data */ int32 fcnt, /* Number of cepstrum frame availiable */ int32 cf_cnt) /* Number of coeff's per frame */ { float *p; /* Data pointer */ float min_energy; /* Minimum log-energy */ float max_energy; /* Maximum log-energy */ float dr; /* Dynamic range */ float noise_level; /* Average noise_level */ int32 i; /* frame index */ uint32 histo[101]; uint32 idx; /* Determine minimum/maximum log-energy in utterance * Plus a histogram of the energy */ for (idx = 0; idx < 101; idx++) histo[idx] = 0; min_energy = *cep; max_energy = *cep; for (i = 0, p = cep; i < fcnt; i++, p += cf_cnt) { if (*p < min_energy) min_energy = *p; else if (*p > max_energy) max_energy = *p; } dr = max_energy - min_energy; if (dr == 0.0) return (min_energy); for (i = 0, p = cep; i < fcnt; i++, p += cf_cnt) { idx = ((*p - min_energy) / dr) * 100.0; histo[idx]++; } idx = 5 + find_peak (histo, 101); if (idx > 100) idx = 100; noise_level = idx; noise_level = (noise_level * dr / 100.0) + min_energy; printf ("%.3f = Histo noise (%d)\n", noise_level, idx); return (noise_level); } int delete_background (float32 *cep, /* The cepstrum data */ int32 fcnt, /* Number of cepstrum frame availiable */ int32 cf_cnt, /* Number of coeff's per frame */ float32 thresh) /* background threshold */ { uint32 i, j; float32 *p; static char delete[8000]; if (cf_cnt > 8000) { printf ("%s(%d): number frames %d, exceeds max (8000)\n", __FILE__, __LINE__, fcnt); return fcnt; } /* * Mark the frames that are below the threshold */ for (p = cep, i = 0; i < fcnt; i++, p += cf_cnt) { delete[i] = (*p < thresh) ? 1 : 0; } /* * Select the frames to delete */ for (i = 2; i < fcnt-2; i++) { if (delete[i-2] && delete[i-1] && delete[i] && delete[i+1] && delete[i+2]) { delete[i] = 2; } } /* * Delete the frames */ for (j = i = 0; i < fcnt; i++) { if (delete[i] != 2) { memcpy (&cep[j*cf_cnt], &cep[i*cf_cnt], cf_cnt * sizeof(float)); j++; } } printf ("Deleted %d background frames out of %d frames\n", fcnt-j, fcnt); return (j); } static float observed_min = 100.0; static float observed_max = -100.0; static float observed_dr; static float min_energy = -20.0; static float max_energy = 20.0; static float dynamic_range = 40.0; static uint32 histo[1001]; static float noise_level = -100.0; /* Average noise_level */ static int32 noise_frm_cnt = 0; static int32 noise_frames_discarded = 0; #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) #define MAX(a,b) ( (a) > (b) ? (a) : (b) ) int histo_add_c0 (float32 c0) { uint32 idx; if (c0 < noise_level) noise_frm_cnt++; else noise_frm_cnt = 0; observed_min = MIN(c0,observed_min); observed_max = MAX(c0,observed_max); c0 = MAX (min_energy, c0); c0 = MIN (max_energy, c0); c0 -= min_energy; idx = (c0 / dynamic_range) * 1000.0; histo[idx]++; if (noise_frm_cnt < 5) return TRUE; else { noise_frames_discarded++; return FALSE; } } void compute_noise_level () { uint32 idx; uint32 i; idx = find_peak (histo, 1001); /* * Discard half of the counts */ for (i = 0; i < 1001; i++) histo[i] = histo[i] >> 1; /* * compute the observed dynamic range and contract the observed min and * max by 10% each. Reset noise_frm_cnt to 0. */ observed_dr = observed_max - observed_min; observed_min += observed_dr / 10.0; observed_max -= observed_dr / 10.0; noise_frm_cnt = 0; /* * Compute the noise level as 5% of the dr above the first peak. */ noise_level = idx; noise_level = (noise_level * dynamic_range / 1000.0) + min_energy; noise_level += (observed_dr * 0.05); printf ("%.3f = Histo noise (%d)\n", noise_level, idx); printf ("%d Frames discarded\n", noise_frames_discarded); noise_frames_discarded = 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 1995/10/17 13:05:04 eht * Cleaned up code a bit so that it is more ANSI compliant * * Revision 1.3 1995/10/10 12:36:12 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/09/07 19:55:41 eht * include <s3/s3.h> to pick up define for TRUE and FALSE * since some machines don't choose to define these in * their standard include files * * Revision 1.1 1995/06/02 20:57:22 eht * Initial revision * * */ <file_sep>/scons/SConstruct import os import platform import sys Help(""" Type: 'scons shipDictator' to create and package all dictator related files. Type: 'scons runDictator' to run the dictator and build any necessary things. Type 'scons dictator' to build dictator.jar and its dependencies. Type 'scons common' to build common.jar and its dependencies. Type 'scons sphinx4' to build sphinx4.jar and its dependencies. This produces a different sphinx4.jar than the one produced by build.xml. This sphinx4.jar only includes source from sphinx4/src/sphinx4. It does not include any of the research code, jsapi, demos, etc. As a result it is 25% smaller. Also, it's important to note that everything under src/sphinx4 builds. There are no excludes. Only with your help can we keep it this way. Type 'scons audioCollector' to build audioCollector.jar and its dependencies. This fails because I don't know where AudioRecorder lives. Other sphinx projects are not yet supported. Ship output will be placed in the scons_ship directory adjacent to trunk. Build output will be placed in the scons_build directory adjacent to trunk. Build outputs will be place in scons_build, which will be created two directories above the scons directory Ship outputs will be placed in scons_ship, which will also be created two directories aboce the scons directory These scripts have been tested on OS X 10.4.7, Ubuntu Linux 6.06, Windows XP, and Red Hat Linux 9.0 """) try: javapath = os.path.normpath(os.environ['JAVA_HOME']) + os.sep + 'bin' + os.pathsep javapath += os.environ['PATH'] env = Environment(ENV = {'PATH' : javapath }) except: print "Please define the environmental variable JAVA_HOME" sys.exit(1) SConscript('sphinx4.py', exports = 'javapath') Import('sphinx4') Alias('sphinx4', sphinx4) SConscript('common.py', exports=['javapath', 'sphinx4']) Import('common') Alias('common', common) SConscript('dictator.py', exports=['javapath', 'common', 'sphinx4']) Import('dictator') Alias('dictator', dictator) SConscript('audioCollector.py', exports=['javapath', 'common']) Import('audioCollector') Import('shipAudioCollector') Alias('audioCollector', audioCollector) Alias('shipAudioCollector', shipAudioCollector) SConscript('corpusBrowser.py', exports='javapath') Import('corpusBrowser') Alias('corpusBrowser', corpusBrowser) SConscript('shipDictator.py', exports=['javapath', 'dictator']) Import('shipDictator') Import('runDictator') Alias('shipDictator', shipDictator) Alias('runDictator', runDictator)<file_sep>/archive_s3/s3.3/src/tests/an4/Makefile # ==================================================================== # Copyright (c) 2000 <NAME> University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Sphinx III # # ==================================================================== TOP=../../.. DIRNAME=src/tests/an4 BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = cmd_ln_args.h fe_dump.h feat_dump.h new_fe_sp_dump.h live_dump.h metrics.h # LIVEDECSRCS = parse_args_file.c fe_dump.c feat_dump.c new_fe_sp_dump.c live_dump.c metrics.c MAINSRCS = dump_frontend.c batch_metrics.c # OTHERSRCS = main.c LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile $(SRCS) $(H) LIBNAME= tests LOCAL_INCLUDES = -I$(TOP)/src -I$(TOP)/src/libs3decoder -I$(TOP)/src/libs3audio ALL = $(BINDIR)/batchmetrics include $(TOP)/config/common_make_rules ifeq ($(MODE),quick) MODEAFFIX = _quick else MODEAFFIX = endif $(BINDIR)/batchmetrics: ../batch_metrics.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ batch_metrics.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) -Wl,-R$(LIBDIR) an4_words_unigram: rm -f gmake-an4_words_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_words_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_words.unigram.lm.DMP" >> ARGS.an4_words_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_words$(MODEAFFIX).batch / ./ARGS.an4_words_unigram$(MODEAFFIX) > gmake-an4_words_unigram$(MODEAFFIX).results an4_spelling_unigram: rm -f gmake-an4_spelling_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_spelling_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_spelling.unigram.lm.DMP" >> ARGS.an4_spelling_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_spelling$(MODEAFFIX).batch / ./ARGS.an4_spelling_unigram$(MODEAFFIX) > gmake-an4_spelling_unigram$(MODEAFFIX).results an4_full_unigram: rm -f gmake-an4_full_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_unigram ARGS.an4_full_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_full.unigram.lm.DMP" >> ARGS.an4_full_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_full$(MODEAFFIX).batch / ./ARGS.an4_full_unigram$(MODEAFFIX) > gmake-an4_full_unigram$(MODEAFFIX).results an4_words_flat_unigram: rm -f gmake-an4_words_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_words_flat_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_words.flat_unigram.lm.DMP" >> ARGS.an4_words_flat_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_words$(MODEAFFIX).batch / ./ARGS.an4_words_flat_unigram$(MODEAFFIX) > gmake-an4_words_flat_unigram$(MODEAFFIX).results an4_spelling_flat_unigram: rm -f gmake-an4_spelling_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_spelling_flat_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_spelling.flat_unigram.lm.DMP" >> ARGS.an4_spelling_flat_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_spelling$(MODEAFFIX).batch / ./ARGS.an4_spelling_flat_unigram$(MODEAFFIX) > gmake-an4_spelling_flat_unigram$(MODEAFFIX).results an4_full_flat_unigram: rm -f gmake-an4_full_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.an4_flat_unigram ARGS.an4_full_flat_unigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_full.flat_unigram.lm.DMP" >> ARGS.an4_full_flat_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_full$(MODEAFFIX).batch / ./ARGS.an4_full_flat_unigram$(MODEAFFIX) > gmake-an4_full_flat_unigram$(MODEAFFIX).results an4_words_bigram: rm -f gmake-an4_words_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_words_bigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_words.bigram.lm.DMP" >> ARGS.an4_words_bigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_words$(MODEAFFIX).batch / ./ARGS.an4_words_bigram$(MODEAFFIX) > gmake-an4_words_bigram$(MODEAFFIX).results an4_spelling_bigram: rm -f gmake-an4_spelling_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_spelling_bigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_spelling.bigram.lm.DMP" >> ARGS.an4_spelling_bigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_spelling$(MODEAFFIX).batch / ./ARGS.an4_spelling_bigram$(MODEAFFIX) > gmake-an4_spelling_bigram$(MODEAFFIX).results an4_full_bigram: rm -f gmake-an4_full_bigram$(MODEAFFIX).results /bin/cp ARGS.an4_bigram ARGS.an4_full_bigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_full.bigram.lm.DMP" >> ARGS.an4_full_bigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_full$(MODEAFFIX).batch / ./ARGS.an4_full_bigram$(MODEAFFIX) > gmake-an4_full_bigram$(MODEAFFIX).results an4_words_trigram: rm -f gmake-an4_words_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_words_trigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_words.trigram.lm.DMP" >> ARGS.an4_words_trigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_words$(MODEAFFIX).batch / ./ARGS.an4_words_trigram$(MODEAFFIX) > gmake-an4_words_trigram$(MODEAFFIX).results an4_spelling_trigram: rm -f gmake-an4_spelling_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_spelling_trigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_spelling.trigram.lm.DMP" >> ARGS.an4_spelling_trigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_spelling$(MODEAFFIX).batch / ./ARGS.an4_spelling_trigram$(MODEAFFIX) > gmake-an4_spelling_trigram$(MODEAFFIX).results an4_full_trigram: rm -f gmake-an4_full_trigram$(MODEAFFIX).results /bin/cp ARGS.an4_trigram ARGS.an4_full_trigram$(MODEAFFIX) echo "-lm /lab/speech/sphinx4/data/an4/lists/an4_full.trigram.lm.DMP" >> ARGS.an4_full_trigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./an4_full$(MODEAFFIX).batch / ./ARGS.an4_full_trigram$(MODEAFFIX) > gmake-an4_full_trigram$(MODEAFFIX).results <file_sep>/scons/corpusBrowser.py import platform import os import fnmatch Import('javapath') Import('common') srcDir = os.path.normpath('../tools/corpusBrowser/src/java') classDir = os.path.normpath('../../scons_build/classes/corpusBrowser') libpath = '..' + os.sep + 'tools' + os.sep + 'common' + os.sep + 'lib' + os.sep classpath = libpath + 'batch.jar' + os.pathsep classpath += libpath + 'dom4j-1.6.1.jar' + os.pathsep classpath += libpath + 'forms_rt_license.jar' + os.pathsep classpath += libpath + 'forms_rt.jar' + os.pathsep classpath += libpath + 'javolution.jar' + os.pathsep classpath += libpath + 'sphinx4.jar' + os.pathsep classpath += str(common[0]) env = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS = '-source 1.5 -classpath "' + classpath + '"', JARCHDIR = classDir) classes = env.Java(target = classDir, source = srcDir ) Depends(classes, common) jarFile = os.path.normpath('../../scons_build/jars/corpusBrowser.jar') corpusBrowser = env.Jar(target = jarFile, source = classDir) Export('corpusBrowser') <file_sep>/SphinxTrain/src/programs/mk_s3mixw/mk_s3mixw.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: mk_s3mixw.c * * Description: * Make a SPHINX-3 mixing weight file from SPHINX-2 SDM models. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/model_def_io.h> #include <s3/acmod_set.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s2_read_seno.h> #include <s3/s3mixw_io.h> #include <s3/s2_param.h> #include <s3/s3.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #define NO_STATE 0xffffffff static char *ord_suff(uint32 i) { return (i == 1 ? "st" : (i == 2 ? "nd" : (i == 3 ? "rd" : "th"))); } int main(int argc, char *argv[]) { model_def_t *mdef; model_def_entry_t *defn; uint32 n_defn; uint32 *cluster_offset; uint32 max_int; uint32 *state_of; uint32 max_state; uint32 sstate; int32 i; uint32 j; uint32 n_base_phone; acmod_id_t base; acmod_id_t p; float32 ***out; uint32 **smap; char comment[4192]; time_t t; parse_cmd_ln(argc, argv); printf("%s(%d): Reading model definition file %s\n", __FILE__, __LINE__, (const char *)cmd_ln_access("-moddeffn")); if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { exit(1); } defn = mdef->defn; n_defn = mdef->n_defn; printf("%s(%d): %d models defined\n", __FILE__, __LINE__, n_defn); smap = ckd_calloc(n_defn, sizeof(uint32 *)); n_base_phone = acmod_set_n_ci(mdef->acmod_set); cluster_offset = ckd_calloc(n_base_phone+1, sizeof(uint32)); max_int = 0; --max_int; /* underflow offset values to max value */ for (i = 0; i < n_base_phone; i++) { cluster_offset[i] = max_int; } for (i = 0, max_state = 0; i < n_defn; i++) { for (j = 0; j < defn[i].n_state; j++) { sstate = defn[i].state[j]; if ((sstate != TYING_NON_EMITTING) && (defn[i].state[j] > max_state)) max_state = defn[i].state[j]; } } /* record the total # of senones */ cluster_offset[n_base_phone] = max_state+1; state_of = ckd_calloc(max_state+1, sizeof(uint32)); for (i = 0; i <= max_state; i++) state_of[i] = NO_STATE; for (i = 0; i < n_defn; i++) { p = defn[i].p; base = acmod_set_base_phone(mdef->acmod_set, defn[i].p); smap[i] = defn[i].state; for (j = 0; j < defn[i].n_state; j++) { sstate = defn[i].state[j]; if (sstate != TYING_NON_EMITTING) { if (state_of[sstate] == NO_STATE) state_of[sstate] = j; else if (state_of[sstate] != j) { printf("%s %d appears as %d%s and %d%s model states\n", acmod_set_id2name(mdef->acmod_set, acmod_set_base_phone(mdef->acmod_set, defn[i].p)), sstate, state_of[sstate], ord_suff(state_of[sstate]), j, ord_suff(j)); } if ((p != base) && (cluster_offset[base] > sstate)) { cluster_offset[base] = sstate; } } } } /* any untouched CLUSTER_OFFSET's implies a base phone without any CD states. So offset is same as next one */ for (i = (n_base_phone - 1); i >= 0 ; i--) { if (cluster_offset[i] == max_int) cluster_offset[i] = cluster_offset[i+1]; } fflush(stdout); for (i = 0; i < n_base_phone; i++) { if (cluster_offset[i] != max_int) { fprintf(stderr, "%s(%d): %s offset %d\n", __FILE__, __LINE__, acmod_set_id2name(mdef->acmod_set, i), cluster_offset[i]); } else { fprintf(stderr, "%s(%d): %s <no CD states>\n", __FILE__, __LINE__, acmod_set_id2name(mdef->acmod_set, i)); } } fflush(stderr); printf("%s(%d): Reading senone weights in %s with floor %e\n", __FILE__, __LINE__, (const char *)cmd_ln_access("-hmmdir"), *(float32 *)cmd_ln_access("-floor")); out = s2_read_seno_3(mdef->acmod_set, cluster_offset, cmd_ln_access("-hmmdir"), (*(int32 *)cmd_ln_access("-ci2cd") ? NULL : smap), *(float32 *)cmd_ln_access("-floor"), state_of); t = time(NULL); sprintf(comment, "Generated on %s\n\tmoddeffn: %s\n\tfloor: %e\n\thmmdir: %s\n\n\n\n\n\n\n\n\n", ctime(&t), (const char *)cmd_ln_access("-moddeffn"), *(float32 *)cmd_ln_access("-floor"), (const char *)cmd_ln_access("-hmmdir")); fflush(stdout); fprintf(stderr, "%s(%d): writing %s\n", __FILE__, __LINE__, (const char *)cmd_ln_access("-mixwfn")); fflush(stderr); if (s3mixw_write(cmd_ln_access("-mixwfn"), out, cluster_offset[n_base_phone], /* total # states */ S2_N_FEATURE, S2_N_CODEWORD) != S3_SUCCESS) { fflush(stdout); fprintf(stderr, "%s(%d): couldn't write mixture weight file\n", __FILE__, __LINE__); perror(cmd_ln_access("-mixwfn")); fflush(stderr); } ckd_free(state_of); ckd_free(cluster_offset); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 19:17:25 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:23:47 eht * Library reorganization changes * * Revision 1.1 97/03/07 08:56:17 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/norm/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * Parse the command line for norm(1) * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[]= "Description: \n\ compute the HMM's parameter generated by bw."; const char examplestr[]= "Example: \n\ norm \n\ -accumdir dir1 [dir2 dir3 ...] \n\ -mixwfn mixw \n\ -tmatfn tmat \n\ -meanfn mean \n\ -varfn variances"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-accumdir", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "One or more paths containing reestimation sums from bw" }, { "-oaccumdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Path to contain the overall reestimation sums" }, { "-tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Transition prob. matrix file to produce (if any)"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Mixing weight file to produce (if any)"}, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Gaussian density mean file to produce (if any)"}, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Gaussian density variance file to produce (if any)"}, { "-regmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "MLLR regression matrices file to produce (if any)"}, { "-dcountfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Gaussian density count file to produce"}, { "-inmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Use mixing weights from this file if never observed"}, { "-inmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Use mean from this file if never observed"}, { "-invarfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Use var from this file if never observed"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Variances are full covariance matrices"}, { "-tiedvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Tie all covariances together"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ exit(1); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/11/29 01:43:51 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.6 2004/08/08 04:53:40 arthchan2003 * norm's help and example strings * * Revision 1.5 2004/07/21 19:17:25 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/03/01 00:47:44 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:22:39 eht * Allow an inmixfn for those mixing weights that were unseen in the accumulators * * Revision 1.7 97/03/07 08:53:11 eht * - added -inmeanfn and -invarfn arguments for unseen means and vars * * */ <file_sep>/SphinxTrain/src/libs/libio/fp_cache.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: fp_cache.c * * Description: * Maintains a cache of (FILE *) according to a caller-supplied * id. * * Possible uses might include creating dump files for the * observations associated with some state i where each state is kept * in a separate file. * * Uses LRU cache replacement. Caller must supply open() and close() * functions for cache replacement. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/fp_cache.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #define UNSET 0xffffffff static int use_lkptbl = FALSE; static uint32 fpc_max_sz = 2048; static uint32 fpc_sz = UNSET; static FILE **fpc = NULL; static uint32 *fpc_cnt = NULL; static uint32 *fpc_id = NULL; static uint32 fpc_hit = 0; static uint32 fpc_miss = 0; static void (*fpc_close)(FILE *fp) = NULL; static FILE * (*fpc_open)(uint32 id) = NULL; int fpc_setmaxsz(uint32 sz) { fpc_max_sz = sz; return S3_SUCCESS; } int fpc_setclose(void (*fn)(FILE *fp)) { fpc_close = fn; return S3_SUCCESS; } int fpc_setopen(FILE * (*fn)(uint32 id)) { fpc_open = fn; return S3_SUCCESS; } int fpc_n_id(uint32 n) { uint32 i; /* Deallocate previous cache+stats (if any) */ if (fpc) { ckd_free((void *)fpc); fpc = NULL; } if (fpc_cnt) { ckd_free((void *)fpc_cnt); fpc_cnt = NULL; } if (fpc_id) { ckd_free((void *)fpc_id); fpc_id = NULL; } if (n <= fpc_max_sz) { use_lkptbl = TRUE; fpc_sz = n; } else { fpc_sz = fpc_max_sz; use_lkptbl = FALSE; fpc_cnt = (uint32 *)ckd_calloc(fpc_sz, sizeof(uint32)); fpc_id = (uint32 *)ckd_calloc(fpc_sz, sizeof(uint32)); for (i = 0; i < fpc_sz; i++) fpc_id[i] = UNSET; } fpc = (FILE **)ckd_calloc(fpc_sz, sizeof(FILE *)); return S3_SUCCESS; } FILE * fpc_get(uint32 id) { FILE *ret; uint32 max_cnt, lru_i=0; uint32 i; assert(fpc_open); assert(fpc_close); if (use_lkptbl) { if (fpc[id] == NULL) { fpc[id] = fpc_open(id); } ret = fpc[id]; } else { /* Can't use cache as a lookup table. */ /* Check for cache hit; if no hit, do LRU replacement */ for (i = 0, ret = NULL; i < fpc_sz; i++) { if (fpc_id[i] == id) { /* The dmp fp is in cache; use it */ ret = fpc[i]; fpc_cnt[i] = 0; ++fpc_hit; /* cache hit count */ } } if (ret == NULL) { /* The dmp fp is not in cache*/ ++fpc_miss; /* Find the LRU fp for replacement */ for (i = 0, max_cnt = 0; i < fpc_sz; i++) { if (fpc_cnt[i] >= max_cnt) { max_cnt = fpc_cnt[i]; lru_i = i; } } /* Replace LRU fp with fp to id dmp file */ if (fpc[lru_i]) fpc_close(fpc[lru_i]); ret = fpc_open(id); fpc[lru_i] = ret; fpc_id[lru_i] = id; fpc_cnt[lru_i] = 0; } /* update the LRU counters */ for (i = 0; i < fpc_sz; i++) ++fpc_cnt[i]; ++fpc_hit; } return ret; } int fpc_flush() { uint32 i; for (i = 0; i < fpc_sz; i++) { fpc_close(fpc[i]); if (fpc_id) fpc_id[i] = UNSET; if (fpc_cnt) fpc_cnt[i] = 0; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/param_cnt/main.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include "parse_cmd_ln.h" #include "param_cnt.h" #include "ts_cnt.h" #include <s3/s3ts2cb_io.h> #include <s3/ts2cb.h> #include <s3/corpus.h> #include <s3/cmd_ln.h> #include <s3/lexicon.h> #include <s3/acmod_set.h> #include <s3/model_def_io.h> #include <s3/ckd_alloc.h> #include <s3/feat.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <string.h> static int initialize(lexicon_t **out_lex, model_def_t **out_mdef, int argc, char *argv[]) { lexicon_t *lex; model_def_t *mdef; const char *fdictfn; const char *dictfn; const char *ts2cbfn; uint32 n_ts; /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); corpus_set_seg_dir(cmd_ln_access("-segdir")); corpus_set_seg_ext(cmd_ln_access("-segext")); if (cmd_ln_access("-lsnfn")) corpus_set_lsn_filename(cmd_ln_access("-lsnfn")); else { corpus_set_sent_dir(cmd_ln_access("-sentdir")); corpus_set_sent_ext(cmd_ln_access("-sentext")); } corpus_set_ctl_filename(cmd_ln_access("-ctlfn")); if (cmd_ln_access("-part") && cmd_ln_access("-npart")) { corpus_set_partition(*(uint32 *)cmd_ln_access("-part"), *(uint32 *)cmd_ln_access("-npart")); } else if (cmd_ln_access("-nskip") && cmd_ln_access("-runlen")) { corpus_set_interval(*(uint32 *)cmd_ln_access("-nskip"), *(uint32 *)cmd_ln_access("-runlen")); } if (corpus_init() != S3_SUCCESS) { return S3_ERROR; } E_INFO("Reading: %s\n", cmd_ln_access("-moddeffn")); /* Read in the model definitions. Defines the set of CI phones and context dependent phones. Defines the transition matrix tying and state level tying. */ if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { return S3_ERROR; } ts2cbfn = cmd_ln_access("-ts2cbfn"); if (ts2cbfn) { E_INFO("Reading %s\n", cmd_ln_access("-ts2cbfn")); if (strcmp(ts2cbfn, SEMI_LABEL) == 0) { /* see <s3/ts2cb.h> */ mdef->cb = semi_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; mdef->n_cb = 1; } else if (strcmp(ts2cbfn, CONT_LABEL) == 0) { /* see <s3/ts2cb.h> */ mdef->cb = cont_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; mdef->n_cb = mdef->n_tied_state; } else if (strcmp(PTM_LABEL, ts2cbfn) == 0) { mdef->cb = ptm_ts2cb(mdef); n_ts = mdef->n_tied_state; mdef->n_cb = mdef->acmod_set->n_ci; } else if (s3ts2cb_read(cmd_ln_access("-ts2cbfn"), &mdef->cb, &n_ts, &mdef->n_cb) != S3_SUCCESS) { return S3_ERROR; } if (n_ts != mdef->n_tied_state) { E_WARN("# of tied states in ts2cb mapping, %u != # tied states in model def, %u\n", n_ts, mdef->n_tied_state); } } *out_mdef = mdef; dictfn = cmd_ln_access("-dictfn"); if (dictfn == NULL) { E_FATAL("You must specify a content dictionary using -dictfn\n"); } E_INFO("Reading: %s\n", dictfn); lex = lexicon_read(NULL, /* no lexicon to start */ dictfn, mdef->acmod_set); if (lex == NULL) return S3_ERROR; fdictfn = cmd_ln_access("-fdictfn"); if (fdictfn) { E_INFO("Reading: %s\n", fdictfn); (void)lexicon_read(lex, /* add filler words content lexicon */ fdictfn, mdef->acmod_set); } *out_lex = lex; return S3_SUCCESS; } int main(int argc, char *argv[]) { lexicon_t *lex; model_def_t *mdef; const char *type; const char *outfn; FILE *out_fp = stdout; if (initialize(&lex, &mdef, argc, argv) != S3_SUCCESS) { E_ERROR("errors initializing.\n"); return 1; } type = (const char *)cmd_ln_access("-paramtype"); outfn = (const char *)cmd_ln_access("-outputfn"); if (outfn != NULL) { out_fp = fopen(outfn, "w"); if (out_fp == NULL) { E_ERROR_SYSTEM("Couldn't open %s for writing\n", outfn); } } if (param_cnt(out_fp, lex, mdef, type) != S3_SUCCESS) { return 1; } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2006/02/03 18:53:07 eht * Added -outputfn to the command line. * * When -outputfn <somefile> is present on the command line, the * parameter counts are written to the specified file <somefile>. * When no -outputfn argument is present on the command line, the * parameter counts are written to standard output as before this * change. * * Revision 1.4 2004/07/21 19:17:26 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.2 97/03/07 08:41:14 eht * - Deal w/ new i/o routines * * Revision 1.1 1996/03/25 15:21:20 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/acmod_set_ds.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************** * * File: acmod_set_ds.h * * Description: * This header file defines the data structures used by the * acmod_set (acoustic model set) module and its clients. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef ACMOD_SET_DS_H #define ACMOD_SET_DS_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/prim_type.h> typedef unsigned char ci_acmod_id_t; #define NO_CI_ACMOD (0xff) #define MAX_CI_ACMOD (0xfe) typedef uint32 acmod_id_t; #define NO_ACMOD (0xffffffff) /* The ID representing no acoustic * model. */ #define MAX_ACMOD (0xfffffffe) /* The max ID possible */ typedef enum { WORD_POSN_BEGIN = 0, /* beginning phone of word */ WORD_POSN_END = 1, /* ending phone of word */ WORD_POSN_SINGLE = 2, /* single phone word (i.e. begin & end) */ WORD_POSN_INTERNAL = 3, /* internal phone of word */ WORD_POSN_UNDEFINED = 4 /* undefined value, used for initial conditions, etc */ } word_posn_t; #define N_WORD_POSN 4 /* total # of word position indicators (excluding undefined) */ /* the following map must be consistent w/ the types above. Unpredictable * behaviour w/ result if not. */ #define WORD_POSN_CHAR_MAP "besiu" /* b == begin, e == end, s == single-phone i == word-internal, u == undefined */ /* acoustic model record (describes triphones, diphones, etc.) */ typedef struct acmod_s { ci_acmod_id_t base; /* The base phone associated w/ this phone */ ci_acmod_id_t left_context; /* The left context associated w/ this phone, * if there is no specified left context, this * is set to NO_ACMOD */ ci_acmod_id_t right_context; /* The right context associated w/ this phone, * This can be any CI phone id or NO_ACMOD. * NO_ACMOD indicates to specified right context */ word_posn_t posn; /* Word position indicator (see above) */ /* The name is generatable from the information above */ const char **attrib; /* A NULL terminated list of C strings which * represent various attributes of the acoustic model. * For instance, "ci", "non_speech", "triphone" * model. */ } acmod_t; /* ci_acmod record (represents base phones and filler words) */ typedef struct ci_acmod_s { const char *name; /* A C string representation for the acoustic model */ const char **attrib; /* A NULL terminated list of C strings which * represent various attributes of the acoustic model. * For instance, "ci", "non_speech", "triphone" * model. */ ci_acmod_id_t id; /* The ID of this acoustic model */ } ci_acmod_t; #include <s3/itree.h> typedef struct acmod_set_s { ci_acmod_t *ci; /* base phone and filler model list. * The base phone set are used to compose * triphones, diphones, etc. They are also * acoustic models themselves that represent * phones trained with no regard to their * left and right contexts. * * filler models are used to represent non-speech * signals such as silence (actually stationary * background noise), coughs, door slams, etc. */ uint32 n_ci; /* # of CI acoustic models */ uint32 max_n_ci; acmod_t *multi; /* The remaining acoustic models. Includes only * triphones at the moment. */ uint32 n_multi; uint32 max_n_multi; uint32 next_id; /* The ID which would be assigned to the next * new acoustic model */ itree_t **multi_idx; /* A quick index for mapping a multiphone to * an ID. */ char **attrib; /* A NULL terminated list of C strings which * represent all possible attributes of the phones in * a phone set. * For instance, "base", "non_speech", "triphone" */ uint32 *n_with; /* The number of phones having each attribute. */ } acmod_set_t; #ifdef __cplusplus } #endif #endif /* ACMOD_SET_DS_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:08 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.2 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.1 1995/09/08 19:13:52 eht * Initial revision * * Revision 1.1 95/08/15 13:44:14 13:44:14 eht (<NAME>) * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/del_sil_seg.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: del_sil_seg.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include <s3/feat.h> #include <s3/err.h> #include <string.h> #include <assert.h> uint32 del_sil_seg(vector_t *mfcc, uint32 n_frame_in, uint32 *del_b, uint32 *del_e, uint32 n_del) { uint32 n_del_frame; /* # of deleted frames */ uint32 n_frame; /* # of frames output */ uint32 i; /* source frame index */ uint32 j; /* destination frame indext */ uint32 d; /* next deleted segment */ uint32 ceplen; /* # of components of the cepstrum vector */ if (n_del == 0) return n_frame_in; for (i = 0, n_del_frame = 0; i < n_del; i++) { n_del_frame += del_e[i] - del_b[i] + 1; } ceplen = feat_mfcc_len(); n_frame = n_frame_in - n_del_frame; for (i = 0, j = 0, d = 0; i < n_frame_in; i++, j++) { if ((d < n_del) && (i == del_b[d])) { i = del_e[d] + 1; ++d; } if ((i != j) && (i < n_frame_in)) memcpy(mfcc[j], mfcc[i], sizeof(float32) * ceplen); } if (d != n_del) { E_FATAL("d(%u) != n_del(%u)\n", d, n_del); } return n_frame; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcommon/Makefile # ==================================================================== # Copyright (c) 2000 Carnegie Mellon University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 3. The names "Sphinx" and "Carnegie Mellon" must not be used to # endorse or promote products derived from this software without # prior written permission. To obtain permission, contact # <EMAIL>. # # 54 Redistributions of any form whatsoever must retain the following # acknowledgment: # "This product includes software developed by Carnegie # Mellon University (http://www.speech.cs.cmu.edu/)." # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # C libraries libcommon # # ==================================================================== TOP=../../.. DIRNAME=src/libs/libcommon BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) SRCS = \ acmod_set.c \ best_q.c \ btree.c \ ck_seg.c \ ckd_alloc.c \ cmd_ln.c \ cmu6_lts_rules.c \ cvt2triphone.c \ dtree.c \ enum_subset.c \ err.c \ get_cpu_time.c \ get_host_name.c \ get_time.c \ hash.c \ heap.c \ itree.c \ lexicon.c \ lts.c \ matrix.c \ mk_phone_list.c \ mk_phone_seq.c \ mk_sseq.c \ mk_trans_seq.c \ mk_ts2ci.c \ mk_wordlist.c \ n_words.c \ prefetch.c \ prefix_upto.c \ profile.c \ quest.c \ remap.c \ state_seq.c \ timer.c \ ts2cb.c \ two_class.c \ vector.c \ was_added.c H = cmu6_lts_rules.h FILES = Makefile $(SRCS) $(H) LIBNAME= common ALL = .build_lib include $(TOP)/config/common_make_rules <file_sep>/SphinxTrain/src/programs/printp/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ Display numerical values of resources generated by Sphinx \n\ Current we supoort the following formats \n\ \n\ -tmatfn : transition matrix \n\ \n\ -mixwfn : mixture weight file \n\ \n\ -gaufn : mean or variance \n\ \n\ -fullgaufn : full covariance \n\ \n\ -gaucntn : sufficient statistics for mean and diagonal covariance \n\ \n\ -lambdafn : interpolation weight \n\ \n\ Currently, some parameters can be specified as intervals such as mixture weight. \n\ \n\ You can also specified -sigfig the number of significant digits by you would like to see. \n\ \n\ and normalize the parameters by -norm"; const char examplestr[] = "Example: \n\ \n\ Print the mean of a Gaussian: \n\ printp -gaufn mean \n\ \n\ Print the variance of a Gaussian: \n\ printp -gaufn var \n\ \n\ Print the sufficient statistic: \n\ printp -gaucntfn gaucnt: \n\ \n\ Print the mixture weights: \n\ printp -mixw mixw\n\ \n\ Print the LDA transformation matrix(es): \n\ printp -ldafn lda\n\ \n\ Print the interpolation weight: \n\ printp -lambdafn lambda "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The transition matrix parameter file name"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The mixture weight parameter file name"}, { "-mixws", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Start id of mixing weight subinterval"}, { "-mixwe", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "End id of mixing weight subinterval"}, { "-gaufn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A Gaussian parameter file name (either for means or vars)"}, { "-fullgaufn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A full Gaussian covariance file name"}, { "-gaucntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A Gaussian parameter weighted vector file"}, { "-regmatcntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "MLLR regression matrix count file"}, { "-ldafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "An LDA transformation file name"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The model definition file"}, { "-lambdafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The interpolation weight file"}, { "-lambdamin", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0", "Print int. wt. >= this"}, { "-lambdamax", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1", "Print int. wt. <= this"}, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The tied state to codebook mapping file"}, { "-norm", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Print normalized parameters"}, { "-sigfig", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "4", "Number of significant digits in 'e' notation" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ exit(1); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/11/29 01:43:51 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.6 2004/08/07 21:29:48 arthchan2003 * Update command line info and make tex happy * * Revision 1.5 2004/08/07 21:24:24 arthchan2003 * add help and example to printp * * Revision 1.4 2004/07/21 19:17:26 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.5 97/03/07 08:51:42 eht * - added -sigfig argument * - added -regmatcntfn argument * - added interpolation weight arguments * * Revision 1.4 1996/01/30 17:06:44 eht * Include "-gaucntfn" argument and coalesce "-meanfn" and "-varfn" * into "-gaufn" * * Revision 1.3 1995/09/07 20:03:56 eht * Include defn of TRUE/FALSE for machines like HP's running HPUX * * Revision 1.2 1995/08/09 20:37:06 eht * *** empty log message *** * * Revision 1.1 1995/06/02 20:36:50 eht * Initial revision * * */ <file_sep>/CLP/src/Lattice.cc //------------------------------------------------------------------------------------------- // Lattice.cc //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- // 05/31/2001 fixed bug in DFS_visit #include <cstdlib> #include <iomanip> #include <cstdio> #include <cassert> #include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; #include "Link.h" #include "Lattice.h" #include "LineSplitter.h" #include "common_lattice.h" #include "common.h" /* ---------------------------------------------------------------------------------- */ /* --------------------------- LINK STUFF ----------- ------------------------------- */ /* ---------------------------------------------------------------------------------- */ // ----------------------------- private --------------------------- void Link::fill_link_fields(const string& idf, const string& entry) { if (idf == "J") id = (LinkId)atol((const char*)entry.c_str()); else if (idf == "S") start_node_id = (NodeId)atol((const char*)entry.c_str()); else if (idf == "E") end_node_id = (NodeId)atol((const char*)entry.c_str()); else if (idf == "a") ac_score = atof((const char*)entry.c_str()); else if (idf == "n" || idf == "l") lm_score = atof((const char*)entry.c_str()); else if (idf == "r") pr_score = atof((const char*)entry.c_str()); else if (idf == "p") /* Do nothing, this is a pre-existing posterior... */; else if (idf == "score") // this is for the FSM style input score = atof((const char*)entry.c_str()); else{ cerr << "ERROR: Link::fill_link_fields(): unknown identifier:" << endl; cerr << idf << " " << entry << endl; exit(1); } return; } // ---------------------------------------- public ----------------------------------------- Link::Link(): lat_ptr((Lattice *)0), id(0), start_node_id(0), end_node_id(0), word_idx(-1), ac_score(LZERO), lm_score(LZERO), pr_score(LZERO), score(LZERO), pscore(LZERO), pruned(false){} Link::Link(const string& line, const Lattice* from_lattice, const Prons& P): lat_ptr(from_lattice), id(0), start_node_id(0), end_node_id(0), word_idx(-1), ac_score(LZERO), lm_score(LZERO), pr_score(LZERO), score(LZERO), pscore(LZERO), pruned(false) { static LineSplitter fields; fields.Split(line); unsigned int no_fields = fields.NoWords(); if (from_lattice->Type() == "SLF"){ assert(no_fields < MAX_NO_FIELDS_LINK); assert(no_fields >= MIN_NO_FIELDS_LINK); assert(line.find_first_of("J") == 0); for(int i=0; i < no_fields; i++){ int pos = fields[i].find("="); assert(pos != string::npos); const string& idf = fields[i].substr(0,pos); // MOD 6/30/2000 - const added const string& entry = fields[i].substr(pos+1,string::npos); // MOD 6/30/2000 - const added if (idf == "W" || idf == "WORD"){ word_idx = ((Prons&) P).get_idx(entry); // MOD 6/30/2000 - cast added was: word_idx = P.get_idx(entry); } else fill_link_fields(idf, entry); } } else if (from_lattice->Type() == "FSM"){ assert(no_fields < MAX_NO_FIELDS_FSM); assert(no_fields >= MIN_NO_FIELDS_FSM); assert(line.find_first_of(" ") != 0); if (no_fields >= 3){ // node 1 node2 word [score] fill_link_fields("S",fields[0]); fill_link_fields("E",fields[1]); word_idx = ((Prons&) P).get_idx(fields[2]); // MOD 6/30/2000 - cast added if (no_fields == 4) fill_link_fields("score", fields[no_fields-1]); else fill_link_fields("score", "0"); } else if (no_fields != 0){ // end_node [score] fill_link_fields("S",fields[0]); word_idx = ((Prons&) P).get_idx(EPS); // MOD 6/30/2000 - cast added if (no_fields == 2) fill_link_fields("score",fields[1]); else fill_link_fields("score","0"); fill_link_fields("E",fields[0]); // i make it the same as the start node and take care of it later on } } else cerr << "ERROR:Link():lattice type " << from_lattice->Type() << " not supported\n"; } // /////////////////////////////////////////////////////////////////////////// const Node& Link::start_node() const{ return lat_ptr->node(start_node_id);} const Node& Link::end_node() const{ return lat_ptr->node(end_node_id);} float Link::start_time() const { return lat_ptr->node(start_node_id).Time();} float Link::end_time() const { return lat_ptr->node(end_node_id).Time();} // ///////////////////////////////////////////////////////////////////////////// void Link::print_it(const Prons& P) { cout.setf(ios::left, ios::adjustfield); const string& w = P.get_word(word_idx); // MOD 6/30/2000 - const added string wdash = " -- "; cout << " S=" << setw(5) << start_node_id << " E=" << setw(5) << end_node_id; cout << " W=" << setw(20) << w.c_str(); if (((Lattice* )lat_ptr)->has_time_info()) // MOD 7/3/2000 - cast added cout << " Time: " << setw(5) << start_time() << setw(5) << wdash.c_str() << setw(10) << end_time(); else{ cout << " Approx time: " << setw(5) << this->start_node().Max_dist() << setw(4) << wdash.c_str() << setw(10) << this->end_node().Max_dist(); if (start_time() >= 0) cout << " Time: " << setw(5) << start_time() << setw(5) << wdash.c_str() << setw(10) << end_time(); } cout << "Prob=" << setw(10) << Pscore(); cout << endl; cout.setf(ios::internal, ios::adjustfield); } // ///////////////////////////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const Link& link) { os.setf(ios::left, ios::adjustfield); os << " J=" << setw(6) << link.Id() << " S=" << setw(5) << link.Start_node_id() << " E=" << setw(5) << link.End_node_id(); os << " W=" << setw(20) << link.Word_idx() ; //os << " a=" << setw(10) << link.ACscore(); //os << " n=" << setw(10) << link.LMscore(); //os << " r=" << setw(10) << link.PRscore(); if (link.start_time() >= 0) os << setw(10) << link.start_time() << " -- " << setw(10) << link.end_time(); os << "score=" << setw(10) << link.Score(); os << "Pscore=" << setw(10) << link.Pscore(); os.setf(ios::internal, ios::adjustfield); assert(os.good()); return os; } /* ---------------------------------------------------------------------------------- */ /* --------------------------- Node stuff ----------- ------------------------------- */ /* ---------------------------------------------------------------------------------- */ /* ----------------------- private --------------------- */ void Node::fill_node_fields(const string& idf, const string& entry) { if (idf == "I"){ id = (NodeId)atol((const char *)entry.c_str()); }else if (idf == "t" || idf == "T"){ time = atof((const char*)entry.c_str()); }else if (idf == "v"){ } else{ cerr << "ERROR: Lattice::fill_node_fields(): unknown identifier:"; cerr << idf << " " << entry << endl; exit(1); } return; } /* --------------- public ---------------------- */ Node::Node(): lat_ptr((Lattice *)0),id(0),word_idx(-1),time(-1.0), max_dist(0){} Node::Node(const string& line, const Lattice* from_lattice, const Prons& P): lat_ptr(from_lattice),id(0),word_idx(-1),time(-1.0),max_dist(0) { static LineSplitter fields; fields.Split(line); unsigned int no_fields = fields.NoWords(); assert(no_fields < MAX_NO_FIELDS_NODE); assert(no_fields >= MIN_NO_FIELDS_NODE); assert(line.find_first_of("I") == 0); for(int i=0; i < no_fields; i++){ int pos = fields[i].find("="); assert(pos != string::npos); const string& idf = fields[i].substr(0,pos); // MOD 6/30/2000 - const added const string& entry = fields[i].substr(pos+1,string::npos); // MOD 6/30/2000 - const added if (idf == "W" || idf == "WORD") word_idx = ((Prons&) P).get_idx(entry); // MOD 6/30/2000 - cast added else fill_node_fields(idf, entry); } } // ///////////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const Node& node) { os.setf(ios::left, ios::adjustfield); os << "I=" << setw(5) << node.id; if (node.time >= 0) os << "t=" << setw(6) << node.time; if (node.word_idx != -1) os << "W=" << setw(20) << node.word_idx; os.setf(ios::internal, ios::adjustfield); assert(os.good()); return os; } // /////////////////////////////////////////////////////////////// /* ---------------------------------------------------------------------------------- */ /* --------------------------- Lattice Info Stuff ----------------------------------- */ /* ---------------------------------------------------------------------------------- */ void LatticeInfo::fill_info_fields(const string& idf, const string& entry) { if (idf == "UTTERANCE") utterance = entry; else if (idf == "wdpenalty") wdpenalty = atof((const char*)entry.c_str()); else if (idf == "lmscale" || idf == "ngscale") lmscale = atof((const char*)entry.c_str()); else if (idf == "prscale") prscale = atof((const char*)entry.c_str()); else if (idf == "NODES" || idf == "N") no_nodes = (unsigned int)atol((const char*)entry.c_str()); else if (idf == "LINKS" || idf == "L") no_links = (unsigned int)atol((const char*)entry.c_str()); else if (idf == "VERSION"){ } else if (idf == "ngname" || idf == "lmname"){ } else if (idf == "vocab"){ } else if (idf == "hmms"){ } else if (idf == "tscale"){} //else{ // cerr << "ERROR: LatticeInfo::fill_info_fields(): unknown identifier:" << endl; // cerr << idf << " " << entry << endl; // exit(1); // } return; } // ////////////////////////////////////////////////////////////////////////////////////////// LatticeInfo::LatticeInfo(const string& infile, const string& graph_type): file_name(infile), type(graph_type), utterance(""), lmscale(0), prscale(0), wdpenalty(0), no_nodes(0), no_links(0) { //istdiostream f(zopen(file_name.c_str(),"rt")); ifstream f; f.open(infile.c_str()); if (!f){ cerr << "ERROR:: File " << file_name << " doesn't exist !!" << endl; exit(1); } string line; LineSplitter fields; if (type == "SLF"){ string info_line; while(f.peek() != EOF){ getlineH(f, line); assert(f.good()); if(line.find_first_of("#") == 0) continue; else if(line.find_first_of("I") == 0) continue; else if(line.find_first_of("J") == 0) continue; else info_line += line + " "; } fields.Split(info_line); unsigned int no_fields = fields.NoWords(); assert(no_fields < MAX_NO_FIELDS_INFO_SLF); assert(no_fields >= MIN_NO_FIELDS_INFO_SLF); LineSplitter comp("="); for(int i=0; i < no_fields; i++){ assert(fields[i].find("=") != string::npos); comp.Split(fields[i]); assert(comp.NoWords() == 2); fill_info_fields(comp[0], comp[1]); } } else if (type == "FSM"){ unsigned count_lines = 0; map<string,int> m; bool add_node = false; while(f.peek() != EOF){ getlineH(f, line); assert(f.good()); if(line.find_first_of("#") == 0) continue; else{ fields.Split(line); unsigned no_fields = fields.NoWords(); assert(no_fields < MAX_NO_FIELDS_FSM); assert(no_fields >= MIN_NO_FIELDS_FSM); if (no_fields != 0) count_lines++; if (no_fields >= 3){ m[fields[0]] = 1; m[fields[1]] = 1; } } } no_links = count_lines; no_nodes = m.size() +1 ; // I will add a new end-node; this is mainly for the case with // multiple end nodes } else cerr << "ERROR:LatticeInfo():lattice type " << type << " not supported\n"; f.close(); //f.sync(); // zclose(f.rdbuf()->stdiofile()); assert(no_nodes >0); assert(no_links >0); } // //////////////////////////////////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const LatticeInfo& info) { os << "Type=" << info.type << endl; os << "File name=" << info.file_name << endl; os << "UTTERANCE=" << info.utterance << endl; os << "wdpenalty=" << info.wdpenalty << endl; os << "lmscale=" << info.lmscale << endl; os << "prscale=" << info.prscale << endl; os << "NODES=" << info.no_nodes << endl; os << "LINKS=" << info.no_links << endl; assert(os.good()); return os; } /* ---------------------------------------------------------------------------------- */ /* --------------------------- Lattice: general stuff ------------------------------- */ /* ---------------------------------------------------------------------------------- */ Lattice::Lattice(const LatticeInfo& from_info, const Prons& P): info(from_info), nodes(from_info.no_nodes), links(from_info.no_links),total_prob(LZERO),time_info(true) { //istdiostream h(zopen(info.file_name.c_str(),"rt")); //assert(h); ifstream h; h.open(info.file_name.c_str()); string line; if (info.type == "SLF"){ // go over the header lines while((h.peek() != EOF) && (h.peek() != 'I')){ getlineH(h, line); assert(h.good()); continue; } // read the nodes while((h.peek() != EOF) && (h.peek() == 'I')){ getlineH(h, line); assert(h.good()); Node this_node(line, this, P); assert(this_node.id < nodes.size()); nodes[this_node.id] = this_node; } assert (nodes.size() == info.no_nodes); if (nodes[0].time < 0) time_info = false; // this is an SLF without time information while((h.peek() != EOF) && (h.peek() != 'J')){ getlineH(h, line); assert(h.good()); continue; } // read the links while((h.peek() != EOF) && (h.peek() == 'J')){ getlineH(h, line); assert(h.good()); Link this_link(line, this, P); assert(this_link.id < links.size()); if (this_link.word_idx == -1){ Node& n = this->node(this_link.end_node_id); this_link.word_idx = n.word_idx; } links[this_link.id] = this_link; } assert(links.size() == info.no_links); } else if (info.type == "FSM"){ time_info = false; // the FSMs don't have time information unsigned count_nodes = 0; for (int i = 0; i< info.no_nodes; ++i){ Node this_node; this_node.setId(i); nodes[this_node.Id()] = this_node; // we make the assumption that the nodes have ids // between 0 and info.no_nodes; info.no_nodes-1 is the new node } unsigned count_links = 0; LineSplitter ls; while(h.peek() != EOF){ getlineH(h, line); assert(h.good()); ls.Split(line); if (ls.NoWords() != 0){ // read the links Link this_link(line, this, P); if (this_link.start_node_id == this_link.end_node_id) this_link.end_node_id = info.no_nodes-1; links[count_links] = this_link; count_links++; } } assert(info.no_links == links.size()); } else cerr << "ERROR:Lattice():lattice type " << info.type << " not supported\n"; h.close(); // h.sync(); // zclose(h.rdbuf()->stdiofile()); fill_outgoing_links(); // fill in the list of the outgoing nodes for each node bool nodes_OK = false; bool links_OK = false; if (time_info){ nodes_OK = this->check_nodes(); if (nodes_OK) links_OK = this->check_links(); } if (time_info == false || nodes_OK == false || links_OK == false){ do_TopSort(); } } // //////////////////////////////////////////////////////////////////////////////////////////////////// bool Lattice::check_nodes(){ int no_nodes = this->no_nodes(); for (int i = 1; i< no_nodes; ++i) if (nodes[i].time < nodes[i-1].time) return false; return true; } // ///////////////////////////////////////////////////////////////////////////////////////////////////// bool Lattice::check_links(){ int no_links = this->no_links(); for (int i = 0; i< no_links; ++i) if ((i > 0 && links[i].end_time() < links[i-1].end_time()) || (links[i].start_node_id > links[i].end_node_id)) return false; return true; } // ///////////////////////////////////////////////////////////////////////////////////////////////////// unsigned Lattice::put_uniform_pron_prob(const Prons& P){ if (links[0].pr_score == LZERO || fabs(links[0].pr_score)< exp(-20)){ // either the 'r' field didn't exist or it did but was 0.000 int no_links = this->no_links(); for (int i = 0; i< no_links; ++i){ int wd_idx = links[i].Word_idx(); assert(wd_idx != -1); unsigned no_prons = P.get_no_prons(wd_idx); assert(no_prons != 0); LnProb unif_pron_score = -log(no_prons); links[i].pr_score = unif_pron_score; } return 1; } else return 0; } // //////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Lattice::add_prons(const Prons& P, float PRweight) { unsigned no_links = this->no_links(); for (int i = 0; i< no_links; ++i){ int wd_idx = links[i].Word_idx(); assert(wd_idx != -1); unsigned no_prons = P.get_no_prons(wd_idx); assert(no_prons != 0); LnProb unif_pron_score = -log(no_prons); links[i].score += PRweight * unif_pron_score; } } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Lattice::scale_link_scores(const float scale) { unsigned no_links = this->no_links(); for (int i = 0; i< no_links; ++i) links[i].score /= scale; } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Lattice::add_WIP(const float WIP) { unsigned no_links = this->no_links(); for (int i = 0; i< no_links; ++i) links[i].score -= WIP; } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Lattice::compute_link_scores(const float lmscale, const float prscale, const float WIP, const float allscale) { unsigned no_links = this->no_links(); for (int i = 0; i< no_links; ++i) links[i].score = (links[i].ac_score + lmscale * links[i].lm_score + prscale * links[i].pr_score - WIP)/allscale; } // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Lattice::do_ForwardBackward() { int no_links = this->no_links(); int no_nodes = this->no_nodes(); unsigned lat_start_node = links[0].start_node_id; unsigned lat_end_node = links[no_links-1].end_node_id; vector<double> alpha(no_nodes,100000.0); alpha[lat_start_node] = 0.0; for (int j = 0; j < no_links; j++){ double new_score = alpha[links[j].start_node_id] + links[j].score; unsigned endnode_id = links[j].end_node_id; if (alpha[endnode_id] == 100000.0){ alpha[endnode_id] = new_score; } else{ double dtmp = alpha[endnode_id]; alpha[endnode_id] = LogPlus(new_score, dtmp); } } vector<double> beta(no_nodes, 100000.0); beta[lat_end_node] = 0.0; for (int j = no_links-1; j >= 0; j--){ double new_beta = beta[links[j].end_node_id] + links[j].score; unsigned startnode_id = links[j].start_node_id; if (beta[startnode_id] == 100000.0) beta[startnode_id] = new_beta; else{ double dtmp = beta[startnode_id]; beta[startnode_id] = LogPlus(new_beta,dtmp); } } assert(fabs(alpha[lat_end_node] - beta[lat_start_node]) < exp(-20)); total_prob = alpha[lat_end_node]; for (int j = 0; j < no_links; j++) links[j].pscore = alpha[links[j].start_node_id] + links[j].score + beta[links[j].end_node_id]; } // ////////////////////////////////////////////////////////////////// void Lattice::fill_outgoing_links() { int no_links = this->no_links(); for(unsigned i=0; i<no_links; i++){ Link& curr_link = links[i]; Node& start_node = nodes[curr_link.start_node_id]; start_node.outgoing_links[curr_link.end_node_id] = 1; } } // ////////////////////////////////////////////////////////////////////////////// void Lattice::mark_pruned_percentage(const float thresh){ unsigned no_links = this->no_links(); vector<Link> v = links; compLS comp_link_scores; sort(v.begin(), v.end(), comp_link_scores); for (unsigned i = 0; i< no_links; i++) if (i > thresh/100 * no_links) links[v[i].Id()].pruned = 1; } // /////////////////////////////////////////////////////////////////////////// void Lattice::mark_pruned_score(const float thresh){ unsigned no_links = this->no_links(); for (unsigned i = 0; i < no_links; i++) if (exp(total_prob - links[i].Pscore()) > thresh) links[i].pruned = 1; } // //////////////////////////////////////////////////////////////////////////////////////// void Lattice::do_TopSort() { IdsList l; unsigned no_nodes = this->no_nodes(); unsigned no_links = this->no_links(); vector<int> color(no_nodes); for (int i = 0; i<no_nodes; i++) color[i]=0; for (int i = no_nodes-1; i>=0; --i) if (color[i] == 0) DFS_visit(i,l,color); // node l[i] is mapped to i unsigned count = 0; vector<Node> nodestmp(no_nodes); for (IdsListIt it = l.begin(); it != l.end(); it++){ if (*it != count) nodestmp[count] = nodes[*it]; else nodestmp[count].setId(count); count++; } for (unsigned i = 0; i< no_nodes; i++) if (nodestmp[i].id != i){ nodes[i] = nodestmp[i]; nodes[i].setId(i); } IdsVector invl(no_nodes); count = 0; for (IdsListIt it = l.begin(); it != l.end(); it++) invl[(*it)] = count++; // node i is mapped to invl[i] for (unsigned i = 0; i< no_links; i++){ links[i].start_node_id = invl[links[i].start_node_id]; links[i].end_node_id = invl[links[i].end_node_id]; } compL comp_links; sort(links.begin(), links.end(), comp_links); for (unsigned i = 0; i< no_nodes; i++){ IntIntMap& v = nodes[i].outgoing_links; IntIntMap v1; for (IntIntMapIt it = v.begin(); it != v.end(); ++it){ v1[invl[(*it).first]]=1; } v.erase(v.begin(),v.end()); nodes[i].outgoing_links=v1; } for (unsigned i = 0; i< no_links; i++) links[i].setId(i); } // ///////////////////////////////////////////////////////////////////////////// bool Lattice::less_nodes(NodeId id1, NodeId id2, unsigned MAX_DIST ) { /* we did topological sort on the links and renamed the nodes therefore, there could be paths only between nodes with increasingly ordered ids */ if (MAX_DIST == 0){ if (id1 != id2) return 0; else return 1; } IntIntMap& v = nodes[id1].outgoing_links; for (IntIntMapIt it = v.begin(); it != v.end(); ++it){ unsigned next_node_id = (*it).first; if (next_node_id > id2) return 0; else { if (next_node_id == id2) return 1; else { if (MAX_DIST <= 1) continue; if (less_nodes(next_node_id, id2, MAX_DIST - 1)) return 1; } } } return 0; } // //////////////////////////////////////////////////////////////////// void Lattice::DFS_visit(int nodeid, IdsList& l, vector<int>& color) { color[nodeid] = 1; IntIntMap& v = nodes[nodeid].outgoing_links; for (IntIntMapIt it = v.begin(); it != v.end(); ++it){ int next_node_id = (*it).first; if (color[next_node_id] == 0) DFS_visit(next_node_id, l, color); } color[nodeid] = 2; l.push_front(nodeid); return; } // ////////////////////////////////////////////////////////////////// void Lattice::put_max_dist(const Prons& P) { unsigned no_links = this->no_links(); LineSplitter ls; int length; for (int j = 0; j < no_links; j++){ const string& ss = P.get_pron(links[j].word_idx); // MOD 6/30/2000 - const added if (ss != ""){ ls.Split(ss); length = ls.NoWords(); } else length = P.get_word(links[j].word_idx).size(); nodes[links[j].end_node_id].max_dist = max( nodes[links[j].end_node_id].max_dist, nodes[links[j].start_node_id].max_dist + length); } } // ////////////////////////////////////////////////////////////////////// int Lattice::no_words() { IntIntMap words; unsigned no_links = this->no_links(); for (int j = 0; j < no_links; j++){ int idx = links[j].word_idx; if (idx >= 0) words[idx] = 1; } return words.size(); } // /////////////////////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const Lattice& lat) { os << "#" << endl << "#nodes" << endl << "#" << endl; for(NodeId k=0; k< lat.nodes.size(); k++) os << lat.nodes[k] << endl; os << "#" << endl << "#links" << endl << "#" << endl; for(LinkId k=0; k<lat.links.size(); k++) os << lat.links[k] << endl; assert(os.good()); return os; } // //////////////////////////////////////////////////////////////////// /* ------------------------------- THE END --------------------------------------- */ <file_sep>/archive_s3/s3.0/src/libmain/kbcore.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * kbcore.h -- Structures for maintain the main models. * * * HISTORY * * 28-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #ifndef _LIBMAIN_KBCORE_H_ #define _LIBMAIN_KBCORE_H_ #include <libutil/libutil.h> #include <libfeat/libfeat.h> #include "mdef.h" #include "dict.h" #include "lm.h" #include "fillpen.h" #include "gauden.h" #include "senone.h" #include "tmat.h" #include "wid.h" typedef struct { feat_t *fcb; mdef_t *mdef; dict_t *dict; lm_t *lm; fillpen_t *fillpen; tmat_t *tmat; s3lmwid_t *dict2lmwid; gauden_t *gau; senone_t *sen; } kbcore_t; /* * Initialize one or more of all the major models: pronunciation dictionary, acoustic models, * language models. Several arguments are optional (e.g., pointers may be NULL); however, they * may not all be independently so. The logbase argument is required (i.e. must be valid). * A number of consistency verifications are carried out. It's recommended that a reasonable * default be provided for any real or integer argument, even if it's unused. * Return value: obvious. * NOTE: If any model fails to initialize, the call fails with a FATAL ERROR. */ kbcore_t *kbcore_init (float64 logbase, /* Must be specified */ char *feattype, char *mdeffile, char *dictfile, char *fdictfile, char *compsep, /* Must be valid if dictfile specified */ char *lmfile, char *fillpenfile, float64 silprob, /* Must be valid if lmfile/fillpenfile is specified */ float64 fillprob, /* Must be valid if lmfile/fillpenfile is specified */ float64 langwt, /* Must be valid if lmfile/fillpenfile is specified. */ float64 inspen, /* Must be valid if lmfile/fillpenfile is specified. */ char *meanfile, char *varfile, /* Must be specified if meanfile specified */ float64 varfloor, /* Must be valid if meanfile specified */ char *sen2mgau, /* Must be specified if mixwfile specified */ char *mixwfile, float64 mixwfloor, /* Must be valid if mixwfile specified */ char *tmatfile, float64 tmatfloor); /* Must be valid if tmatfile specified */ #endif <file_sep>/SphinxTrain/src/programs/bw/viterbi.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1996-2007 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: viterbi.c * * Description: * * Authors: * <NAME> * <NAME> *********************************************************************/ #include "forward.h" #include "backward.h" #include "viterbi.h" #include "accum.h" #include <s3/ckd_alloc.h> #include <s3/profile.h> #include <s3/remap.h> #include <s3/corpus.h> #include <s3/err.h> #include <s3/cmd_ln.h> #include <s3/s3phseg_io.h> #include <s3/model_def.h> #include <s2/byteorder.h> #include <math.h> #include <string.h> #include <assert.h> #include <stdio.h> #define INVLOGS3 100000.5 /* (1.0/log(1.0001)) */ int32 write_phseg(const char *filename, model_inventory_t *modinv, state_t *state_seq, uint32 **active_astate, uint32 *n_active_astate, uint32 n_state, uint32 n_obs, float64 **active_alpha, float64 *scale, uint32 **bp) { FILE *fh; int32 t; uint32 q; s3phseg_t *phseg, *next; model_def_t *mdef; model_def_entry_t *defn; uint32 n_defn; float64 ascr; /* Find the non-emitting ending state */ for (q = 0; q < n_active_astate[n_obs-1]; ++q) { if (active_astate[n_obs-1][q] == n_state-1) break; } if (q == n_active_astate[n_obs-1]) { E_ERROR("final state not reached\n"); return S3_ERROR; } if ((fh = fopen(filename, "w")) == NULL) { return S3_ERROR; } /* Backtrace and build a phone segmentation */ mdef = modinv->mdef; defn = mdef->defn; n_defn = mdef->n_defn; phseg = NULL; ascr = 0; for (t = n_obs-1; t >= 0; --t) { uint32 j; j = active_astate[t][q]; /* Follow any non-emitting states at time t first. */ if (state_seq[j].mixw == TYING_NON_EMITTING) { s3phseg_t *prev; uint32 phn; while (state_seq[j].mixw == TYING_NON_EMITTING) { j = active_astate[t][bp[t][q]]; q = bp[t][q]; } /* Do a rather nasty mdef scan to find the triphone in question. */ for (phn = 0; phn < n_defn; phn++) { if (state_seq[j].mixw == defn[phn].state[defn[phn].n_state-2]) break; } if (phn == n_defn) { E_ERROR("mixw %u not found\n", state_seq[j].mixw); } /* Record ascr and sf for the next phone */ if (phseg) { phseg->score = (int32)(ascr * INVLOGS3); phseg->sf = t + 1; ascr = 0; } prev = ckd_calloc(1, sizeof(*prev)); prev->next = phseg; prev->phone = phn; prev->ef = t; phseg = prev; } /* Multiply alphas to get "acoustic score" for this phone */ ascr += (log(active_alpha[t][q]) + log(scale[t])); /* Backtrace. */ if (t > 0) { q = bp[t][q]; } } fprintf(fh, "\t%5s %5s %9s %s\n", "SFrm", "EFrm", "SegAScr", "Phone"); phseg->sf = 0; /* vacuous */ while (phseg) { next = phseg->next; fprintf(fh, "\t%5d %5d %9d %s\n", phseg->sf, phseg->ef, phseg->score, acmod_set_id2name(mdef->acmod_set, phseg->phone)); ckd_free(phseg); phseg = next; } fclose(fh); return S3_SUCCESS; } int32 write_s2stseg(const char *filename, state_t *state_seq, uint32 **active_astate, uint32 *n_active_astate, uint32 n_state, uint32 n_obs, uint32 **bp) { FILE *fh; uint32 q; int32 t; uint16 word, *stseg; /* Backtrace and build a phone segmentation. */ /* Find the non-emitting ending state */ for (q = 0; q < n_active_astate[n_obs-1]; ++q) { if (active_astate[n_obs-1][q] == n_state-1) break; } if (q == n_active_astate[n_obs-1]) { E_ERROR("final state not reached\n"); return S3_ERROR; } if ((fh = fopen(filename, "wb")) == NULL) { return S3_ERROR; } word = n_obs; SWAPW(&word); fwrite(&word, 2, 1, fh); stseg = ckd_calloc(n_obs, sizeof(uint16)); for (t = n_obs-1; t >= 0; --t) { uint32 j; j = active_astate[t][q]; /* Follow any non-emitting states at time t first. */ while (state_seq[j].mixw == TYING_NON_EMITTING) { j = active_astate[t][bp[t][q]]; q = bp[t][q]; } /* mixw = senone (we hope!) */ stseg[t] = state_seq[j].mixw; SWAPW(&stseg[t]); /* Backtrace. */ if (t > 0) { q = bp[t][q]; } } fwrite(stseg, 2, n_obs, fh); ckd_free(stseg); fclose(fh); return S3_SUCCESS; } int32 viterbi_update(float64 *log_forw_prob, vector_t **feature, uint32 n_obs, state_t *state_seq, uint32 n_state, model_inventory_t *inv, float64 a_beam, float32 spthresh, s3phseg_t *phseg, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 pass2var, int32 var_is_full, FILE *pdumpfh, float32 ***lda) { float64 *scale = NULL; float64 **dscale = NULL; float64 **active_alpha; uint32 **active_astate; uint32 **bp; uint32 *n_active_astate; gauden_t *g; /* Gaussian density parameters and reestimation sums */ float32 ***mixw; /* all mixing weights */ float64 ***now_den = NULL; /* Short for den[t] */ uint32 ***now_den_idx = NULL;/* Short for den_idx[t] */ uint32 *active_cb; uint32 n_active_cb; float32 **tacc; /* Transition matrix reestimation sum accumulators for the utterance. */ float32 ***wacc; /* mixing weight reestimation sum accumulators for the utterance. */ float32 ***denacc = NULL; /* mean/var reestimation accumulators for time t */ size_t denacc_size; /* Total size of data references in denacc. Allows for quick clears between time frames */ uint32 n_lcl_cb; uint32 *cb_inv; uint32 i, j, q; int32 t; uint32 n_feat; uint32 n_density; uint32 n_top; int ret; timing_t *fwd_timer = NULL; timing_t *rstu_timer = NULL; timing_t *gau_timer = NULL; timing_t *rsts_timer = NULL; timing_t *rstf_timer = NULL; float64 log_fp; /* accumulator for the log of the probability * of observing the input given the model */ uint32 max_n_next = 0; uint32 n_cb; static float64 *p_op = NULL; static float64 *p_ci_op = NULL; static float64 **d_term = NULL; static float64 **d_term_ci = NULL; /* caller must ensure that there is some non-zero amount of work to be done here */ assert(n_obs > 0); assert(n_state > 0); /* Get the forward estimation CPU timer */ fwd_timer = timing_get("fwd"); /* Get the per utterance reestimation CPU timer */ rstu_timer = timing_get("rstu"); /* Get the Gaussian density evaluation CPU timer */ gau_timer = timing_get("gau"); /* Get the per state reestimation CPU timer */ rsts_timer = timing_get("rsts"); /* Get the per frame reestimation CPU timer */ rstf_timer = timing_get("rstf"); g = inv->gauden; n_feat = gauden_n_feat(g); n_density = gauden_n_density(g); n_top = gauden_n_top(g); n_cb = gauden_n_mgau(g); if (p_op == NULL) { p_op = ckd_calloc(n_feat, sizeof(float64)); p_ci_op = ckd_calloc(n_feat, sizeof(float64)); } if (d_term == NULL) { d_term = (float64 **)ckd_calloc_2d(n_feat, n_top, sizeof(float64)); d_term_ci = (float64 **)ckd_calloc_2d(n_feat, n_top, sizeof(float64)); } scale = (float64 *)ckd_calloc(n_obs, sizeof(float64)); dscale = (float64 **)ckd_calloc(n_obs, sizeof(float64 *)); n_active_astate = (uint32 *)ckd_calloc(n_obs, sizeof(uint32)); active_alpha = (float64 **)ckd_calloc(n_obs, sizeof(float64 *)); active_astate = (uint32 **)ckd_calloc(n_obs, sizeof(uint32 *)); active_cb = ckd_calloc(2*n_state, sizeof(uint32)); bp = (uint32 **)ckd_calloc(n_obs, sizeof(uint32 *)); /* Run forward algorithm, which has embedded Viterbi. */ if (fwd_timer) timing_start(fwd_timer); ret = forward(active_alpha, active_astate, n_active_astate, bp, scale, dscale, feature, n_obs, state_seq, n_state, inv, a_beam, phseg); /* Dump a phoneme segmentation if requested */ if (cmd_ln_str("-outphsegdir")) { const char *phsegdir; char *segfn, *uttid; phsegdir = cmd_ln_str("-outphsegdir"); uttid = (cmd_ln_int32("-outputfullpath") ? corpus_utt_full_name() : corpus_utt()); segfn = ckd_calloc(strlen(phsegdir) + 1 + strlen(uttid) + strlen(".phseg") + 1, 1); strcpy(segfn, phsegdir); strcat(segfn, "/"); strcat(segfn, uttid); strcat(segfn, ".phseg"); write_phseg(segfn, inv, state_seq, active_astate, n_active_astate, n_state, n_obs, active_alpha, scale, bp); ckd_free(segfn); } if (fwd_timer) timing_stop(fwd_timer); if (ret != S3_SUCCESS) { /* Some problem with the utterance, release per utterance storage and * forget about adding the utterance accumulators to the global accumulators */ goto all_done; } mixw = inv->mixw; if (mixw_reest) { /* Need to reallocate mixing accumulators for utt */ if (inv->l_mixw_acc) { ckd_free_3d((void ***)inv->l_mixw_acc); inv->l_mixw_acc = NULL; } inv->l_mixw_acc = (float32 ***)ckd_calloc_3d(inv->n_mixw_inverse, n_feat, n_density, sizeof(float32)); } wacc = inv->l_mixw_acc; n_lcl_cb = inv->n_cb_inverse; cb_inv = inv->cb_inverse; /* Allocate local accumulators for mean, variance reestimation sums if necessary */ gauden_alloc_l_acc(g, n_lcl_cb, mean_reest, var_reest, var_is_full); if (tmat_reest) { if (inv->l_tmat_acc) { ckd_free_2d((void **)inv->l_tmat_acc); inv->l_tmat_acc = NULL; } for (i = 0; i < n_state; i++) { if (state_seq[i].n_next > max_n_next) max_n_next = state_seq[i].n_next; } inv->l_tmat_acc = (float32 **)ckd_calloc_2d(n_state, max_n_next, sizeof(float32)); } /* transition matrix reestimation sum accumulators for the utterance */ tacc = inv->l_tmat_acc; n_active_cb = 0; now_den = (float64 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_top, sizeof(float64)); now_den_idx = (uint32 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_top, sizeof(uint32)); if (mean_reest || var_reest) { /* allocate space for the per frame density counts */ denacc = (float32 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_density, sizeof(float32)); /* # of bytes required to store all weighted vectors */ denacc_size = n_lcl_cb * n_feat * n_density * sizeof(float32); } else { denacc = NULL; denacc_size = 0; } /* Okay now run through the backtrace and accumulate counts. */ /* Find the non-emitting ending state */ for (q = 0; q < n_active_astate[n_obs-1]; ++q) { if (active_astate[n_obs-1][q] == n_state-1) break; } if (q == n_active_astate[n_obs-1]) { E_ERROR("final state not reached\n"); ret = S3_ERROR; goto all_done; } for (t = n_obs-1; t >= 0; --t) { uint32 l_cb; uint32 l_ci_cb; float64 op, p_reest_term; uint32 prev; j = active_astate[t][q]; /* Follow any non-emitting states at time t first. */ while (state_seq[j].mixw == TYING_NON_EMITTING) { prev = active_astate[t][bp[t][q]]; #if VITERBI_DEBUG printf("Following non-emitting state at time %d, %u => %u\n", t, j, prev); #endif /* Backtrace and accumulate transition counts. */ if (tmat_reest) { assert(tacc != NULL); tacc[prev][j - prev] += 1.0; } q = bp[t][q]; j = prev; } /* Now accumulate statistics for the real state. */ l_cb = state_seq[j].l_cb; l_ci_cb = state_seq[j].l_ci_cb; n_active_cb = 0; if (gau_timer) timing_start(gau_timer); gauden_compute_log(now_den[l_cb], now_den_idx[l_cb], feature[t], g, state_seq[j].cb, NULL); active_cb[n_active_cb++] = l_cb; if (l_cb != l_ci_cb) { gauden_compute_log(now_den[l_ci_cb], now_den_idx[l_ci_cb], feature[t], g, state_seq[j].ci_cb, NULL); active_cb[n_active_cb++] = l_ci_cb; } gauden_scale_densities_bwd(now_den, now_den_idx, &dscale[t], active_cb, n_active_cb, g); assert(state_seq[j].mixw != TYING_NON_EMITTING); /* Now calculate mixture densities. */ /* This is the normalizer sum_m c_{jm} p(o_t|\lambda_{jm}) */ op = gauden_mixture(now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], g); if (gau_timer) timing_stop(gau_timer); if (rsts_timer) timing_start(rsts_timer); /* Make up this bogus value to be consistent with backward.c */ p_reest_term = 1.0 / op; /* Compute the output probability excluding the contribution * of each feature stream. i.e. p_op[0] is the output * probability excluding feature stream 0 */ partial_op(p_op, op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], n_feat, n_top); /* compute the probability of each (of possibly topn) density */ den_terms(d_term, p_reest_term, p_op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], n_feat, n_top); if (l_cb != l_ci_cb) { /* For each feature stream f, compute: * sum_k(mixw[f][k] den[f][k]) * and store the results in p_ci_op */ partial_ci_op(p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[j].ci_mixw], n_feat, n_top); /* For each feature stream and density compute the terms: * w[f][k] den[f][k] / sum_k(w[f][k] den[f][k]) * post_j * and store results in d_term_ci */ den_terms_ci(d_term_ci, 1.0, /* post_j = 1.0 */ p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[j].ci_mixw], n_feat, n_top); } /* accumulate the probability for each density in the mixing * weight reestimation accumulators */ if (mixw_reest) { accum_den_terms(wacc[state_seq[j].l_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); /* check if mixw and ci_mixw are different to avoid * doubling the EM counts in a CI run. */ if (state_seq[j].mixw != state_seq[j].ci_mixw) { if (n_cb < inv->n_mixw) { /* semi-continuous, tied mixture, and discrete case */ accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); } else { /* continuous case */ accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } } /* accumulate the probability for each density in the * density reestimation accumulators */ if (mean_reest || var_reest) { accum_den_terms(denacc[l_cb], d_term, now_den_idx[l_cb], n_feat, n_top); if (l_cb != l_ci_cb) { accum_den_terms(denacc[l_ci_cb], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } if (rsts_timer) timing_stop(rsts_timer); /* Note that there is only one state/frame so this is kind of redundant */ if (rstf_timer) timing_start(rstf_timer); if (mean_reest || var_reest) { /* Update the mean and variance reestimation accumulators */ if (pdumpfh) fprintf(pdumpfh, "time %d:\n", t); accum_gauden(denacc, cb_inv, n_lcl_cb, feature[t], now_den_idx, g, mean_reest, var_reest, pass2var, inv->l_mixw_acc, var_is_full, pdumpfh, lda); memset(&denacc[0][0][0], 0, denacc_size); } if (rstf_timer) timing_stop(rstf_timer); if (t > 0) { prev = active_astate[t-1][bp[t][q]]; #if VITERBI_DEBUG printf("Backtrace at time %d, %u => %u\n", t, j, prev); #endif /* Backtrace and accumulate transition counts. */ if (tmat_reest) { assert(tacc != NULL); tacc[prev][j-prev] += 1.0; } q = bp[t][q]; j = prev; } } /* If no error was found, add the resulting utterance reestimation * accumulators to the global reestimation accumulators */ if (rstu_timer) timing_start(rstu_timer); accum_global(inv, state_seq, n_state, mixw_reest, tmat_reest, mean_reest, var_reest, var_is_full); if (rstu_timer) timing_stop(rstu_timer); /* Find the final state */ for (i = 0; i < n_active_astate[n_obs-1]; ++i) { if (active_astate[n_obs-1][i] == n_state-1) break; } /* Calculate log[ p( O | \lambda ) ] */ assert(active_alpha[n_obs-1][i] > 0); log_fp = log(active_alpha[n_obs-1][i]); for (t = 0; t < n_obs; t++) { assert(scale[t] > 0); log_fp -= log(scale[t]); for (j = 0; j < inv->gauden->n_feat; j++) { log_fp += dscale[t][j]; } } *log_forw_prob = log_fp; all_done: ckd_free((void *)scale); for (i = 0; i < n_obs; i++) { if (dscale[i]) ckd_free((void *)dscale[i]); } ckd_free((void **)dscale); ckd_free(n_active_astate); for (i = 0; i < n_obs; i++) { ckd_free((void *)active_alpha[i]); ckd_free((void *)active_astate[i]); ckd_free((void *)bp[i]); } ckd_free((void *)active_alpha); ckd_free((void *)active_astate); ckd_free((void *)active_cb); if (denacc) ckd_free_3d((void ***)denacc); if (now_den) ckd_free_3d((void ***)now_den); if (now_den_idx) ckd_free_3d((void ***)now_den_idx); if (ret != S3_SUCCESS) E_ERROR("%s ignored\n", corpus_utt_brief_name()); return ret; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 1996/07/29 16:20:55 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/mk_flat/main.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * * Author: * (probably) <NAME> *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/model_def_io.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s2_read_seno.h> #include <s3/s3mixw_io.h> #include <s3/s3tmat_io.h> #include <s3/s2_param.h> #include <s3/topo_read.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #define NO_STATE 0xffffffff int main(int argc, char *argv[]) { model_def_t *mdef; uint32 n_tmat; uint32 n_tied_state; uint32 n_state_pm; uint32 n_stream; uint32 n_density; float32 ***tmat; float32 **proto_tmat; float32 ***mixw; uint32 i, j, k; float32 mixw_ini; int retval = 0; parse_cmd_ln(argc, argv); printf("%s(%d): Reading model definition file %s\n", __FILE__, __LINE__, (const char *)cmd_ln_access("-moddeffn")); if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { return 1; } printf("%s(%d): %d models defined\n", __FILE__, __LINE__, mdef->n_defn); if (!cmd_ln_access("-tmatfn") && ! cmd_ln_access("-mixwfn")){ E_FATAL("Both -tmatfn and -mixwfn were not specified, forced exit\n"); } if (cmd_ln_access("-tmatfn")) { if (topo_read(&proto_tmat, &n_state_pm, cmd_ln_access("-topo")) != S3_SUCCESS) return 1; /* proto_tmat is normalized */ n_tmat = mdef->n_tied_tmat; tmat = (float32 ***)ckd_calloc_3d(n_tmat, n_state_pm-1, n_state_pm, sizeof(float32)); for (k = 0; k < n_tmat; k++) { for (i = 0; i < n_state_pm-1; i++) { for (j = 0; j < n_state_pm; j++) { /* perhaps this could be replaced with a block copy per tmat */ tmat[k][i][j] = proto_tmat[i][j]; } } } if (s3tmat_write(cmd_ln_access("-tmatfn"), tmat, n_tmat, n_state_pm) != S3_SUCCESS) { retval = 1; } ckd_free_3d((void ***)tmat); } else { E_INFO("No tmat file given; none generated\n"); } n_tied_state = mdef->n_tied_state; n_stream = *(int32 *)cmd_ln_access("-nstream"); n_density = *(int32 *)cmd_ln_access("-ndensity"); mixw = (float32 ***)ckd_calloc_3d(n_tied_state, n_stream, n_density, sizeof(float32)); /* weight each density uniformly */ mixw_ini = 1.0 / (float)n_density; for (i = 0; i < n_tied_state; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { mixw[i][j][k] = mixw_ini; } } } if (cmd_ln_access("-mixwfn")) { if (s3mixw_write(cmd_ln_access("-mixwfn"), mixw, n_tied_state, n_stream, n_density) != S3_SUCCESS) { retval = 2; } } else { E_INFO("No mixw file given; none generated\n"); } ckd_free_3d((void ***)mixw); return retval; } <file_sep>/CLP/include/Cluster.h //------------------------------------------------------------------------------------------- // Implementation of a cluster (set of links with the corresponding set of words) //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _Cluster_h #define _Cluster_h #include "common_lattice.h" #include "Link.h" #include "Prob.h" #include "Lattice.h" #include "Similarities.h" class Cluster { friend class Clustering; public: Cluster(); Cluster(unsigned, const Lattice*); const unsigned Id() const {return cid;} void setId(unsigned id) {cid = id;} unsigned Best_link() const {return best_link;} unsigned no_links() const {return clinks.size();} unsigned no_words() const {return cwords.size();} // add a link to a cluster void add_link(const Link& l); // returns 1 if the first link in the cluster has the start time = starttime and the word index = widx bool match_start_word(float starttime, unsigned widx); // merge with cluster c (stage = intra or inter clustering) void merge_with(const Cluster& c, const int stage); // returns 1 if the two clusters are ordered (there is a link in one class which is less than a link in the second one) int is_less(const Cluster& c, const IntIntIntMap& removed); unsigned compare_less(const Cluster& c, IntIntIntMap& are_less, unsigned MAX_DIST); // from the list of links obtain the list of words with their corresponding posterior probabilities void fill_cwords(); // index of the word on the first link in the cluster unsigned wordidx(); // ending time of the first link in the cluster float end_time(); // starting time of the first link in the cluster float start_time(); // approximative ending time of the first link in the cluster (for the lattices with no time info) int approx_end_time(); // starting time of the first link in the cluster int approx_start_time(); // the length of the longest path from the lattice start node to the end node of the first link in the cluster int max_dist(); friend ostream& operator << (ostream& os, const Cluster& c); void print(const Prons& P, bool print_links, bool print_words); float Min_time() { return min_time;} float Max_time(){return max_time;} private: const Lattice* lat_ptr; unsigned cid; /* cluster id */ IdsList clinks; /* vector of ids of all the links in the class */ IntDblMap cwords; /* all the words occuring in the cluster (and their post probs) */ int best_link; /* the link with the highest posterior in the cluster */ float min_time; float max_time; }; #endif <file_sep>/archive_s3/s3.0/src/libmisc/alpha/datagen.c #include <libutil/libutil.h> main (int32 argc, char *argv[]) { int32 r, c; int32 i, j; if (argc != 3) E_FATAL("Usage: %s #rows #cols\n", argv[0]); sscanf (argv[1], "%d", &r); sscanf (argv[2], "%d", &c); printf ("%d %d\n", r, c); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) printf (" %.6f", drand48()); printf ("\n"); } } <file_sep>/SphinxTrain/include/s2/byteorder.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* in place byte order conversion nothing is promised to be returned currently only works for suns and Vax MIPS machines */ /* defines needed for little endian machines */ #ifndef WORDS_BIGENDIAN /* Determined by the configure script */ #define NEEDS_SWAP #define SWAPBYTES #define SWAPW(x) *(x) = ((0xff & (*(x))>>8) | (0xff00 & (*(x))<<8)) #define SWAPL(x) *(x) = ((0xff & (*(x))>>24) | (0xff00 & (*(x))>>8) |\ (0xff0000 & (*(x))<<8) | (0xff000000 & (*(x))<<24)) #define SWAPF(x) SWAPL((int *) x) #define SWAPP(x) SWAPL((int *) x) #define SWAPD(x) { int *low = (int *) (x), *high = (int *) (x) + 1,\ temp;\ SWAPL(low); SWAPL(high);\ temp = *low; *low = *high; *high = temp;} /* yes, these "reversed senses" are confusing. FIXME. */ #define SWAP_W(x) #define SWAP_L(x) #else /* don't need byte order conversion, do nothing */ #undef NEEDS_SWAP #define SWAPW(x) #define SWAPL(x) #define SWAPF(x) #define SWAPP(x) #define SWAPD(x) /* "reversed senses". FIXME. */ #define SWAP_W(x) x = ( (((x)<<8)&0x0000ff00) | (((x)>>8)&0x00ff) ) #define SWAP_L(x) x = ( (((x)<<24)&0xff000000) | (((x)<<8)&0x00ff0000) | \ (((x)>>8)&0x0000ff00) | (((x)>>24)&0x000000ff) ) #endif <file_sep>/archive_s3/s3/src/libfbs/lmcontext.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * lmcontext.h -- Surrounding LM context for each utterance * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 26-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _LMCONTEXT_H_ #define _LMCONTEXT_H_ #include <libmisc/corpus.h> #include <s3.h> #include "dict.h" /* * Read LM context words for the given uttid from the given corpus. Two words of * preceding context, and 1 word of succeeding context. The preceding context can be: * - - (i.e., no context, use unigram transition to first word) * - <word> (single word context, can be START_WORD) * <word1> <word2> (two word context) * The succeeding context can be: * - (i.e., no context, utt can end in any word) * FINISH_WORD (utt must end in FINISH_WORD). * (FATAL_ERROR if any error, such as unknown word, or missing context spec for uttid.) */ void lmcontext_load (corpus_t *corp, /* In: Corpus to look up */ char *uttid, /* In: Uttid to look for in corpus */ s3wid_t *pred, /* Out: pred[0],pred[1] = two word history; pred[0] is earlier than pred[1] */ s3wid_t *succ); /* Out: *succ = FINISH_WORD id or BAD_WID */ #endif <file_sep>/SphinxTrain/src/libs/libcommon/matrix.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: matrix.c * * Description: * * Author: * *********************************************************************/ #include <string.h> #include <stdlib.h> #include <s3/matrix.h> #include <s3/s3.h> #include <s3/err.h> #include <s3/clapack_lite.h> #include <s3/ckd_alloc.h> void norm_3d(float32 ***arr, uint32 d1, uint32 d2, uint32 d3) { uint32 i, j, k; float64 s; for (i = 0; i < d1; i++) { for (j = 0; j < d2; j++) { /* compute sum (i, j) as over all k */ for (k = 0, s = 0; k < d3; k++) { s += arr[i][j][k]; } /* do 1 floating point divide */ s = 1.0 / s; /* divide all k by sum over k */ for (k = 0; k < d3; k++) { arr[i][j][k] *= s; } } } } void accum_3d(float32 ***out, float32 ***in, uint32 d1, uint32 d2, uint32 d3) { uint32 i, j, k; for (i = 0; i < d1; i++) { for (j = 0; j < d2; j++) { for (k = 0; k < d3; k++) { out[i][j][k] += in[i][j][k]; } } } } void floor_3d(float32 ***m, uint32 d1, uint32 d2, uint32 d3, float32 floor) { uint32 i, j, k; for (i = 0; i < d1; i++) { for (j = 0; j < d2; j++) { for (k = 0; k < d3; k++) { if (m[i][j][k] < floor) m[i][j][k] = floor; } } } } void floor_nz_3d(float32 ***m, uint32 d1, uint32 d2, uint32 d3, float32 floor) { uint32 i, j, k; for (i = 0; i < d1; i++) { for (j = 0; j < d2; j++) { for (k = 0; k < d3; k++) { if ((m[i][j][k] != 0) && (m[i][j][k] < floor)) m[i][j][k] = floor; } } } } void floor_nz_1d(float32 *v, uint32 d1, float32 floor) { uint32 i; for (i = 0; i < d1; i++) { if ((v[i] != 0) && (v[i] < floor)) v[i] = floor; } } /* Ensures that non-zero values x such that * -band < x < band, band > 0 * are set to -band if x < 0 and band if x > 0. */ void band_nz_1d(float32 *v, uint32 d1, float32 band) { uint32 i; for (i = 0; i < d1; i++) { if (v[i] != 0) { if ((v[i] > 0) && (v[i] < band)) { v[i] = band; } else if ((v[i] < 0) && (v[i] > -band)) { v[i] = -band; } } } } /* Find determinant through LU decomposition. */ float64 determinant(vector_t *a, int32 n) { float32 *tmp_a; float64 det; int32 M, N, LDA, INFO; int32 *IPIV; int32 i, j; M = N = LDA = n; /* To use the f2c lapack function, row/column ordering of the arrays need to be changed. (FIXME: might be faster to do this in-place twice?) */ tmp_a = (float32 *)ckd_calloc(N * N, sizeof(float32)); for (i = 0; i < N; i++) for (j = 0; j < N; j++) tmp_a[j+N*i] = a[i][j]; IPIV = (int32 *)ckd_calloc(N, sizeof(int32)); sgetrf_(&M, &N, tmp_a, &LDA, IPIV, &INFO); det = IPIV[0] == 1 ? tmp_a[0] : -tmp_a[0]; for (i = 1; i < n; ++i) { if (IPIV[i] != i+1) det *= -tmp_a[i+N*i]; else det *= tmp_a[i+N*i]; } ckd_free(tmp_a); ckd_free(IPIV); return det; } /* Find inverse by solving AX=I. */ int32 invert(vector_t *ainv, vector_t *a, int32 n) { float32 *tmp_a, *tmp_i; int i, j; int32 N, NRHS, LDA, LDB, INFO; int32 *IPIV; N=n; NRHS=n; LDA=n; LDB=n; /* To use the f2c lapack function, row/column ordering of the arrays need to be changed. (FIXME: might be faster to do this in-place twice?) */ tmp_a = (float32 *)ckd_calloc(N * N, sizeof(float32)); for (i = 0; i < N; i++) for (j = 0; j < N; j++) tmp_a[j+N*i] = a[i][j]; /* Construct an identity matrix. */ tmp_i = (float32 *) ckd_calloc(N * N, sizeof(float32)); for (i = 0; i < N; i++) tmp_i[i+N*i] = 1.0; IPIV = (int32 *)ckd_calloc(N, sizeof(int32)); /* Beware! all arguments of lapack have to be a pointer */ sgesv_(&N, &NRHS, tmp_a, &LDA, IPIV, tmp_i, &LDB, &INFO); if (INFO != 0) return S3_ERROR; /* FIXME: We should be able to do this in place actually */ for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) ainv[i][j] = tmp_i[j+N*i]; ckd_free ((void *)tmp_a); ckd_free ((void *)tmp_i); ckd_free ((void *)IPIV); return S3_SUCCESS; } int32 eigenvectors(float32 **a, float32 *out_ur, float32 *out_ui, float32 **out_vr, float32 **out_vi, int32 len) { float32 *tmp_a, *vr, *work, lwork; int32 one, info, ilwork, all_real, i, j; char no, yes; /* Transpose A to FORTRAN format. */ tmp_a = ckd_calloc(len * len, sizeof(float32)); for (i = 0; i < len; i++) for (j = 0; j < len; j++) tmp_a[len * j + i] = a[i][j]; /* Right eigenvectors. */ vr = ckd_calloc(len * len, sizeof(float32)); /* Find the optimal workspace. */ one = 1; no = 'N'; yes = 'V'; ilwork = -1; sgeev_(&no, &yes, &len, tmp_a, &len, out_ur, out_ui, NULL, &one, vr, &len, &lwork, &ilwork, &info); if (info != 0) E_FATAL("Failed to get workspace from SGEEV: %d\n", info); /* Allocate workspace. */ ilwork = (int)lwork; work = ckd_calloc(ilwork, sizeof(float32)); /* Actually calculate the eigenvectors. */ sgeev_(&no, &yes, &len, tmp_a, &len, out_ur, out_ui, NULL, &one, vr, &len, work, &ilwork, &info); ckd_free(work); ckd_free(tmp_a); /* Reconstruct the outputs. */ /* Check if all eigenvalues are real. */ all_real = 1; for (i = 0; i < len; i++) { if (out_ui[i] != 0.0) { all_real = 0; break; } } if (all_real) { /* Then all eigenvectors are real. */ memset(out_vi[0], 0, sizeof(float32) * len * len); /* We don't need to do anything because LAPACK places the * eigenvectors in the columns in FORTRAN order, which puts * them in the rows for us. */ memcpy(out_vr[0], vr, sizeof(float32) * len * len); } else { for (i = 0; i < len; ++i) { if (out_ui[i] == 0.0) { for (j = 0; j < len; ++j) { /* Again, see above: FORTRAN column order. */ out_vr[i][j] = vr[i * len + j]; } } else { /* There is a complex conjugate pair here. */ if (i < len-1) { for (j = 0; j < len; ++j) { out_vr[i][j] = vr[i * len + j]; out_vi[i][j] = vr[(i + 1) * len + j]; out_vr[i+1][j] = vr[i * len + j]; out_vi[i+1][j] = -vr[(i+1) * len + j]; } ++i; } else { E_FATAL("Complex eigenvalue at final index %d?!\n", len-1); } } } } ckd_free(vr); return info; } void outerproduct(vector_t *a, vector_t x, vector_t y, int32 len) { int32 i, j; for (i = 0; i < len; ++i) { a[i][i] = x[i] * y[i]; for (j = i+1; j < len; ++j) { a[i][j] = x[i] * y[j]; a[j][i] = x[j] * y[i]; } } } void matrixmultiply(vector_t *c, vector_t *a, vector_t *b, int32 m, int32 n, int32 k) { int32 i, j, r; /* FIXME: Probably faster to do this with SGEMM */ memset(c[0], 0, sizeof(float32) * m * n); for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) for (r = 0; r < k; ++r) c[i][j] += a[i][r] * b[r][j]; } void scalarmultiply(vector_t *a, float32 x, int32 m, int32 n) { int32 i, j; for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) a[i][j] *= x; } void matrixadd(vector_t *a, vector_t *b, int32 m, int32 n) { int32 i, j; for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) a[i][j] += b[i][j]; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/mllr_transform/main.c /********************************************************************* * * $Header: * * Carnegie Mellon ARPA Speech Group * * Modify Gaussian mean vector using mllr (the output of mllr_mat) * * Modified: <EMAIL>, 990315 * * Copyright (c) 1996 -2004Carnegie Mellon University. * All rights reserved. * *********************************************************************/ /* * 2004-07-25 ARCHAN: first adapted from Sam Joo's program to SphinxTrain. */ #include "parse_cmd_ln.h" /* The SPHINX-III common library */ #include <s3/common.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3gau_io.h> #include <s3/gauden.h> #include <s3/mllr.h> #include <s3/mllr_io.h> #include <s3/s3cb2mllr_io.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s3/s3.h> #include <s3/err.h> #include <sys_compat/file.h> #include <sys_compat/misc.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <string.h> #define MAX2(x,y) ((x) > (y) ? (x):(y)) #define ABS(x) ((x) < 0. ? (-(x)):(x)) static int initialize(int argc, char *argv[]) { /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); return S3_SUCCESS; } static int read_mllr_files(const char *mllrmatfn, const char *cb2mllrfn, float32 *****out_A, float32 ****out_B, int32 **out_cb2mllr, uint32 *out_n_mllr_class, uint32 *out_n_mgau, uint32 *out_n_feat, const uint32 **out_veclen, uint32 inverse) { uint32 n_mllr_class_rd, m, j; E_INFO("Read %s\n", mllrmatfn); if (read_reg_mat(mllrmatfn, out_veclen, out_n_mllr_class, out_n_feat, out_A, out_B) != S3_SUCCESS) { E_FATAL("Unable to read %s\n",mllrmatfn); } E_INFO("n_mllr_class = %d\n", *out_n_mllr_class); if (inverse) { float32 **** ainv; ainv = (float32 ****)ckd_calloc_2d((*out_n_mllr_class), (*out_n_feat), sizeof(float32 **)); for (m = 0; m < *out_n_mllr_class; ++m) { for (j = 0; j < *out_n_feat; ++j) { ainv[m][j] = (float32 **)ckd_calloc_2d((*out_veclen)[j], (*out_veclen)[j], sizeof(float32)); invert(ainv[m][j], (*out_A)[m][j], (*out_veclen)[j]); } } free_mllr_A(*out_A, *out_n_mllr_class, *out_n_feat); *out_A = ainv; } if (strcmp(cb2mllrfn, ".1cls.") == 0) { n_mllr_class_rd = 1; *out_cb2mllr = NULL; *out_n_mgau = 0; } else { if (s3cb2mllr_read(cb2mllrfn, out_cb2mllr, out_n_mgau, &n_mllr_class_rd) != S3_SUCCESS) { E_FATAL("Unable to read %s\n", cb2mllrfn); } } if (n_mllr_class_rd != *out_n_mllr_class) { E_FATAL("# MLLR class, %u, inconsistent w/ cb2mllr # MLLR class, %u\n", n_mllr_class_rd, *out_n_mllr_class); } return S3_SUCCESS; } static int read_mdef(const char *moddeffn, model_def_t **out_mdef, uint32 *out_gau_begin, int32 *cb2mllr) { uint32 i; if (! moddeffn) { E_FATAL("-moddeffn is not given.\n"); } else if (model_def_read(out_mdef, moddeffn) != S3_SUCCESS) { E_FATAL("Can not read model definition file %s\n", moddeffn); } if (cb2mllr == NULL) cb2mllr = (char *)ckd_calloc((*out_mdef)->n_total_state,sizeof(char)); *out_gau_begin = (*out_mdef)->n_tied_ci_state; for (i = 0; i < *out_gau_begin; i++) { cb2mllr[i] = -1; /* skip CI senones */ } E_INFO("Use CD senones only. (index >= %d)\n",(*out_mdef)->n_tied_ci_state); return S3_SUCCESS; } static int mllr_adapt_mean(const char *outmeanfn, const char *inmeanfn, const char *mllrmatfn, const char *cb2mllrfn, const char *moddeffn, uint32 cdonly, uint32 inverse) { model_def_t *mdef = NULL; vector_t ***mean = NULL; uint32 n_mgau; uint32 n_feat; uint32 n_density; const uint32 *veclen = NULL; uint32 n_mgau_rd; uint32 n_feat_rd; const uint32 *veclen_rd = NULL; uint32 n_mllr_class; int32 *cb2mllr = NULL; float32 ****A = NULL; float32 ***B = NULL; uint32 j; uint32 gau_begin; read_mllr_files(mllrmatfn, cb2mllrfn, &A, &B, &cb2mllr, &n_mllr_class, &n_mgau, &n_feat, &veclen, inverse); /* Read input means */ fprintf(stderr,"\n"); if (s3gau_read(inmeanfn, &mean, &n_mgau_rd, &n_feat_rd, &n_density, &veclen_rd) != S3_SUCCESS) { E_FATAL("Unable to read Gaussian means from %s\n",inmeanfn); } if (n_mgau == 0) n_mgau = n_mgau_rd; if (n_mgau_rd != n_mgau) { E_FATAL("# means %u inconsistent w/ cb2mllr # cb %u\n", n_mgau_rd, n_mgau); } else if (n_feat_rd != n_feat) { E_FATAL("# feature stream inconsistent. (%u : %u)\n",n_feat_rd,n_feat); } else { for (j=0; j < n_feat; j++) { if (veclen_rd[j] != veclen[j]) { E_FATAL("veclen inconsistent. (%u : %u)\n",veclen_rd[j],veclen[j]); } } } ckd_free((void *)veclen_rd); gau_begin = 0; if (cdonly) read_mdef(moddeffn, &mdef, &gau_begin, cb2mllr); fprintf(stderr,"\n"); E_INFO("Adapt mean values.\n"); mllr_transform_mean(mean, NULL, gau_begin, n_mgau, n_feat, n_density, veclen, A, B, cb2mllr, n_mllr_class); fprintf(stderr,"\n"); if (s3gau_write(outmeanfn, (const vector_t ***)mean, n_mgau, n_feat, n_density, veclen) != S3_SUCCESS) { E_FATAL("Unable to write Gaussian means to %s\n",outmeanfn); } return S3_SUCCESS; } static int mllr_adapt_gaucnt(const char *outgaufn, const char *ingaufn, const char *mllrmatfn, const char *cb2mllrfn, const char *moddeffn, uint32 cdonly, uint32 inverse) { model_def_t *mdef = NULL; vector_t ***wt_mean = NULL; vector_t ***wt_var = NULL; int32 pass2var; float32 ***dnom = NULL; uint32 n_mgau; uint32 n_feat; uint32 n_density; const uint32 *veclen = NULL; uint32 n_mgau_rd; uint32 n_feat_rd; const uint32 *veclen_rd = NULL; uint32 n_mllr_class; uint32 gau_begin; int32 *cb2mllr = NULL; float32 ****A = NULL; float32 ***B = NULL; uint32 j; read_mllr_files(mllrmatfn, cb2mllrfn, &A, &B, &cb2mllr, &n_mllr_class, &n_mgau, &n_feat, &veclen, inverse); fprintf(stderr,"\n"); if (s3gaucnt_read(ingaufn, &wt_mean, &wt_var, &pass2var, &dnom, &n_mgau_rd, &n_feat_rd, &n_density, &veclen_rd) != S3_SUCCESS) { E_FATAL("Unable to read Gaussian counts from %s\n", ingaufn); } if (n_mgau == 0) n_mgau = n_mgau_rd; if (n_mgau_rd != n_mgau) { E_FATAL("# means %u inconsistent w/ cb2mllr # cb %u\n", n_mgau_rd, n_mgau); } else if (n_feat_rd != n_feat) { E_FATAL("# feature stream inconsistent. (%u : %u)\n",n_feat_rd,n_feat); } else { for (j=0; j < n_feat; j++) { if (veclen_rd[j] != veclen[j]) { E_FATAL("veclen inconsistent. (%u : %u)\n",veclen_rd[j],veclen[j]); } } } ckd_free((void *)veclen_rd); gau_begin = 0; if (cdonly) read_mdef(moddeffn, &mdef, &gau_begin, cb2mllr); fprintf(stderr,"\n"); E_INFO("Adapt mean values.\n"); mllr_transform_mean(wt_mean, NULL, 0, n_mgau, n_feat, n_density, veclen, A, B, cb2mllr, n_mllr_class); /*----- 7. Write to outmeanfn -----*/ fprintf(stderr,"\n"); if (s3gaucnt_write(outgaufn, wt_mean, wt_var, pass2var, dnom, n_mgau, n_feat, n_density, veclen) != S3_SUCCESS) { E_FATAL("Unable to write Gaussian counts to %s\n",outgaufn); } return S3_SUCCESS; } int main(int argc, char *argv[]) { const char *outmeanfn, *inmeanfn; const char *outgaufn, *ingaufn; const char *mllrmatfn, *cb2mllrfn, *moddeffn; uint32 cdonly, inverse; printf("----- Compiled on %s, %s\n\n",__DATE__,__TIME__); if (initialize(argc, argv) != S3_SUCCESS) { E_ERROR("Errors initializing.\n"); return 0; } outmeanfn = (const char *)cmd_ln_access("-outmeanfn"); inmeanfn = (const char *)cmd_ln_access("-inmeanfn"); outgaufn = (const char *)cmd_ln_access("-outgaucntfn"); ingaufn = (const char *)cmd_ln_access("-ingaucntfn"); mllrmatfn = (const char *)cmd_ln_access("-mllrmat"); cb2mllrfn = (const char *)cmd_ln_access("-cb2mllrfn"); moddeffn = (const char *)cmd_ln_access("-moddeffn"); cdonly = cmd_ln_int32("-cdonly"); inverse = cmd_ln_int32("-inverse"); if (! (mllrmatfn && cb2mllrfn)) { E_FATAL("You must specify all mllr files\n"); } if (outmeanfn) { if (mllr_adapt_mean(outmeanfn, inmeanfn, mllrmatfn, cb2mllrfn, moddeffn, cdonly, inverse) == S3_SUCCESS) { E_INFO("mllr_adapt finished successfully.\n"); return(0); } else { E_FATAL("Error in mllr_adapt_mean().\n"); return (1); } } else if (outgaufn) { if (mllr_adapt_gaucnt(outgaufn, ingaufn, mllrmatfn, cb2mllrfn, moddeffn, cdonly, inverse) == S3_SUCCESS) { E_INFO("mllr_adapt finished successfully.\n"); return(0); } else { E_FATAL("Error in mllr_adapt_mean().\n"); return (1); } } else { E_FATAL("No -outmeanfn or -outgaucntfn given, nothing done.\n"); } return 0 ; } <file_sep>/cmudict/sphinxdict/README.txt Converted versions of cmudict; suitable as input to trainer and decoder ----------------------------------------------------------------------- [20080219] (air) [20100118] (air) updated; reflects new organization The Sphinx-compatible version of the dictionary, compiled from the corresponding version of cmudict. For human browsing, please use the uncompiled version. To produce a new version of the SPHINX dictionary see instructions in ../scripts/README Note that compilation produces two (identical) files. The generic cmudict_SPHINX_40 is for convenience: the name is not expected to change as the dictionary evolves. It is (reasonably) safe to use it in your programs and scripts. <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/conftree/PackageTree.java package edu.cmu.sphinx.tools.confdesigner.conftree; import edu.cmu.sphinx.util.props.Configurable; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /** * A component tree where the tree structure is defined by the package-structure of the class path. * * @author <NAME> */ public class PackageTree extends ConfigurableTree { public void rebuildTree() { setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); categories.clear(); //add all s4-configurables to the tree DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot(); rootNode.removeAllChildren(); for (Class<? extends Configurable> configurable : filteredConfigClasses) { String category = configurable.getPackage().getName(); if (!categories.containsKey(category)) { categories.put(category, new DefaultMutableTreeNode(category)); rootNode.add(categories.get(category)); } DefaultMutableTreeNode categoryNode = categories.get(category); categoryNode.add(new ConfigurableNode(configurable)); } for (int i = 0; i < getRowCount(); i++) expandRow(i); } } <file_sep>/SphinxTrain/src/programs/cp_parm/main.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * Copies parameters from an input file to and output file * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/s3mixw_io.h> #include <s3/s3gau_io.h> #include <s3/s3tmat_io.h> #include <s3/gauden.h> #include <s3/ckd_alloc.h> #include <s3/feat.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <stdio.h> static int rd_parm(void); static int cp_parm(void); static int wr_parm(void); static float32 ***imixw; static uint32 n_mixw_i; static float32 ***omixw; static uint32 n_mixw_o; static uint32 n_stream; static uint32 n_density; static vector_t ***igau; static vector_t ****igau_full; static uint32 n_cb_i; static vector_t ***ogau; static vector_t ****ogau_full; static uint32 n_cb_o; static const uint32 *veclen; static float32 ***itmat; static uint32 n_tmat_i; static float32 ***otmat; static uint32 n_tmat_o; static uint32 n_state_pm; int rd_mixw(const char *fn, uint32 n_o) { if (s3mixw_read(fn, &imixw, &n_mixw_i, &n_stream, &n_density) != S3_SUCCESS) return S3_ERROR; n_mixw_o = n_o; omixw = (float32 ***)ckd_calloc_3d(n_mixw_o, n_stream, n_density, sizeof(float32)); return S3_SUCCESS; } int cp_mixw(uint32 o, uint32 i) { uint32 j, k; printf("mixw %u <= %u\n", o, i); for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { omixw[o][j][k] = imixw[i][j][k]; } } return S3_SUCCESS; } int wr_mixw(const char *fn) { if (s3mixw_write(fn, omixw, n_mixw_o, n_stream, n_density) != S3_SUCCESS) return S3_ERROR; ckd_free_3d((void ***)omixw); ckd_free_3d((void ***)imixw); return S3_SUCCESS; } int rd_tmat(const char *fn, uint32 n_o) { if (s3tmat_read(fn, &itmat, &n_tmat_i, &n_state_pm) != S3_SUCCESS) return S3_ERROR; n_tmat_o = n_o; otmat = (float32 ***)ckd_calloc_3d(n_tmat_o, n_state_pm-1, n_state_pm, sizeof(float32)); return S3_SUCCESS; } int cp_tmat(uint32 o, uint32 i) { uint32 j, k; printf("tmat %u <= %u\n", o, i); for (j = 0; j < n_state_pm-1; j++) { for (k = 0; k < n_state_pm; k++) { otmat[o][j][k] = itmat[i][j][k]; } } return S3_SUCCESS; } int wr_tmat(const char *fn) { if (s3tmat_write(fn, otmat, n_tmat_o, n_state_pm) != S3_SUCCESS) return S3_ERROR; ckd_free_3d((void ***)otmat); ckd_free_3d((void ***)itmat); return S3_SUCCESS; } int rd_gau(const char *fn, uint32 n_o) { if (s3gau_read(fn, &igau, &n_cb_i, &n_stream, &n_density, &veclen) != S3_SUCCESS) return S3_ERROR; n_cb_o = n_o; ogau = (vector_t ***)gauden_alloc_param(n_cb_o, n_stream, n_density, veclen); return S3_SUCCESS; } int cp_gau(uint32 o, uint32 i) { uint32 j, k, l; printf("gau %u <= %u\n", o, i); for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { for (l = 0; l < veclen[j]; l++) { ogau[o][j][k][l] = igau[i][j][k][l]; } } } return S3_SUCCESS; } int wr_gau(const char *fn) { if (s3gau_write(fn, (const vector_t ***)ogau, n_cb_o, n_stream, n_density, veclen) != S3_SUCCESS) return S3_ERROR; gauden_free_param(ogau); gauden_free_param(igau); return S3_SUCCESS; } int rd_gau_full(const char *fn, uint32 n_o) { if (s3gau_read_full(fn, &igau_full, &n_cb_i, &n_stream, &n_density, &veclen) != S3_SUCCESS) return S3_ERROR; n_cb_o = n_o; ogau_full = (vector_t ****)gauden_alloc_param_full(n_cb_o, n_stream, n_density, veclen); return S3_SUCCESS; } int cp_gau_full(uint32 o, uint32 i) { uint32 j, k, l, ll; printf("gau %u <= %u\n", o, i); for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { for (l = 0; l < veclen[j]; l++) { for (ll = 0; ll < veclen[j]; ll++) { ogau_full[o][j][k][l][ll] = igau_full[i][j][k][l][ll]; } } } } return S3_SUCCESS; } int wr_gau_full(const char *fn) { if (s3gau_write_full(fn, (const vector_t ****)ogau_full, n_cb_o, n_stream, n_density, veclen) != S3_SUCCESS) return S3_ERROR; gauden_free_param_full(ogau_full); gauden_free_param_full(igau_full); return S3_SUCCESS; } static int rd_parm() { if(cmd_ln_access("-imixwfn") ==NULL&& cmd_ln_access("-igaufn") ==NULL&& cmd_ln_access("-ifullgaufn")==NULL&& cmd_ln_access("-itmatfn") ==NULL ) { E_INFO("Please specify one of the following: -imixwfn, -igaufn, -ifullgaufn, -itmatfn\n"); return S3_ERROR; } if (cmd_ln_access("-imixwfn")) { if(cmd_ln_access("-nmixwout")==NULL){ E_INFO("Please specify -nmixwout\n"); return S3_ERROR; } rd_mixw((const char *)cmd_ln_access("-imixwfn"), *(uint32 *)cmd_ln_access("-nmixwout")); } if (cmd_ln_access("-igaufn")) { if(cmd_ln_access("-ncbout")==NULL){ E_INFO("Please specify -ncbout\n"); return S3_ERROR; } rd_gau((const char *)cmd_ln_access("-igaufn"), *(uint32 *)cmd_ln_access("-ncbout")); } if (cmd_ln_access("-ifullgaufn")) { if(cmd_ln_access("-ncbout")==NULL){ E_INFO("Please specify -ncbout\n"); return S3_ERROR; } rd_gau_full((const char *)cmd_ln_access("-ifullgaufn"), *(uint32 *)cmd_ln_access("-ncbout")); } if (cmd_ln_access("-itmatfn")) { if(cmd_ln_access("-ntmatout")==NULL){ E_INFO("Please specify -ntmatout\n"); return S3_ERROR; } rd_tmat((const char *)cmd_ln_access("-itmatfn"), *(uint32 *)cmd_ln_access("-ntmatout")); } return S3_SUCCESS; } static int cp_parm() { FILE *fp; uint32 i, o; uint32 max=0; /* Open the file first to see whether command-line parameters match */ if(cmd_ln_access("-cpopsfn")==NULL) { E_INFO("Please specify -cpopsfn\n"); return S3_ERROR; } fp = fopen((char *)cmd_ln_access("-cpopsfn"), "r"); if (fp == NULL) { E_INFO("Unable to open cpops file\n"); return S3_ERROR; } while (fscanf(fp, "%u %u", &o, &i) == 2) { if(o+1>max) { max=o+1; } } if (omixw) { if(max != n_mixw_o) { E_INFO("Mismatch between cp operation file (max out %d) and -nmixout (%d)\n",max, n_mixw_o); return S3_ERROR; } } if (ogau) { if(max != n_cb_o) { E_INFO("Mismatch between cp operation file (max out %d) and -ncbout (%d)\n",max, n_cb_o); return S3_ERROR; } } if (ogau_full) { if(max != n_cb_o) { E_INFO("Mismatch between cp operation file (max out %d) and -ncbout (%d)\n",max, n_cb_o); return S3_ERROR; } } if (otmat) { if(max != n_tmat_o) { E_INFO("Mismatch between cp operation file (max out %d) and -ntmatout (%d)\n",max, n_tmat_o); return S3_ERROR; } } fclose(fp); fp = fopen((char *)cmd_ln_access("-cpopsfn"), "r"); while (fscanf(fp, "%u %u", &o, &i) == 2) { if (omixw) { cp_mixw(o, i); } if (ogau) { cp_gau(o, i); } if (ogau_full) { cp_gau_full(o, i); } if (otmat) { cp_tmat(o, i); } } fclose(fp); return S3_SUCCESS; } static int wr_parm() { if (omixw) { if(cmd_ln_access("-omixwfn") == NULL) { E_INFO("Please specify -omixwfn\n"); return S3_ERROR; } wr_mixw((const char *)cmd_ln_access("-omixwfn")); } if (ogau) { if(cmd_ln_access("-ogaufn") == NULL) { E_INFO("Please specify -ogaufn\n"); return S3_ERROR; } wr_gau((const char *)cmd_ln_access("-ogaufn")); } if (ogau_full) { if(cmd_ln_access("-ofullgaufn") == NULL) { E_INFO("Please specify -ofullgaufn\n"); return S3_ERROR; } wr_gau_full((const char *)cmd_ln_access("-ofullgaufn")); } if (otmat) { if(cmd_ln_access("-otmatfn") == NULL) { E_INFO("Please specify -otmatfn\n"); return S3_ERROR; } wr_tmat((const char *)cmd_ln_access("-otmatfn")); } return S3_SUCCESS; } int main(int argc, char *argv[]) { parse_cmd_ln(argc, argv); if(rd_parm()==S3_ERROR) { E_FATAL("Problem in reading input parameters.\n"); } if(cp_parm()==S3_ERROR) { E_FATAL("Problem in copying parameters.\n"); } if(wr_parm()==S3_ERROR) { E_FATAL("Problem in writing output parameters.\n"); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:17 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/bw/main.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * This is the top level routine for SPHINX-III Baum-Welch * reestimation. * * Author: * <NAME> (<EMAIL>) 20-Jun-95 * *********************************************************************/ #include "train_cmd_ln.h" #include "forward.h" #include "viterbi.h" #include "next_utt_states.h" #include "baum_welch.h" #include "accum.h" /* The SPHINX-III common library */ #include <s3/common.h> #include <s3/prefetch.h> #include <s3/profile.h> #include <s3/ckd_alloc.h> #include <s3/get_host_name.h> #include <s3/mk_wordlist.h> #include <s3/mk_phone_list.h> #include <s3/cvt2triphone.h> #include <s3/mk_sseq.h> #include <s3/mk_trans_seq.h> #include <s3/silcomp.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3ts2cb_io.h> #include <s3/mllr.h> #include <s3/mllr_io.h> #include <s3/ts2cb.h> #include <s3/lda.h> #include <s3/s3cb2mllr_io.h> #include <s3/feat.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <sys_compat/misc.h> #include <sys_compat/time.h> #include <sys_compat/file.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #define DUMP_RETRY_PERIOD 3 /* If a count dump fails, retry every # of sec's */ /* FIXME: Should go in libutil */ static char * string_join(const char *base, ...) { va_list args; size_t len; const char *c; char *out; va_start(args, base); len = strlen(base); while ((c = va_arg(args, const char *)) != NULL) { len += strlen(c); } len++; va_end(args); out = ckd_calloc(len, 1); va_start(args, base); strcpy(out, base); while ((c = va_arg(args, const char *)) != NULL) { strcat(out, c); } va_end(args); return out; } /********************************************************************* * * Function: * main_initialize * * Description: * Construct data structures and precompute values necessary * for Baum-Welch reestimation. * * Function Inputs: * - argc * The number of command line arguments * - argv * Array of command line argument strings * - out_inv * The model inventory data structure created * by this routine. (see libmodinv/modinv.c) * - lex * A word -> phone dictionary for the training set. * * Global Inputs: * None * * Return Values: * - S3_SUCCESS * This value is returned when no error condition * has been detected. * - S3_ERROR * This value is returned when an error condition * has been detected. * * Global Outputs: * None * * Errors: * * Pre-Conditions: * * Post-Conditions: * *********************************************************************/ static int main_initialize(int argc, char *argv[], model_inventory_t **out_inv, lexicon_t **out_lex, model_def_t **out_mdef) { model_inventory_t *inv; /* the model inventory */ lexicon_t *lex; /* the lexicon to be returned to the caller */ model_def_t *mdef; uint32 n_map; uint32 n_ts; uint32 n_cb; uint32 n_mllr; int mixw_reest; int tmat_reest; int mean_reest; int var_reest; int sil_del; int did_restore = FALSE; const char *fn; char* silence_str; /* dhuggins@cs, 2006-08: Note these are forward transforms for use in training. The inverse transform of the accumulators is now done externally by mllr_transform. */ float32 ****sxfrm_a = NULL; float32 ***sxfrm_b = NULL; int32 *mllr_idx = NULL; const char *hmmdir; char *mdeffn, *meanfn, *varfn, *mixwfn, *tmatfn, *fdictfn; E_INFO("Compiled on %s at %s\n", __DATE__, __TIME__); /* define, parse and (partially) validate the command line */ train_cmd_ln_parse(argc, argv); if (cmd_ln_access("-feat") != NULL) { feat_set(cmd_ln_str("-feat")); feat_set_in_veclen(cmd_ln_int32("-ceplen")); feat_set_subvecs(cmd_ln_str("-svspec")); } else { E_FATAL("You need to set a feature extraction config using -feat\n"); } if (cmd_ln_access("-ceplen") == NULL) { E_FATAL("Input vector length must be specified\n"); } feat_set_in_veclen(cmd_ln_int32("-ceplen")); if (cmd_ln_access("-ldafn") != NULL) { if (cmd_ln_boolean("-ldaaccum")) { /* If -ldaaccum is set, we will not apply LDA until we accumulate, so read it in later. */ } else { /* Otherwise we load it into the feature computation so it * applies globally. */ if (feat_read_lda(cmd_ln_access("-ldafn"), cmd_ln_int32("-ldadim"))) { E_FATAL("Failed to read LDA matrix\n"); } } } /* create a new model inventory structure */ *out_inv = inv = mod_inv_new(); mod_inv_set_n_feat(inv, feat_n_stream()); mdeffn = cmd_ln_str("-moddeffn"); meanfn = cmd_ln_str("-meanfn"); varfn = cmd_ln_str("-varfn"); mixwfn = cmd_ln_str("-mixwfn"); tmatfn = cmd_ln_str("-tmatfn"); fdictfn = cmd_ln_str("-fdictfn"); /* Note: this will leak a small amount of memory but we really * don't care. */ if ((hmmdir = cmd_ln_str("-hmmdir")) != NULL) { if (mdeffn == NULL) mdeffn = string_join(hmmdir, "/mdef", NULL); if (meanfn == NULL) meanfn = string_join(hmmdir, "/means", NULL); if (varfn == NULL) varfn = string_join(hmmdir, "/variances", NULL); if (mixwfn == NULL) mixwfn = string_join(hmmdir, "/mixture_weights", NULL); if (tmatfn == NULL) tmatfn = string_join(hmmdir, "/transition_matrices", NULL); if (fdictfn == NULL) fdictfn = string_join(hmmdir, "/noisedict", NULL); } E_INFO("Reading %s\n", mdeffn); /* Read in the model definitions. Defines the set of CI phones and context dependent phones. Defines the transition matrix tying and state level tying. */ if (model_def_read(&mdef, mdeffn) != S3_SUCCESS) { return S3_ERROR; } *out_mdef = mdef; fn = cmd_ln_access("-ts2cbfn"); if (fn == NULL) { E_FATAL("Specify -ts2cbfn\n"); } if (strcmp(fn, SEMI_LABEL) == 0) { mdef->cb = semi_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; n_cb = 1; } else if (strcmp(fn, CONT_LABEL) == 0) { mdef->cb = cont_ts2cb(mdef->n_tied_state); n_ts = mdef->n_tied_state; n_cb = mdef->n_tied_state; } else if (strcmp(fn, PTM_LABEL) == 0) { mdef->cb = ptm_ts2cb(mdef); n_ts = mdef->n_tied_state; n_cb = mdef->acmod_set->n_ci; } else if (s3ts2cb_read(fn, &mdef->cb, &n_ts, &n_cb) != S3_SUCCESS) { return S3_ERROR; } inv->acmod_set = mdef->acmod_set; inv->mdef = mdef; if (mod_inv_read_mixw(inv, mdef, mixwfn, *(float32 *)cmd_ln_access("-mwfloor")) != S3_SUCCESS) return S3_ERROR; if (n_ts != inv->n_mixw) { E_WARN("%u mappings from tied-state to cb, but %u tied-state in %s\n", mdef->n_cb, inv->n_mixw, mixwfn); } if (mod_inv_read_tmat(inv, tmatfn, *(float32 *)cmd_ln_access("-tpfloor")) != S3_SUCCESS) return S3_ERROR; if (mod_inv_read_gauden(inv, meanfn, varfn, *(float32 *)cmd_ln_access("-varfloor"), *(int32 *)cmd_ln_access("-topn"), cmd_ln_int32("-fullvar")) != S3_SUCCESS) { if (!cmd_ln_int32("-fullvar")) { return S3_ERROR; } else { /* If reading full variances failed, try reading * them as diagonal variances (allows us to * initialize full vars from diagonal ones) */ if (mod_inv_read_gauden(inv, meanfn, varfn, *(float32 *)cmd_ln_access("-varfloor"), *(int32 *)cmd_ln_access("-topn"), FALSE) != S3_SUCCESS) { return S3_ERROR; } } } /* If we want to use diagonals only, and we didn't read diagonals * above, then we have to extract them here. */ if (cmd_ln_int32("-diagfull") && inv->gauden->var == NULL) { /* Extract diagonals and use them for Gaussian computation. */ gauden_t *g; uint32 i, j, k, l; g = inv->gauden; g->var = gauden_alloc_param(g->n_mgau, g->n_feat, g->n_density, g->veclen); for (i = 0; i < g->n_mgau; ++i) for (j = 0; j < g->n_feat; ++j) for (k = 0; k < g->n_density; ++k) for (l = 0; l < g->veclen[j]; ++l) g->var[i][j][k][l] = g->fullvar[i][j][k][l][l]; gauden_free_param_full(g->fullvar); g->fullvar = NULL; gauden_floor_variance(g); } if (gauden_eval_precomp(inv->gauden) != S3_SUCCESS) { E_ERROR("Problems precomputing values used during Gaussian density evaluation\n"); return S3_ERROR; } if (inv->gauden->n_mgau != n_cb) { printf("# of codebooks in mean/var files, %u, inconsistent with ts2cb mapping %u\n", inv->gauden->n_mgau, n_cb); } mixw_reest = *(int32 *)cmd_ln_access("-mixwreest"); mean_reest = *(int32 *)cmd_ln_access("-meanreest"); var_reest = *(int32 *)cmd_ln_access("-varreest"); tmat_reest = *(int32 *)cmd_ln_access("-tmatreest"); sil_del = *(int32 *)cmd_ln_access("-sildel"); E_INFO("Will %sreestimate mixing weights.\n", (mixw_reest ? "" : "NOT ")); E_INFO("Will %sreestimate means.\n", (mean_reest ? "" : "NOT ")); E_INFO("Will %sreestimate variances.\n", (var_reest ? "" : "NOT ")); E_INFO("WIll %soptionally delete silence in Baum Welch or Viterbi. \n", (sil_del ? "" : "NOT ")); if (*(int32 *)cmd_ln_access("-mixwreest")) { if (mod_inv_alloc_mixw_acc(inv) != S3_SUCCESS) return S3_ERROR; } E_INFO("Will %sreestimate transition matrices\n", (*(int32 *)cmd_ln_access("-tmatreest") ? "" : "NOT ")); if (*(int32 *)cmd_ln_access("-tmatreest")) { if (mod_inv_alloc_tmat_acc(inv) != S3_SUCCESS) return S3_ERROR; } if (*(int32 *)cmd_ln_access("-meanreest") || *(int32 *)cmd_ln_access("-varreest")) { if (mod_inv_alloc_gauden_acc(inv) != S3_SUCCESS) return S3_ERROR; } E_INFO("Reading main lexicon: %s\n", cmd_ln_access("-dictfn")); lex = lexicon_read(NULL, cmd_ln_access("-dictfn"), mdef->acmod_set); if (lex == NULL) return S3_ERROR; if (cmd_ln_int32("-ltsoov")) lex->lts_rules = (lts_t *)&cmu6_lts_rules; if (fdictfn) { E_INFO("Reading filler lexicon: %s\n", fdictfn); (void)lexicon_read(lex, fdictfn, mdef->acmod_set); } *out_lex = lex; /* * Configure corpus module (controls sequencing/access of per utterance data) */ /* set the data directory and extension for cepstrum files */ corpus_set_mfcc_dir(cmd_ln_access("-cepdir")); corpus_set_mfcc_ext(cmd_ln_access("-cepext")); /* The parameter required for re-estimation routines*/ silence_str = (char *)cmd_ln_access("-siltag"); E_INFO("Silence Tag %s\n",silence_str); if (cmd_ln_access("-lsnfn")) { /* use a LSN file which has all the transcripts */ corpus_set_lsn_filename(cmd_ln_access("-lsnfn")); } else { /* set the data directory and extension for word transcript files */ corpus_set_sent_dir(cmd_ln_access("-sentdir")); corpus_set_sent_ext(cmd_ln_access("-sentext")); } if (cmd_ln_access("-ctlfn")) { corpus_set_ctl_filename(cmd_ln_access("-ctlfn")); } if (cmd_ln_access("-sildelfn")) { corpus_set_sildel_filename((const char *)cmd_ln_access("-sildelfn")); } if (cmd_ln_access("-phsegdir")) { corpus_set_phseg_dir(cmd_ln_access("-phsegdir")); corpus_set_phseg_ext(cmd_ln_access("-phsegext")); } if (cmd_ln_access("-accumdir")) { char fn[MAXPATHLEN+1]; FILE *fp; sprintf(fn, "%s/ckpt", (const char *)cmd_ln_access("-accumdir")); fp = fopen(fn, "r"); if (fp != NULL) { fclose(fp); E_INFO("RESTORING CHECKPOINTED COUNTS IN %s\n", cmd_ln_access("-accumdir")); if (mod_inv_restore_acc(inv, (const char *)cmd_ln_access("-accumdir"), mixw_reest, mean_reest, var_reest, tmat_reest) != S3_SUCCESS) { E_FATAL("Unable to restore checkpoint information\n"); } if (corpus_ckpt_set_interval(fn) != S3_SUCCESS) { E_FATAL("Unable to restore corpus state information\n"); } E_INFO("Resuming at utt %u\n", corpus_get_begin()); did_restore = TRUE; } } if (!did_restore) { if (cmd_ln_access("-part") && cmd_ln_access("-npart")) { corpus_set_partition(*(uint32 *)cmd_ln_access("-part"), *(uint32 *)cmd_ln_access("-npart")); } else if (cmd_ln_access("-nskip") && cmd_ln_access("-runlen")) { corpus_set_interval(*(uint32 *)cmd_ln_access("-nskip"), *(uint32 *)cmd_ln_access("-runlen")); } } /* BEWARE: this function call must be done after all the other corpus configuration */ corpus_init(); if (cmd_ln_access("-mllrmat")) { const uint32 *tmp_veclen, *feat_veclen; uint32 tmp_n_mllrcls; uint32 tmp_n_stream; uint32 j; if (read_reg_mat(cmd_ln_access("-mllrmat"), &tmp_veclen, &tmp_n_mllrcls, &tmp_n_stream, &sxfrm_a, &sxfrm_b) != S3_SUCCESS) { E_FATAL("Unable to read %s\n", cmd_ln_access("-mllrmat")); } if (feat_n_stream() != tmp_n_stream) { E_FATAL("# feature streams in -mllrmat %s != # feature streams configured on cmd ln\n"); } feat_veclen = feat_vecsize(); for (j = 0; j < tmp_n_stream; j++) { if (feat_veclen[j] != tmp_veclen[j]) { E_FATAL("# components of stream %u in -mllrmat inconsistent w/ -feat config (%u != %u)\n", j, tmp_veclen[j], feat_veclen[j]); } } ckd_free((void *)tmp_veclen); fn = cmd_ln_access("-cb2mllrfn"); if (fn != NULL) { if (strcmp(fn, ".1cls.") == 0) { mllr_idx = ckd_calloc(inv->gauden->n_mgau, sizeof(int32)); n_mllr = 1; n_map = inv->gauden->n_mgau; } else if (s3cb2mllr_read((const char *)cmd_ln_access("-cb2mllrfn"), &mllr_idx, &n_map, &n_mllr) != S3_SUCCESS) { return S3_ERROR; } if (n_map != inv->gauden->n_mgau) { E_FATAL("cb2mllr maps %u cb, but read %u cb from files\n", n_map, inv->gauden->n_mgau); } } /* Transform the means using the speaker transform if available. */ mllr_transform_mean(inv->gauden->mean, inv->gauden->var, 0, inv->gauden->n_mgau, inv->gauden->n_feat, inv->gauden->n_density, inv->gauden->veclen, sxfrm_a, sxfrm_b, mllr_idx, n_mllr); ckd_free(mllr_idx); free_mllr_A(sxfrm_a, n_mllr, tmp_n_stream); free_mllr_B(sxfrm_b, n_mllr, tmp_n_stream); } return S3_SUCCESS; } void main_reestimate(model_inventory_t *inv, lexicon_t *lex, model_def_t *mdef, int32 viterbi) { vector_t *mfcc; /* utterance cepstra */ uint32 n_frame; /* # of cepstrum frames */ uint32 svd_n_frame; /* # of cepstrum frames */ uint32 mfc_veclen; /* # of MFC coefficients per frame */ vector_t **f; /* independent feature streams derived * from cepstra */ state_t *state_seq; /* sentence HMM state sequence for the utterance */ float32 ***lda = NULL; uint32 n_lda = 0, m, n; uint32 n_state = 0; /* # of sentence HMM states */ float64 total_log_lik; /* total log liklihood over corpus */ float64 log_lik; /* log liklihood for an utterance */ uint32 total_frames; /* # of frames over the corpus */ float64 a_beam; /* alpha pruning beam */ float64 b_beam; /* beta pruning beam */ float32 spthresh; /* state posterior probability threshold */ uint32 seq_no; /* sequence # of utterance in corpus */ uint32 mixw_reest; /* if TRUE, reestimate mixing weights */ uint32 tmat_reest; /* if TRUE, reestimate transition probability matrices */ uint32 mean_reest; /* if TRUE, reestimate means */ uint32 var_reest; /* if TRUE, reestimate variances */ uint32 sil_del; /* if TRUE optionally delete silence at the end */ char *trans; char* silence_str; char *pdumpdir; FILE *pdumpfh; uint32 in_veclen; timing_t *utt_timer = NULL; timing_t *upd_timer = NULL; timing_t *fwd_timer = NULL; timing_t *bwd_timer = NULL; timing_t *gau_timer = NULL; timing_t *rsts_timer = NULL; timing_t *rstf_timer = NULL; timing_t *rstu_timer = NULL; int32 profile; int32 pass2var; int32 var_is_full; uint32 n_utt; uint32 *del_sf; uint32 *del_ef; uint32 n_del; s3phseg_t *phseg = NULL; uint32 maxuttlen; uint32 n_frame_skipped = 0; uint32 ckpt_intv = 0; uint32 no_retries=0; uint32 outputfullpath=0; uint32 fullsuffixmatch=0; E_INFO("Reestimation: %s\n", (viterbi ? "Viterbi" : "Baum-Welch")); profile = *(int32 *)cmd_ln_access("-timing"); if (profile) { E_INFO("Generating profiling information consumes significant CPU resources.\n"); E_INFO("If you are not interested in profiling, use -timing no\n"); } outputfullpath = *(int32 *)cmd_ln_access("-outputfullpath"); fullsuffixmatch = *(int32 *)cmd_ln_access("-fullsuffixmatch"); corpus_set_full_suffix_match(fullsuffixmatch); if (profile) { utt_timer = timing_new(); upd_timer = timing_new(); fwd_timer = timing_new(); bwd_timer = timing_new(); gau_timer = timing_new(); rsts_timer = timing_new(); rstf_timer = timing_new(); rstu_timer = timing_new(); /* bind some timers to names so that lower level routines * can get at them easily */ timing_bind_name("fwd", fwd_timer); timing_bind_name("bwd", bwd_timer); timing_bind_name("gau", gau_timer); timing_bind_name("rsts", rsts_timer); timing_bind_name("rstf", rstf_timer); timing_bind_name("rstu", rstu_timer); } mixw_reest = *(int32 *)cmd_ln_access("-mixwreest"); tmat_reest = *(int32 *)cmd_ln_access("-tmatreest"); mean_reest = *(int32 *)cmd_ln_access("-meanreest"); var_reest = *(int32 *)cmd_ln_access("-varreest"); pass2var = *(int32 *)cmd_ln_access("-2passvar"); var_is_full = *(int32 *)cmd_ln_access("-fullvar"); sil_del = *(int32 *)cmd_ln_access("-sildel"); silence_str = (char *)cmd_ln_access("-siltag"); pdumpdir = (char *)cmd_ln_access("-pdumpdir"); in_veclen = cmd_ln_int32("-ceplen"); if (cmd_ln_access("-ldafn") && cmd_ln_boolean("-ldaaccum")) { /* Read in an LDA matrix for accumulation. */ lda = lda_read(cmd_ln_access("-ldafn"), &n_lda, &m, &n); } if (cmd_ln_access("-ckptintv")) { ckpt_intv = *(int32 *)cmd_ln_access("-ckptintv"); } if (cmd_ln_access("-accumdir") == NULL) { E_WARN("NO ACCUMDIR SET. No counts will be written; assuming debug\n"); } if (!mixw_reest && !tmat_reest && !mean_reest && !var_reest) { E_WARN("No reestimation specified! None done.\n"); return; } total_log_lik = 0; total_frames = 0; a_beam = *(float64 *)cmd_ln_access("-abeam"); b_beam = *(float64 *)cmd_ln_access("-bbeam"); spthresh = *(float32 *)cmd_ln_access("-spthresh"); maxuttlen = *(int32 *)cmd_ln_access("-maxuttlen"); /* Begin by skipping over some (possibly zero) # of utterances. * Continue to process utterances until there are no more (either EOF * or end of run). */ seq_no = corpus_get_begin(); printf("column defns\n"); printf("\t<seq>\n"); printf("\t<id>\n"); printf("\t<n_frame_in>\n"); printf("\t<n_frame_del>\n"); printf("\t<n_state_shmm>\n"); printf("\t<avg_states_alpha>\n"); if (!cmd_ln_int32("-viterbi")) { printf("\t<avg_states_beta>\n"); printf("\t<avg_states_reest>\n"); printf("\t<avg_posterior_prune>\n"); } printf("\t<frame_log_lik>\n"); printf("\t<utt_log_lik>\n"); printf("\t... timing info ... \n"); n_utt = 0; while (corpus_next_utt()) { /* Zero timers before utt processing begins */ if (utt_timer) { timing_reset(utt_timer); } if (upd_timer) { timing_reset(upd_timer); } if (fwd_timer) { timing_reset(fwd_timer); } if (bwd_timer) { timing_reset(bwd_timer); } if (gau_timer) { timing_reset(gau_timer); } if (rsts_timer) { timing_reset(rsts_timer); } if (rstf_timer) { timing_reset(rstf_timer); } if (rstu_timer) { timing_reset(rstu_timer); } if (utt_timer) { timing_start(utt_timer); } printf("utt> %5u %25s", seq_no, (outputfullpath ? corpus_utt_full_name() : corpus_utt())); /* get the MFCC data for the utterance */ /* CHANGE BY BHIKSHA; IF INPUT VECLEN != 13, THEN DO NOT USE THE REGULAR corpus_get_mfcc() WHICH REQUIRES INPUT DATA TO BE 13 DIMENSIONAL CEPSTRA. USE, INSTEAD, THE HACKED VERSION corpus_get_generic_featurevec() WHICH TAKES FEATURES OF ARBITRARY LENGTH 7 JAN 1998 */ if (in_veclen == S2_CEP_VECLEN) { if (corpus_get_mfcc(&mfcc, &n_frame, &mfc_veclen) < 0) { E_FATAL("Can't read input features\n"); } assert(mfc_veclen == in_veclen); } else { if (corpus_get_generic_featurevec(&mfcc, &n_frame, in_veclen) < 0) { E_FATAL("Can't read input features\n"); } } /* END CHANGES BY BHIKSHA */ printf(" %4u", n_frame); if (n_frame < 9) { E_WARN("utt %s too short\n", corpus_utt()); if (mfcc) { ckd_free(mfcc[0]); ckd_free(mfcc); } continue; } if ((maxuttlen > 0) && (n_frame > maxuttlen)) { E_INFO("utt # frames > -maxuttlen; skipping\n"); n_frame_skipped += n_frame; if (mfcc) { ckd_free(mfcc[0]); ckd_free(mfcc); } continue; } corpus_get_sildel(&del_sf, &del_ef, &n_del); silcomp_set_del_seg(del_sf, del_ef, n_del); svd_n_frame = n_frame; /* compute feature vectors from the MFCC data */ f = feat_compute(mfcc, &n_frame); printf(" %4u", n_frame - svd_n_frame); /* Get the transcript */ corpus_get_sent(&trans); /* Get the phone segmentation */ corpus_get_phseg(inv->acmod_set, &phseg); /* Open a dump file if required. */ if (pdumpdir) { char *pdumpfn, *uttid; uttid = (outputfullpath ? corpus_utt_full_name() : corpus_utt()); pdumpfn = ckd_calloc(strlen(pdumpdir) + 1 + strlen(uttid) + strlen(".pdump") + 1, 1); strcpy(pdumpfn, pdumpdir); strcat(pdumpfn, "/"); strcat(pdumpfn, uttid); strcat(pdumpfn, ".pdump"); if ((pdumpfh = fopen(pdumpfn, "w")) == NULL) E_FATAL_SYSTEM("Failed to open %s for wrigint", pdumpfn); ckd_free(pdumpfn); } else pdumpfh = NULL; if (upd_timer) timing_start(upd_timer); /* create a sentence HMM */ state_seq = next_utt_states(&n_state, lex, inv, mdef, trans, sil_del, silence_str); printf(" %5u", n_state); if (!viterbi) { /* accumulate reestimation sums for the utterance */ if (baum_welch_update(&log_lik, f, n_frame, state_seq, n_state, inv, a_beam, b_beam, spthresh, phseg, mixw_reest, tmat_reest, mean_reest, var_reest, pass2var, var_is_full, pdumpfh, lda) == S3_SUCCESS) { total_frames += n_frame; total_log_lik += log_lik; printf(" %e %e", (n_frame > 0 ? log_lik / n_frame : 0.0), log_lik); } } else { /* Viterbi search and accumulate in it */ if (viterbi_update(&log_lik, f, n_frame, state_seq, n_state, inv, a_beam, spthresh, phseg, mixw_reest, tmat_reest, mean_reest, var_reest, pass2var, var_is_full, pdumpfh, lda) == S3_SUCCESS) { total_frames += n_frame; total_log_lik += log_lik; printf(" %e %e", (n_frame > 0 ? log_lik / n_frame : 0.0), log_lik); } } if (upd_timer) timing_stop(upd_timer); if (pdumpfh) fclose(pdumpfh); free(mfcc[0]); ckd_free(mfcc); feat_free(f); free(trans); /* alloc'ed using strdup() */ seq_no++; if (utt_timer) timing_stop(utt_timer); if (profile) { printf(" utt %4.3fx %4.3fe" " upd %4.3fx %4.3fe" " fwd %4.3fx %4.3fe" " bwd %4.3fx %4.3fe" " gau %4.3fx %4.3fe" " rsts %4.3fx %4.3fe" " rstf %4.3fx %4.3fe" " rstu %4.3fx %4.3fe", utt_timer->t_cpu/(n_frame*0.01), (utt_timer->t_cpu > 0 ? utt_timer->t_elapsed / utt_timer->t_cpu : 0.0), upd_timer->t_cpu/(n_frame*0.01), (upd_timer->t_cpu > 0 ? upd_timer->t_elapsed / upd_timer->t_cpu : 0.0), fwd_timer->t_cpu/(n_frame*0.01), (fwd_timer->t_cpu > 0 ? fwd_timer->t_elapsed / fwd_timer->t_cpu : 0.0), bwd_timer->t_cpu/(n_frame*0.01), (bwd_timer->t_cpu > 0 ? bwd_timer->t_elapsed / bwd_timer->t_cpu : 0.0), gau_timer->t_cpu/(n_frame*0.01), (gau_timer->t_cpu > 0 ? gau_timer->t_elapsed / gau_timer->t_cpu : 0.0), rsts_timer->t_cpu/(n_frame*0.01), (rsts_timer->t_cpu > 0 ? rsts_timer->t_elapsed / rsts_timer->t_cpu : 0.0), rstf_timer->t_cpu/(n_frame*0.01), (rstf_timer->t_cpu > 0 ? rstf_timer->t_elapsed / rstf_timer->t_cpu : 0.0), rstu_timer->t_cpu/(n_frame*0.01), (rstu_timer->t_cpu > 0 ? rstu_timer->t_elapsed / rstu_timer->t_cpu : 0.0)); } printf("\n"); fflush(stdout); ++n_utt; if ((ckpt_intv > 0) && ((n_utt % ckpt_intv) == 0) && (cmd_ln_access("-accumdir") != NULL)) { while (accum_dump(cmd_ln_access("-accumdir"), inv, mixw_reest, tmat_reest, mean_reest, var_reest, pass2var, var_is_full, TRUE) != S3_SUCCESS) { static int notified = FALSE; time_t t; char time_str[64]; /* * If we were not able to dump the parameters, write one log entry * about the failure */ if (notified == FALSE) { t = time(NULL); strcpy(time_str, (const char *)ctime((const time_t *)&t)); /* nuke the newline at the end of this. */ time_str[strlen(time_str)-1] = '\0'; E_WARN("Ckpt count dump failed on %s. Retrying dump every %3.1f hour until success.\n", time_str, DUMP_RETRY_PERIOD/3600.0); notified = TRUE; no_retries++; if(no_retries>10){ E_FATAL("Failed to get the files after 10 retries(about 5 minutes).\n "); } } sleep(DUMP_RETRY_PERIOD); } } } printf("overall> %s %u (-%u) %e %e", get_host_name(), total_frames, n_frame_skipped, (total_frames > 0 ? total_log_lik / total_frames : 0.0), total_log_lik); if (profile) { printf(" %4.3fx %4.3fe", (total_frames > 0 ? utt_timer->t_tot_cpu/(total_frames*0.01) : 0.0), (utt_timer->t_tot_cpu > 0 ? utt_timer->t_tot_elapsed / utt_timer->t_tot_cpu : 0.0)); } printf("\n"); fflush(stdout); no_retries=0; /* dump the accumulators to a file system */ while (cmd_ln_access("-accumdir") != NULL && accum_dump(cmd_ln_access("-accumdir"), inv, mixw_reest, tmat_reest, mean_reest, var_reest, pass2var, var_is_full, FALSE) != S3_SUCCESS) { static int notified = FALSE; time_t t; char time_str[64]; /* * If we were not able to dump the parameters, write one log entry * about the failure */ if (notified == FALSE) { t = time(NULL); strcpy(time_str, (const char *)ctime((const time_t *)&t)); /* nuke the newline at the end of this. */ time_str[strlen(time_str)-1] = '\0'; E_WARN("Count dump failed on %s. Retrying dump every %3.1f hour until success.\n", time_str, DUMP_RETRY_PERIOD/3600.0); notified = TRUE; no_retries++; if(no_retries>10){ E_FATAL("Failed to get the files after 10 retries(about 5 minutes).\n "); } } sleep(DUMP_RETRY_PERIOD); } /* Write a log entry on success */ if (cmd_ln_access("-accumdir")) E_INFO("Counts saved to %s\n", cmd_ln_access("-accumdir")); else E_INFO("Counts NOT saved.\n"); mod_inv_free(inv); if (lda) ckd_free_3d((void ***)lda); } int main(int argc, char *argv[]) { model_inventory_t *inv; lexicon_t *lex = NULL; model_def_t *mdef = NULL; (void) prefetch_init(); /* should do this BEFORE any allocations */ if (main_initialize(argc, argv, &inv, &lex, &mdef) != S3_SUCCESS) { E_FATAL("initialization failed\n"); } main_reestimate(inv, lex, mdef, *(int32 *)cmd_ln_access("-viterbi")); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.16 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.15 2006/03/20 19:05:46 dhdfu * Add missing newlines * * Revision 1.14 2006/02/24 15:50:23 eht * Output an informational message to the log that collecting profiling * information about bw consumes significant CPU resources and suggest * using -timing no if profiling isn't needed. * * Revision 1.13 2006/02/23 22:21:29 eht * add -outputfullpath and -fullsuffixmatch arguments to bw. * * Default behavior is to keep the existing system behavior when the * corpus module tries to match the transcript utterance id with the * partial path contained in the control file. * * Using -fullsuffixmatch yes will do the following: * The corpus module will check whether the string contained * inside parentheses in the transcript for the utterances * matches the final part of the control file partial path * for the utterance. For instance, if the control file * partial path is: * tidigits/train/man/ae/243za * the following strings will be considered to match: * 243za * ae/243za * man/ae/243za * . * . * . * In any event, the utterance will be used by bw for training. * This switch just modifies when the warning message for * mismatching control file and transcripts is generated. * * Using -outputfullpath yes will output the entire subpath from the * control file in the log output of bw rather than just the final path * component. This allows for simpler automatic processing of the output * of bw. * * Revision 1.12 2005/09/27 02:02:47 arthchan2003 * Check whether utterance is too short in init_gau, bw and agg_seg. * * Revision 1.11 2005/09/15 19:36:00 dhdfu * Add (as yet untested) support for letter-to-sound rules (from CMU * Flite) when constructing sentence HMMs in Baum-Welch. Currently only * rules for CMUdict exist. Of course this is not a substitute for * actually checking pronunciations... * * Revision 1.10 2005/09/15 19:32:36 dhdfu * Another (meaningless) signedness fix * * Revision 1.9 2004/11/17 01:46:58 arthchan2003 * Change the sleeping time to be at most 30 seconds. No one will know whether the code dies or not if keep the code loop infinitely. * * Revision 1.8 2004/07/22 00:08:39 egouvea * Fixed some compilation warnings. * * Revision 1.7 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.6 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.4 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.30 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.29 1996/08/06 14:04:13 eht * Silence deletion file implementation * * Revision 1.28 1996/07/29 16:16:44 eht * Wrap up more initialization functionality into mod_inv module * - MLLR reestimation * Bunch of relatively minor changes * * Revision 1.27 1996/03/26 13:54:51 eht * - Deal w/ case of n_top > n_density in a better way * - Fix bug of float32 beams * - Deal w/ 2d MFCC data rather than the old 1d form * - Add flag to control whether timing stats are printed * - Add feature that when '-accumdir' is not specified, no * counts are written. This allows debugging runs w/o the * fear of overwriting data. A warning is printed at initialization * time that no '-accumdir' argument has been given. * * Revision 1.26 1996/03/04 15:58:36 eht * Added more CPU time counters * * Revision 1.25 1996/02/02 17:55:20 eht * *** empty log message *** * * Revision 1.24 1996/02/02 17:40:32 eht * Deal with alpha and beta beams. * * Revision 1.23 1996/01/26 18:23:49 eht * Deal w/ case when MFC file cannot be read. * Free comments w/ were not freed before. * * Revision 1.22 1995/12/15 18:37:07 eht * Added some type cases for memory alloc/free * * Revision 1.21 1995/12/14 19:47:59 eht * Added some sanity checks to prevent seg faults and weird behavior if * the user gives inconsistent input arguments. * * Revision 1.20 1995/12/01 03:58:22 eht * Fixed transcript core leak * * Revision 1.19 1995/11/30 20:46:44 eht * Added change to allow state parameter definitions to be used. * Added change to allow transition matrix reestimation to be turned off. * * Revision 1.18 1995/11/10 19:37:44 eht * Use new profile * * Revision 1.16 1995/10/18 11:18:38 eht * Include compatibility macros for Windows NT so that * sleep(x) is converted into Sleep(x * 1000) * * Revision 1.15 1995/10/17 14:02:26 eht * Changed so that would port to Windows NT * * Revision 1.14 1995/10/10 12:43:50 eht * Changed to use <s3/prim_type.h> * * Revision 1.13 1995/10/09 14:55:33 eht * Change interface to new ckd_alloc routines * * Revision 1.12 1995/10/05 12:52:17 eht * Get rid of the U Toronto malloc package statements * * Revision 1.11 95/09/14 14:19:36 14:19:36 eht (<NAME>) * Added support for U Toronto debug malloc library * * Revision 1.10 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.9 1995/09/07 18:53:03 eht * Get the seq number of the first utterance in a subcorpus * from the corpus module rather than the command line. Allows * the corpus module to figure this out. May eventually need * to call this for each utterance, but no need now. * * Revision 1.8 1995/08/29 12:25:26 eht * Updates to reflect new interface to corpus * configuration and initialization * * Revision 1.7 1995/08/24 19:58:50 eht * Merged in PWP's prefetching code * * * Revision 1.6 1995/08/24 19:49:43 eht * Upgrade to allow a single LSN file for the corpus * * Revision 1.5 1995/08/09 20:18:31 eht * Add output when mixing weight normalization fails * * Revision 1.4 1995/07/07 12:00:29 eht * Include initial mixing weights and transition probabilities * in verbose output. Also, got rid of the last vestiges of * the tying DAG. Also, added some arguments to state_seq_print * so that it could produce more informative output. * * Revision 1.3 1995/06/28 14:38:32 eht * Removed include of tying DAG header file * * Revision 1.2 1995/06/28 14:31:55 eht * Removed tying DAG creation. Now, next_utt_states() builds state seq using * tying structure in a model_def_t data structure (see libio/model_def_io.c * for details). * * Revision 1.1 1995/06/02 20:39:40 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libmisc/corpus.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * corpus.c -- Corpus-file related misc functions. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 25-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #if (_SUN4) #include <unistd.h> #endif #include <math.h> #include <libutil/libutil.h> #include "corpus.h" corpus_t *corpus_load_headid (char *file) { FILE *fp; int32 ispipe; char line[16384], wd[4096], *id; int32 k, n; corpus_t *corp; E_INFO("Loading corpus (%s)\n", file); if ((fp = fopen_compchk(file, &ispipe)) == NULL) E_FATAL_SYSTEM("fopen_compchk(%s,r) failed\n", file); corp = (corpus_t *) ckd_calloc (1, sizeof(corpus_t)); n = 0; while (fgets (line, sizeof(line), fp) != NULL) { /* Skip comment or empty lines */ if ((line[0] != '#') && (sscanf (line, "%s%n", wd, &k) == 1)) n++; } rewind (fp); corp->ht = hash_new ("corpus", n); corp->n = 0; corp->str = (char **) ckd_calloc (n, sizeof(char *)); n = 0; while (fgets (line, sizeof(line), fp) != NULL) { /* Skip comment or empty lines */ if ((line[0] == '#') || (sscanf (line, "%s%n", wd, &k) != 1)) continue; corp->str[n] = ckd_salloc (line+k); id = ckd_salloc (wd); if (hash_enter (corp->ht, id, n) < 0) E_FATAL("corpus_load(%s) failed\n", file); n++; } corp->n = n; fclose_comp (fp, ispipe); E_INFO("%d entries loaded\n", n); return corp; } char *corpus_lookup (corpus_t *corp, char *id) { int32 n; if (hash_lookup (corp->ht, id, &n) < 0) return NULL; assert ((n >= 0) && (n < corp->n)); return (corp->str[n]); } #if _CORPUS_TEST_ main (int32 argc, char *argv[]) { corpus_t *c; char id[4096], *str; if (argc != 2) E_FATAL("Usage: %s corpusfile\n", argv[0]); c = corpus_load_headid (argv[1]); for (;;) { printf ("> "); scanf ("%s", id); str = corpus_lookup (c, id); if (str == NULL) printf ("%s Not found\n"); else printf ("%s: %s\n", id, str); } } #endif <file_sep>/SphinxTrain/include/s3/model_inventory.h /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: model_inventory.h * * Description: * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #ifndef MODEL_INVENTORY_H #define MODEL_INVENTORY_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/acmod_set.h> #include <s3/gauden.h> #include <s3/prim_type.h> #include <s3/model_def.h> /* data structure definition */ typedef struct model_inventory_s { model_def_t *mdef; /* acoustic model definitions */ acmod_set_t *acmod_set; /* describes mapping of strings to id's and vice versa */ float32 ***mixw; /* mixing weight array */ float32 ***mixw_acc; /* mixing weight count accumulators */ float32 ***l_mixw_acc; /* local (per utterance) mixing weight accumulators */ uint32 n_mixw; /* number of mixing weights */ uint32 n_feat; /* number of feature streams */ uint32 n_density; /* number of densities per mixture */ uint32 *mixw_inverse; /* converts a local (to the utternace) mixing weight ID to a global one */ uint32 n_mixw_inverse; /* # of local mixing weight ID's [0..(n_mixw_inverse-1)]*/ uint32 *cb_inverse; /* local->global map for codebook ID's */ uint32 n_cb_inverse; /* # of local codebook ID's */ float32 ***tmat; /* transition probability matrices */ float32 ***tmat_acc; /* transition probability accumulators */ float32 **l_tmat_acc; /* local (per utterance) transition probability matrix */ uint32 n_tmat; /* number of transition matrices */ uint32 n_state_pm; /* number of states per model */ gauden_t *gauden; /* gaussian densities (see <s3/gauden.h>) */ } model_inventory_t; /* * Public Interface */ /* Creation */ model_inventory_t * mod_inv_new(void); /* Free the entire model inventory */ void mod_inv_free(model_inventory_t *minv); /* Setting of simple parameters */ void mod_inv_set_n_feat(model_inventory_t *minv, uint32 n_feat); void mod_inv_set_n_density(model_inventory_t *minv, uint32 n_density); /* Read routines */ int32 mod_inv_read_gauden(model_inventory_t *minv, const char *meanfn, const char *varfn, float32 varfloor, uint32 n_top, int32 var_is_full); int32 mod_inv_read_tmat(model_inventory_t *minv, const char *fn, float32 floor); int32 mod_inv_read_mixw(model_inventory_t *minv, const model_def_t *mdef, const char *fn, float32 floor); /* Allocation of reestimation accumulators */ int32 mod_inv_alloc_gauden_acc(model_inventory_t *minv); int32 mod_inv_alloc_tmat_acc(model_inventory_t *minv); int32 mod_inv_alloc_mixw_acc(model_inventory_t *minv); int mod_inv_restore_acc(model_inventory_t *minv, const char *accumdir, int mixw_reest, int mean_reest, int var_reest, int tmat_reest); #ifdef __cplusplus } #endif #endif /* MODEL_INVENTORY_H */ /* * Log record. Maintained by CVS. * * $Log$ * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.5 1996/07/29 16:49:12 eht * added read/initialization calls * * Revision 1.4 1996/03/25 15:54:13 eht * Commented * * Revision 1.3 1995/10/10 13:10:34 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/09/08 19:13:52 eht * Updated to use acmod_set module instead of pset module * * Revision 1.1 1995/09/08 15:21:06 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/exp/gauden/subvq.c /* * subvq.c * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 12-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "subvq.h" /* * Precompute variances/(covariance-matrix-determinants) to simplify Mahalanobis distance * calculation (see libmain/gauden.*). Also, calculate 1/(det) for the original codebooks, * based on the VQ vars. */ static void subvq_ivar_idet_precompute (subvq_t *vq, float64 floor) { int32 s, r, c; float32 **idet; E_INFO("Precomputing 1/det(covar), 1/2*var\n"); /* Temporary idet array for vars in subvq */ idet = (float32 **) ckd_calloc_2d (vq->n_sv, vq->vqsize, sizeof(float32)); for (s = 0; s < vq->n_sv; s++) { for (r = 0; r < vq->vqsize; r++) { vector_nz_floor (vq->var[s][r], vq->svsize[s], floor); idet[s][r] = (float32) vector_maha_precomp (vq->var[s][r], vq->svsize[s]); } } vq->idet = idet; } subvq_t *subvq_init (char *file) { FILE *fp; char line[16384]; int32 n_sv; int32 s, k, n, r, c; char *strp; subvq_t *vq; E_INFO("Loading Mixture Gaussian sub-VQ file '%s'\n", file); vq = (subvq_t *) ckd_calloc (1, sizeof(subvq_t)); fp = myfopen(file, "r"); /* Read until "Sub-vectors" */ for (;;) { if (fgets (line, sizeof(line), fp) == NULL) E_FATAL("Failed to read VQParam header\n"); if (sscanf (line, "VQParam %d %d -> %d %d", &(vq->origsize.r), &(vq->origsize.c), &(vq->n_sv), &(vq->vqsize)) == 4) break; } n_sv = vq->n_sv; vq->svsize = (int32 *) ckd_calloc (n_sv, sizeof(int32)); vq->featdim = (int32 **) ckd_calloc (n_sv, sizeof(int32 *)); vq->mean = (float32 ***) ckd_calloc (n_sv, sizeof(float32 **)); vq->var = (float32 ***) ckd_calloc (n_sv, sizeof(float32 **)); vq->map = (int32 ***) ckd_calloc_3d (vq->origsize.r, vq->origsize.c, n_sv, sizeof(int32)); vq->cb_invalid = bitvec_alloc (vq->origsize.r); /* Read subvector sizes and feature dimension maps */ for (s = 0; s < n_sv; s++) { if ((fgets (line, sizeof(line), fp) == NULL) || (sscanf (line, "Subvector %d length %d%n", &k, &(vq->svsize[s]), &n) != 2) || (k != s)) E_FATAL("Error reading length(subvector %d)\n", s); vq->mean[s] = (float32 **) ckd_calloc_2d (vq->vqsize, vq->svsize[s], sizeof(float32)); vq->var[s] = (float32 **) ckd_calloc_2d (vq->vqsize, vq->svsize[s], sizeof(float32)); vq->featdim[s] = (int32 *) ckd_calloc (vq->svsize[s], sizeof(int32)); for (strp = line+n, c = 0; c < vq->svsize[s]; c++) { if (sscanf (strp, "%d%n", &(vq->featdim[s][c]), &n) != 1) E_FATAL("Error reading subvector(%d).featdim(%d)\n", s, c); strp += n; } } /* Echo info for sanity check */ E_INFO("Original #codebooks(states)/codewords: %d x %d\n", vq->origsize.r, vq->origsize.c); E_INFO("Subvectors: %d, VQsize: %d\n", vq->n_sv, vq->vqsize); for (s = 0; s < n_sv; s++) { E_INFO("Feature dims(%d): ", s); for (c = 0; c < vq->svsize[s]; c++) printf (" %2d", vq->featdim[s][c]); printf (" (%d)\n", vq->svsize[s]); } /* Read VQ codebooks and maps for each subvector */ for (s = 0; s < n_sv; s++) { E_INFO("Reading subvq %d\n", s); E_INFO("Reading codebook\n"); if ((fgets (line, sizeof(line), fp) == NULL) || (sscanf (line, "Codebook %d", &k) != 1) || (k != s)) E_FATAL("Error reading header\n", s); for (r = 0; r < vq->vqsize; r++) { if (fgets (line, sizeof(line), fp) == NULL) E_FATAL("Error reading row(%d)\n", r); for (strp = line, c = 0; c < vq->svsize[s]; c++) { if (sscanf (strp, "%f %f%n", &(vq->mean[s][r][c]), &(vq->var[s][r][c]), &k) != 2) E_FATAL("Error reading row(%d) col(%d)\n", r, c); strp += k; } } #if 0 E_INFO("Sanity check: mean[0,%d]:\n", vq->vqsize-1); vector_print (stdout, vq->mean[s][0], vq->svsize[s]); vector_print (stdout, vq->mean[s][vq->vqsize-1], vq->svsize[s]); E_INFO("Sanity check: var[0,%d]:\n", vq->vqsize-1); vector_print (stdout, vq->var[s][0], vq->svsize[s]); vector_print (stdout, vq->var[s][vq->vqsize-1], vq->svsize[s]); #endif E_INFO("Reading map\n"); if ((fgets (line, sizeof(line), fp) == NULL) || (sscanf (line, "Map %d", &k) != 1) || (k != s)) E_FATAL("Error reading header\n", s); for (r = 0; r < vq->origsize.r; r++) { if (fgets (line, sizeof(line), fp) == NULL) E_FATAL("Error reading row(%d)\n", r); for (strp = line, c = 0; c < vq->origsize.c; c++) { if (sscanf (strp, "%d%n", &(vq->map[r][c][s]), &k) != 1) E_FATAL("Error reading row(%d) col(%d)\n", r, c); strp += k; } } #if 0 E_INFO("Sanity check: map[0][0]:\n"); for (c = 0; c < vq->origsize.c; c++) printf (" %d", vq->map[0][c][s]); printf ("\n"); #endif fflush (stdout); } if ((fscanf (fp, "%s", line) != 1) || (strcmp (line, "End") != 0)) E_FATAL("Error reading 'End' token\n"); fclose (fp); subvq_ivar_idet_precompute (vq, 0.0001 /* varfloor */); #if 0 E_INFO("Sanity check: var[*,0]:\n"); for (s = 0; s < n_sv; s++) vector_print (stdout, vq->var[s][0], vq->svsize[s]); #endif /* Replace invalid entries in map with duplicate of a valid entry, if possible */ for (r = 0; r < vq->origsize.r; r++) { k = -1; for (c = 0; c < vq->origsize.c; c++) { if (vq->map[r][c][0] < 0) { /* All ought to be < 0 */ for (s = 1; s < vq->n_sv; s++) { if (vq->map[r][c][s] >= 0) E_FATAL("Partially undefined map[%d][%d]\n", r, c); } } else { /* All ought to be >= 0 */ for (s = 1; s < vq->n_sv; s++) { if (vq->map[r][c][s] < 0) E_FATAL("Partially undefined map[%d][%d]\n", r, c); } k = c; /* A valid codeword found; remember it */ } } if (k >= 0) { /* Copy k into invalid rows */ for (c = 0; c < vq->origsize.c; c++) { if (vq->map[r][c][0] < 0) { for (s = 0; s < vq->n_sv; s++) vq->map[r][c][s] = vq->map[r][k][s]; } } bitvec_clear (vq->cb_invalid, r); } else bitvec_set (vq->cb_invalid, r); } return vq; } void subvq_free (subvq_t *s) { int32 i; for (i = 0; i < s->n_sv; i++) { ckd_free_2d ((void **) s->mean[i]); ckd_free_2d ((void **) s->var[i]); ckd_free ((void *) s->featdim[i]); } ckd_free ((void *) s->svsize); ckd_free ((void *) s->featdim); ckd_free ((void *) s->mean); ckd_free ((void *) s->var); ckd_free_3d ((void ***) s->map); ckd_free ((void *) s); } void subvq_dist_eval (subvq_t *vq, float32 *vec, int32 **score) { int32 s, i, r; float32 *sv; float64 d; for (s = 0; s < vq->n_sv; s++) { /* Extract subvector s from vec */ sv = (float32 *) ckd_calloc (vq->svsize[s], sizeof(float32)); for (i = 0; i < vq->svsize[s]; i++) sv[i] = vec[vq->featdim[s][i]]; /* Compare subvector to all the codewords */ for (r = 0; r < vq->vqsize; r++) { d = vector_dist_maha (sv, vq->mean[s][r], vq->var[s][r], vq->idet[s][r], vq->svsize[s]); score[s][r] = log_to_logs3(d); } ckd_free ((void *) sv); } } <file_sep>/CLP/include/Node.h //------------------------------------- // Node.h stores a lattice node //------------------------------------- //------------------------------------------------------------------------------------------ // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------ #ifndef _Node_h #define _Node_h #include "common_lattice.h" #include "Prons.h" class Lattice; class Node { friend class Lattice; public: Node(); Node(const string&, const Lattice*, const Prons&); const int Word_idx() const {return word_idx;} const int Max_dist() const {return max_dist;} const unsigned Id() const {return id;} void setId(unsigned i) {id = i;} const double Time() const { return time; } friend ostream& operator<<(ostream& os, const Node& node); void print_it(const class Prons &); IntIntMap& Outgoing_links() { return outgoing_links; } private: const Lattice* lat_ptr; NodeId id; int word_idx; /* index of the word at this node; -1 when the words are on the links */ double time; /* Node time */ int max_dist; /* the max length of a path from the lattice start node to it to be used in the graphs without time information */ IntIntMap outgoing_links; /* nodes that can be reached from this node */ void fill_node_fields(const string&, const string& ); }; #endif <file_sep>/archive_s3/s3.2/src/main.c /* * main.c -- * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 29-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Modified to allow run-time choice between 3-state and 5-state HMM * topologies (instead of compile-time selection). * * 13-Aug-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added -maxwpf. * * 10-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "kb.h" #include "corpus.h" static arg_t arg[] = { { "-logbase", ARG_FLOAT32, "1.0003", "Base in which all log-likelihoods calculated" }, #if 0 /* Commented out; must be s3_1x39 */ { "-feat", ARG_STRING, NULL, "Feature type: Must be s3_1x39 / s2_4x / cep_dcep[,%d] / cep[,%d] / %d,%d,...,%d" }, #endif { "-cmn", ARG_STRING, "current", "Cepstral mean normalization scheme (default: Cep -= mean-over-current-sentence(Cep))" }, { "-varnorm", ARG_STRING, "no", "Variance normalize each utterance (yes/no; only applicable if CMN is also performed)" }, { "-agc", ARG_STRING, "max", "Automatic gain control for c0 ('max' or 'none'); (max: c0 -= max-over-current-sentence(c0))" }, { "-mdef", REQARG_STRING, NULL, "Model definition input file" }, { "-dict", REQARG_STRING, NULL, "Pronunciation dictionary input file" }, { "-fdict", REQARG_STRING, NULL, "Filler word pronunciation dictionary input file" }, #if 0 /* Commented out; not supported */ { "-compsep", ARG_STRING, "", /* Default: No compound word (NULL separator char) */ "Separator character between components of a compound word (NULL if none)" }, #endif { "-lm", REQARG_STRING, NULL, "Word trigram language model input file" }, { "-fillpen", ARG_STRING, NULL, "Filler word probabilities input file" }, { "-silprob", ARG_FLOAT32, "0.1", "Default silence word probability" }, { "-fillprob", ARG_FLOAT32, "0.1", "Default non-silence filler word probability" }, { "-lw", ARG_FLOAT32, "8.5", "Language weight" }, { "-wip", ARG_FLOAT32, "0.7", "Word insertion penalty" }, { "-uw", ARG_FLOAT32, "0.7", "Unigram weight" }, { "-mean", REQARG_STRING, NULL, "Mixture gaussian means input file" }, { "-var", REQARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to data from -var file)" }, #if 0 /* Commented out; must be .cont. */ { "-senmgau", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, #endif { "-mixw", REQARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to data from -mixw file)" }, { "-subvq", ARG_STRING, NULL, "Sub-vector quantized form of acoustic model" }, { "-tmat", REQARG_STRING, NULL, "HMM state transition matrix input file" }, { "-tmatfloor", ARG_FLOAT32, "0.0001", "HMM state transition probability floor (applied to -tmat file)" }, { "-Nlextree", ARG_INT32, "3", "No. of lextrees to be instantiated; entries into them staggered in time" }, { "-epl", ARG_INT32, "3", "Entries Per Lextree; #successive entries into one lextree before lextree-entries shifted to the next" }, { "-subvqbeam", ARG_FLOAT64, "3.0e-3", "Beam selecting best components within each mixture Gaussian [0(widest)..1(narrowest)]" }, { "-beam", ARG_FLOAT64, "1.0e-55", "Beam selecting active HMMs (relative to best) in each frame [0(widest)..1(narrowest)]" }, { "-pbeam", ARG_FLOAT64, "1.0e-50", "Beam selecting HMMs transitioning to successors in each frame [0(widest)..1(narrowest)]" }, { "-wbeam", ARG_FLOAT64, "1.0e-35", "Beam selecting word-final HMMs exiting in each frame [0(widest)..1(narrowest)]" }, { "-ctl", ARG_STRING, NULL, "Control file listing utterances to be processed" }, { "-utt", ARG_STRING, NULL, "Utterance file to be processed (-ctlcount argument times)" }, { "-ctloffset", ARG_INT32, "0", "No. of utterances at the beginning of -ctl file to be skipped" }, { "-ctlcount", ARG_INT32, "1000000000", /* A big number to approximate the default: "until EOF" */ "No. of utterances to be processed (after skipping -ctloffset entries)" }, { "-cepdir", ARG_STRING, NULL, "Input cepstrum files directory (prefixed to filespecs in control file)" }, { "-bptbldir", ARG_STRING, NULL, "Directory in which to dump word Viterbi back pointer table (for debugging)" }, { "-outlatdir", ARG_STRING, NULL, "Directory in which to dump word lattices" }, { "-outlatoldfmt", ARG_INT32, "1", "Whether to dump lattices in old format" }, { "-latext", ARG_STRING, "lat.gz", "Filename extension for lattice files (gzip compressed, by default)" }, { "-hmmdump", ARG_INT32, "0", "Whether to dump active HMM details to stderr (for debugging)" }, { "-lextreedump", ARG_INT32, "0", "Whether to dump the lextree structure to stderr (for debugging)" }, { "-maxwpf", ARG_INT32, "20", "Max no. of distinct word exits to maintain at each frame" }, { "-maxhistpf", ARG_INT32, "100", "Max no. of histories to maintain at each frame" }, { "-bghist", ARG_INT32, "0", "Bigram-mode: If TRUE only one BP entry/frame; else one per LM state" }, { "-maxhmmpf", ARG_INT32, "20000", "Max no. of active HMMs to maintain at each frame; approx." }, { "-hmmhistbinsize", ARG_INT32, "5000", "Performance histogram: #frames vs #HMMs active; #HMMs/bin in this histogram" }, { "-ptranskip", ARG_INT32, "0", "Use wbeam for phone transitions every so many frames (if >= 1)" }, { "-hypseg", ARG_STRING, NULL, "Recognition result file, with word segmentations and scores" }, { "-treeugprob", ARG_INT32, "1", "If TRUE (non-0), Use unigram probs in lextree" }, { NULL, ARG_INT32, NULL, NULL } }; static void kb_init (kb_t *kb) { kbcore_t *kbcore; mdef_t *mdef; dict_t *dict; dict2pid_t *d2p; lm_t *lm; s3cipid_t sil, ci; s3wid_t w; int32 i, n, n_lc; wordprob_t *wp; s3cipid_t *lc; bitvec_t lc_active; char *str; kb->kbcore = kbcore_init (cmd_ln_float32 ("-logbase"), "s3_1x39", /* Hack!! Hardwired constant for -feat argument */ cmd_ln_str("-cmn"), cmd_ln_str("-varnorm"), cmd_ln_str("-agc"), cmd_ln_str("-mdef"), cmd_ln_str("-dict"), cmd_ln_str("-fdict"), "", /* Hack!! Hardwired constant for -compsep argument */ cmd_ln_str("-lm"), cmd_ln_str("-fillpen"), cmd_ln_float32("-silprob"), cmd_ln_float32("-fillprob"), cmd_ln_float32("-lw"), cmd_ln_float32("-wip"), cmd_ln_float32("-uw"), cmd_ln_str("-mean"), cmd_ln_str("-var"), cmd_ln_float32("-varfloor"), cmd_ln_str("-mixw"), cmd_ln_float32("-mixwfloor"), cmd_ln_str("-subvq"), cmd_ln_str("-tmat"), cmd_ln_float32("-tmatfloor")); kbcore = kb->kbcore; mdef = kbcore_mdef(kbcore); dict = kbcore_dict(kbcore); lm = kbcore_lm(kbcore); d2p = kbcore_dict2pid(kbcore); if (NOT_S3WID(dict_startwid(dict)) || NOT_S3WID(dict_finishwid(dict))) E_FATAL("%s or %s not in dictionary\n", S3_START_WORD, S3_FINISH_WORD); if (NOT_S3LMWID(lm_startwid(lm)) || NOT_S3LMWID(lm_finishwid(lm))) E_FATAL("%s or %s not in LM\n", S3_START_WORD, S3_FINISH_WORD); /* Check that HMM topology restrictions are not violated */ if (tmat_chk_1skip (kbcore->tmat) < 0) E_FATAL("Tmat contains arcs skipping more than 1 state\n"); /* * Unlink <s> and </s> between dictionary and LM, to prevent their recognition. They * are merely dummy words (anchors) at the beginning and end of each utterance. */ lm_lmwid2dictwid(lm, lm_startwid(lm)) = BAD_S3WID; lm_lmwid2dictwid(lm, lm_finishwid(lm)) = BAD_S3WID; for (w = dict_startwid(dict); IS_S3WID(w); w = dict_nextalt(dict, w)) kbcore->dict2lmwid[w] = BAD_S3LMWID; for (w = dict_finishwid(dict); IS_S3WID(w); w = dict_nextalt(dict, w)) kbcore->dict2lmwid[w] = BAD_S3LMWID; sil = mdef_silphone (kbcore_mdef (kbcore)); if (NOT_S3CIPID(sil)) E_FATAL("Silence phone '%s' not in mdef\n", S3_SILENCE_CIPHONE); E_INFO("Building lextrees\n"); kb->sen_active = (int32 *) ckd_calloc (mdef_n_sen(mdef), sizeof(int32)); kb->ssid_active = (int32 *) ckd_calloc (mdef_n_sseq(mdef), sizeof(int32)); kb->comssid_active = (int32 *) ckd_calloc (dict2pid_n_comsseq(d2p), sizeof(int32)); /* Build active word list */ wp = (wordprob_t *) ckd_calloc (dict_size(dict), sizeof(wordprob_t)); n = lm_ug_wordprob (lm, MAX_NEG_INT32, wp); if (n < 1) E_FATAL("%d active words\n", n); n = wid_wordprob2alt (dict, wp, n); /* Add alternative pronunciations */ /* Retain or remove unigram probs from lextree, depending on option */ if (cmd_ln_int32("-treeugprob") == 0) { for (i = 0; i < n; i++) wp[i].prob = -1; /* Flatten all initial probabilities to a constant */ } /* Build set of all possible left contexts */ lc = (s3cipid_t *) ckd_calloc (mdef_n_ciphone (mdef) + 1, sizeof(s3cipid_t)); lc_active = bitvec_alloc (mdef_n_ciphone (mdef)); for (w = 0; w < dict_size (dict); w++) { ci = dict_pron (dict, w, dict_pronlen(dict, w) - 1); if (! mdef_is_fillerphone (mdef, ci)) bitvec_set (lc_active, ci); } ci = mdef_silphone(mdef); bitvec_set (lc_active, ci); for (ci = 0, n_lc = 0; ci < mdef_n_ciphone(mdef); ci++) { if (bitvec_is_set (lc_active, ci)) lc[n_lc++] = ci; } lc[n_lc] = BAD_S3CIPID; /* Create the desired no. of unigram lextrees */ kb->n_lextree = cmd_ln_int32 ("-Nlextree"); if (kb->n_lextree < 1) { E_ERROR("No. of ugtrees specified: %d; will instantiate 1 ugtree\n", kb->n_lextree); kb->n_lextree = 1; } kb->ugtree = (lextree_t **) ckd_calloc (kb->n_lextree, sizeof(lextree_t *)); for (i = 0; i < kb->n_lextree; i++) { kb->ugtree[i] = lextree_build (kbcore, wp, n, lc); lextree_type (kb->ugtree[i]) = 0; } bitvec_free (lc_active); ckd_free ((void *) lc); /* Create filler lextrees */ n = 0; for (i = dict_filler_start(dict); i <= dict_filler_end(dict); i++) { if (dict_filler_word(dict, i)) { wp[n].wid = i; wp[n].prob = fillpen (kbcore->fillpen, i); n++; } } kb->fillertree = (lextree_t **) ckd_calloc (kb->n_lextree, sizeof(lextree_t *)); for (i = 0; i < kb->n_lextree; i++) { kb->fillertree[i] = lextree_build (kbcore, wp, n, NULL); lextree_type (kb->fillertree[i]) = -1; } ckd_free ((void *) wp); E_INFO("Lextrees(%d), %d nodes(ug), %d nodes(filler)\n", kb->n_lextree, lextree_n_node(kb->ugtree[0]), lextree_n_node(kb->fillertree[0])); if (cmd_ln_int32("-lextreedump")) { for (i = 0; i < kb->n_lextree; i++) { fprintf (stderr, "UGTREE %d\n", i); lextree_dump (kb->ugtree[i], dict, stderr); } for (i = 0; i < kb->n_lextree; i++) { fprintf (stderr, "FILLERTREE %d\n", i); lextree_dump (kb->fillertree[i], dict, stderr); } fflush (stderr); } kb->ascr = ascr_init (mgau_n_mgau(kbcore_mgau(kbcore)), kbcore->dict2pid->n_comstate); kb->beam = beam_init (cmd_ln_float64("-subvqbeam"), cmd_ln_float64("-beam"), cmd_ln_float64("-pbeam"), cmd_ln_float64("-wbeam")); E_INFO("Beam= %d, PBeam= %d, WBeam= %d, SVQBeam= %d\n", kb->beam->hmm, kb->beam->ptrans, kb->beam->word, kb->beam->subvq); if ((kb->feat = feat_array_alloc (kbcore_fcb(kbcore), S3_MAX_FRAMES)) == NULL) E_FATAL("feat_array_alloc() failed\n"); kb->vithist = vithist_init (kbcore, kb->beam->word, cmd_ln_int32 ("-bghist")); ptmr_init (&(kb->tm_sen)); ptmr_init (&(kb->tm_srch)); kb->tot_fr = 0; kb->tot_sen_eval = 0.0; kb->tot_gau_eval = 0.0; kb->tot_hmm_eval = 0.0; kb->tot_wd_exit = 0.0; kb->hmm_hist_binsize = cmd_ln_int32("-hmmhistbinsize"); n = ((kb->ugtree[0]->n_node) + (kb->fillertree[0]->n_node)) * kb->n_lextree; n /= kb->hmm_hist_binsize; kb->hmm_hist_bins = n+1; kb->hmm_hist = (int32 *) ckd_calloc (n+1, sizeof(int32)); /* Really no need for +1 */ /* Open hypseg file if specified */ str = cmd_ln_str("-hypseg"); kb->matchsegfp = NULL; if (str) { if ((kb->matchsegfp = fopen(str, "w")) == NULL) E_ERROR("fopen(%s,w) failed; use FWDXCT: from std logfile\n", str); } } /* * Make the next_active information within all lextrees be the current one, after blowing * away the latter; in preparation for moving on to the next frame. */ static void kb_lextree_active_swap (kb_t *kb) { int32 i; for (i = 0; i < kb->n_lextree; i++) { lextree_active_swap (kb->ugtree[i]); lextree_active_swap (kb->fillertree[i]); } } /* * Begin search at bigrams of <s>, backing off to unigrams; and fillers. Update * kb->lextree_next_active with the list of active lextrees. */ static void utt_begin (kb_t *kb) { kbcore_t *kbc; int32 n, pred; kbc = kb->kbcore; /* Insert initial <s> into vithist structure */ pred = vithist_utt_begin (kb->vithist, kbc); assert (pred == 0); /* Vithist entry ID for <s> */ /* Enter into unigram lextree[0] */ n = lextree_n_next_active(kb->ugtree[0]); assert (n == 0); lextree_enter (kb->ugtree[0], mdef_silphone(kbc->mdef), -1, 0, pred, kb->beam->hmm); /* Enter into filler lextree */ n = lextree_n_next_active(kb->fillertree[0]); assert (n == 0); lextree_enter (kb->fillertree[0], BAD_S3CIPID, -1, 0, pred, kb->beam->hmm); kb->n_lextrans = 1; kb_lextree_active_swap (kb); } static void matchseg_write (FILE *fp, kb_t *kb, glist_t hyp, char *hdr) { gnode_t *gn; hyp_t *h; int32 ascr, lscr; dict_t *dict; ascr = 0; lscr = 0; for (gn = hyp; gn; gn = gnode_next(gn)) { h = (hyp_t *) gnode_ptr (gn); ascr += h->ascr; lscr += h->lscr; } dict = kbcore_dict(kb->kbcore); fprintf (fp, "%s%s S 0 T %d A %d L %d", (hdr ? hdr : ""), kb->uttid, ascr+lscr, ascr, lscr); for (gn = hyp; gn && (gnode_next(gn)); gn = gnode_next(gn)) { h = (hyp_t *) gnode_ptr (gn); fprintf (fp, " %d %d %d %s", h->sf, h->ascr, h->lscr, dict_wordstr (dict, h->id)); } fprintf (fp, " %d\n", kb->nfr); fflush (fp); } static void utt_end (kb_t *kb) { int32 id, ascr, lscr; glist_t hyp; gnode_t *gn; hyp_t *h; FILE *fp, *latfp; dict_t *dict; int32 i; fp = stdout; dict = kbcore_dict (kb->kbcore); if ((id = vithist_utt_end (kb->vithist, kb->kbcore)) >= 0) { if (cmd_ln_str("-bptbldir")) { char file[8192]; sprintf (file, "%s/%s.bpt", cmd_ln_str ("-bptbldir"), kb->uttid); if ((latfp = fopen (file, "w")) == NULL) { E_ERROR("fopen(%s,w) failed; using stdout\n", file); latfp = stdout; } vithist_dump (kb->vithist, -1, kb->kbcore, latfp); if (latfp != stdout) fclose (latfp); } hyp = vithist_backtrace (kb->vithist, id); /* Detailed backtrace */ fprintf (fp, "\nBacktrace(%s)\n", kb->uttid); fprintf (fp, "%6s %5s %5s %11s %8s %4s\n", "LatID", "SFrm", "EFrm", "AScr", "LScr", "Type"); ascr = 0; lscr = 0; for (gn = hyp; gn; gn = gnode_next(gn)) { h = (hyp_t *) gnode_ptr (gn); fprintf (fp, "%6d %5d %5d %11d %8d %4d %s\n", h->vhid, h->sf, h->ef, h->ascr, h->lscr, h->type, dict_wordstr(dict, h->id)); ascr += h->ascr; lscr += h->lscr; } fprintf (fp, " %5d %5d %11d %8d (Total)\n", 0, kb->nfr, ascr, lscr); /* Match */ fprintf (fp, "\nFWDVIT: "); for (gn = hyp; gn; gn = gnode_next(gn)) { h = (hyp_t *) gnode_ptr (gn); if ((! dict_filler_word(dict, h->id)) && (h->id != dict_finishwid(dict))) fprintf (fp, "%s ", dict_wordstr (dict, dict_basewid(dict, h->id))); } fprintf (fp, " (%s)\n\n", kb->uttid); /* Matchseg */ if (kb->matchsegfp) matchseg_write (kb->matchsegfp, kb, hyp, NULL); matchseg_write (fp, kb, hyp, "FWDXCT: "); fprintf (fp, "\n"); if (cmd_ln_str ("-outlatdir")) { char str[16384]; int32 ispipe; float64 logbase; sprintf (str, "%s/%s.%s", cmd_ln_str("-outlatdir"), kb->uttid, cmd_ln_str("-latext")); E_INFO("Writing lattice file: %s\n", str); if ((latfp = fopen_comp (str, "w", &ispipe)) == NULL) E_ERROR("fopen_comp (%s,w) failed\n", str); else { /* Write header info */ getcwd (str, sizeof(str)); fprintf (latfp, "# getcwd: %s\n", str); /* Print logbase first!! Other programs look for it early in the DAG */ logbase = cmd_ln_float32 ("-logbase"); fprintf (latfp, "# -logbase %e\n", logbase); fprintf (latfp, "# -dict %s\n", cmd_ln_str ("-dict")); if (cmd_ln_str ("-fdict")) fprintf (latfp, "# -fdict %s\n", cmd_ln_str ("-fdict")); fprintf (latfp, "# -lm %s\n", cmd_ln_str ("-lm")); fprintf (latfp, "# -mdef %s\n", cmd_ln_str ("-mdef")); fprintf (latfp, "# -mean %s\n", cmd_ln_str ("-mean")); fprintf (latfp, "# -var %s\n", cmd_ln_str ("-var")); fprintf (latfp, "# -mixw %s\n", cmd_ln_str ("-mixw")); fprintf (latfp, "# -tmat %s\n", cmd_ln_str ("-tmat")); fprintf (latfp, "#\n"); fprintf (latfp, "Frames %d\n", kb->nfr); fprintf (latfp, "#\n"); vithist_dag_write (kb->vithist, hyp, dict, cmd_ln_int32("-outlatoldfmt"), latfp); fclose_comp (latfp, ispipe); } } /* Free hyplist */ for (gn = hyp; gn && (gnode_next(gn)); gn = gnode_next(gn)) { h = (hyp_t *) gnode_ptr (gn); ckd_free ((void *) h); } glist_free (hyp); } else E_ERROR("%s: No recognition\n\n", kb->uttid); E_INFO("%4d frm; %4d sen, %5d gau/fr, %4.1f CPU %4.1f Clk; %5d hmm, %3d wd/fr, %4.1f CPU %4.1f Clk (%s)\n", kb->nfr, (kb->utt_sen_eval + (kb->nfr >> 1)) / kb->nfr, (kb->utt_gau_eval + (kb->nfr >> 1)) / kb->nfr, kb->tm_sen.t_cpu * 100.0 / kb->nfr, kb->tm_sen.t_elapsed * 100.0 / kb->nfr, (kb->utt_hmm_eval + (kb->nfr >> 1)) / kb->nfr, (vithist_n_entry(kb->vithist) + (kb->nfr >> 1)) / kb->nfr, kb->tm_srch.t_cpu * 100.0 / kb->nfr, kb->tm_srch.t_elapsed * 100.0 / kb->nfr, kb->uttid); { int32 j, k; for (j = kb->hmm_hist_bins-1; (j >= 0) && (kb->hmm_hist[j] == 0); --j); E_INFO("HMMHist[0..%d](%s):", j, kb->uttid); for (i = 0, k = 0; i <= j; i++) { k += kb->hmm_hist[i]; fprintf (stderr, " %d(%d)", kb->hmm_hist[i], (k*100)/kb->nfr); } fprintf (stderr, "\n"); fflush (stderr); } kb->tot_sen_eval += kb->utt_sen_eval; kb->tot_gau_eval += kb->utt_gau_eval; kb->tot_hmm_eval += kb->utt_hmm_eval; kb->tot_wd_exit += vithist_n_entry(kb->vithist); ptmr_reset (&(kb->tm_sen)); ptmr_reset (&(kb->tm_srch)); system ("ps aguxwww | grep dec"); for (i = 0; i < kb->n_lextree; i++) { lextree_utt_end (kb->ugtree[i], kb->kbcore); lextree_utt_end (kb->fillertree[i], kb->kbcore); } vithist_utt_reset (kb->vithist); lm_cache_stats_dump (kbcore_lm(kb->kbcore)); lm_cache_reset (kbcore_lm(kb->kbcore)); } static void utt_word_trans (kb_t *kb, int32 cf) { int32 k, th; vithist_t *vh; vithist_entry_t *ve; int32 vhid, le, n_ci, score; static int32 *bs = NULL, *bv = NULL, epl; s3wid_t wid; int32 p; dict_t *dict; mdef_t *mdef; vh = kb->vithist; th = kb->bestscore + kb->beam->hmm; /* Pruning threshold */ if (vh->bestvh[cf] < 0) return; dict = kbcore_dict(kb->kbcore); mdef = kbcore_mdef(kb->kbcore); n_ci = mdef_n_ciphone(mdef); /* Initialize best exit for each distinct word-final CIphone to NONE */ if (! bs) { bs = (int32 *) ckd_calloc (n_ci, sizeof(int32)); bv = (int32 *) ckd_calloc (n_ci, sizeof(int32)); epl = cmd_ln_int32 ("-epl"); } for (p = 0; p < n_ci; p++) { bs[p] = MAX_NEG_INT32; bv[p] = -1; } /* Find best word exit in this frame for each distinct word-final CI phone */ vhid = vithist_first_entry (vh, cf); le = vithist_n_entry (vh) - 1; for (; vhid <= le; vhid++) { ve = vithist_id2entry (vh, vhid); if (! vithist_entry_valid(ve)) continue; wid = vithist_entry_wid (ve); p = dict_last_phone (dict, wid); if (mdef_is_fillerphone(mdef, p)) p = mdef_silphone(mdef); score = vithist_entry_score (ve); if (score > bs[p]) { bs[p] = score; bv[p] = vhid; } } /* Find lextree instance to be entered */ k = kb->n_lextrans++; k = (k % (kb->n_lextree * epl)) / epl; /* Transition to unigram lextrees */ for (p = 0; p < n_ci; p++) { if (bv[p] >= 0) lextree_enter (kb->ugtree[k], p, cf, bs[p], bv[p], th); } /* Transition to filler lextrees */ lextree_enter (kb->fillertree[k], BAD_S3CIPID, cf, vh->bestscore[cf], vh->bestvh[cf], th); } /* Invoked by ctl_process in libmisc/corpus.c */ static void utt_decode (void *data, char *uttfile, int32 sf, int32 ef, char *uttid) { kb_t *kb; kbcore_t *kbcore; mdef_t *mdef; dict_t *dict; dict2pid_t *d2p; mgau_model_t *mgau; subvq_t *svq; lextree_t *lextree; int32 besthmmscr, bestwordscr, th, pth, wth, maxwpf, maxhistpf, maxhmmpf, ptranskip; int32 i, j, f; int32 n_hmm_eval, frm_nhmm, hb, pb, wb; FILE *hmmdumpfp; E_INFO("Processing: %s\n", uttid); kb = (kb_t *) data; kbcore = kb->kbcore; mdef = kbcore_mdef (kbcore); dict = kbcore_dict (kbcore); d2p = kbcore_dict2pid (kbcore); mgau = kbcore_mgau (kbcore); svq = kbcore_svq (kbcore); kb->uttid = uttid; hmmdumpfp = cmd_ln_int32("-hmmdump") ? stderr : NULL; maxwpf = cmd_ln_int32 ("-maxwpf"); maxhistpf = cmd_ln_int32 ("-maxhistpf"); maxhmmpf = cmd_ln_int32 ("-maxhmmpf"); ptranskip = cmd_ln_int32 ("-ptranskip"); /* Read mfc file and build feature vectors for entire utterance */ kb->nfr = feat_s2mfc2feat(kbcore_fcb(kbcore), uttfile, cmd_ln_str("-cepdir"), sf, ef, kb->feat, S3_MAX_FRAMES); E_INFO("%s: %d frames\n", kb->uttid, kb->nfr); for (i = 0; i < kb->hmm_hist_bins; i++) kb->hmm_hist[i] = 0; utt_begin (kb); n_hmm_eval = 0; kb->utt_sen_eval = 0; kb->utt_gau_eval = 0; for (f = 0; f < kb->nfr; f++) { /* Acoustic (senone scores) evaluation */ ptmr_start (&(kb->tm_sen)); /* Find active senones and composite senones, from active lextree nodes */ if (kb->sen_active) { memset (kb->ssid_active, 0, mdef_n_sseq(mdef) * sizeof(int32)); memset (kb->comssid_active, 0, dict2pid_n_comsseq(d2p) * sizeof(int32)); /* Find active senone-sequence IDs (including composite ones) */ for (i = 0; i < (kb->n_lextree <<1); i++) { lextree = (i < kb->n_lextree) ? kb->ugtree[i] : kb->fillertree[i - kb->n_lextree]; lextree_ssid_active (lextree, kb->ssid_active, kb->comssid_active); } /* Find active senones from active senone-sequences */ memset (kb->sen_active, 0, mdef_n_sen(mdef) * sizeof(int32)); mdef_sseq2sen_active (mdef, kb->ssid_active, kb->sen_active); /* Add in senones needed for active composite senone-sequences */ dict2pid_comsseq2sen_active (d2p, mdef, kb->comssid_active, kb->sen_active); } /* Evaluate senone acoustic scores for the active senones */ subvq_frame_eval (svq, mgau, kb->beam->subvq, kb->feat[f][0], kb->sen_active, kb->ascr->sen); kb->utt_sen_eval += mgau_frm_sen_eval(mgau); kb->utt_gau_eval += mgau_frm_gau_eval(mgau); /* Evaluate composite senone scores from senone scores */ dict2pid_comsenscr (kbcore_dict2pid(kbcore), kb->ascr->sen, kb->ascr->comsen); ptmr_stop (&(kb->tm_sen)); /* Search */ ptmr_start (&(kb->tm_srch)); /* Evaluate active HMMs in each lextree; note best HMM state score */ besthmmscr = MAX_NEG_INT32; bestwordscr = MAX_NEG_INT32; frm_nhmm = 0; for (i = 0; i < (kb->n_lextree <<1); i++) { lextree = (i < kb->n_lextree) ? kb->ugtree[i] : kb->fillertree[i - kb->n_lextree]; if (hmmdumpfp != NULL) fprintf (hmmdumpfp, "Fr %d Lextree %d #HMM %d\n", f, i, lextree->n_active); lextree_hmm_eval (lextree, kbcore, kb->ascr, f, hmmdumpfp); if (besthmmscr < lextree->best) besthmmscr = lextree->best; if (bestwordscr < lextree->wbest) bestwordscr = lextree->wbest; n_hmm_eval += lextree->n_active; frm_nhmm += lextree->n_active; } if (besthmmscr > 0) { E_ERROR("***ERROR*** Fr %d, best HMM score > 0 (%d); int32 wraparound?\n", f, besthmmscr); } kb->hmm_hist[frm_nhmm / kb->hmm_hist_binsize]++; /* Set pruning threshold depending on whether number of active HMMs within limit */ if (frm_nhmm > (maxhmmpf + (maxhmmpf >> 1))) { int32 *bin, nbin, bw; /* Use histogram pruning */ nbin = 1000; bw = -(kb->beam->hmm) / nbin; bin = (int32 *) ckd_calloc (nbin, sizeof(int32)); for (i = 0; i < (kb->n_lextree <<1); i++) { lextree = (i < kb->n_lextree) ? kb->ugtree[i] : kb->fillertree[i - kb->n_lextree]; lextree_hmm_histbin (lextree, besthmmscr, bin, nbin, bw); } for (i = 0, j = 0; (i < nbin) && (j < maxhmmpf); i++, j += bin[i]); ckd_free ((void *) bin); /* Determine hmm, phone, word beams */ hb = -(i * bw); pb = (hb > kb->beam->ptrans) ? hb : kb->beam->ptrans; wb = (hb > kb->beam->word) ? hb : kb->beam->word; #if 0 E_INFO("Fr %5d, #hmm= %6d, #bin= %d, #hmm= %6d, beam= %8d, pbeam= %8d, wbeam= %8d\n", f, frm_nhmm, i, j, hb, pb, wb); #endif } else { hb = kb->beam->hmm; pb = kb->beam->ptrans; wb = kb->beam->word; } kb->bestscore = besthmmscr; kb->bestwordscore = bestwordscr; th = kb->bestscore + hb; /* HMM survival threshold */ pth = kb->bestscore + pb; /* Cross-HMM transition threshold */ wth = kb->bestwordscore + wb; /* Word exit threshold */ /* * For each lextree, determine if the active HMMs remain active for next * frame, propagate scores across HMM boundaries, and note word exits. */ for (i = 0; i < (kb->n_lextree <<1); i++) { lextree = (i < kb->n_lextree) ? kb->ugtree[i] : kb->fillertree[i - kb->n_lextree]; /* Hack!! Use a narrow phone transition beam (wth) every so many frames */ if ((ptranskip < 1) || ((f % ptranskip) != 0)) lextree_hmm_propagate (lextree, kbcore, kb->vithist, f, th, pth, wth); else lextree_hmm_propagate (lextree, kbcore, kb->vithist, f, th, wth, wth); } /* Limit vithist entries created this frame to specified max */ vithist_prune (kb->vithist, dict, f, maxwpf, maxhistpf, wb); /* Cross-word transitions */ utt_word_trans (kb, f); /* Wind up this frame */ vithist_frame_windup (kb->vithist, f, NULL, kbcore); kb_lextree_active_swap (kb); ptmr_stop (&(kb->tm_srch)); if ((f % 100) == 0) { fprintf (stderr, "."); fflush (stderr); } } kb->utt_hmm_eval = n_hmm_eval; utt_end (kb); kb->tot_fr += kb->nfr; fprintf (stdout, "\n"); } int32 main (int32 argc, char *argv[]) { kb_t kb; ptmr_t tm; #if (! WIN32) { char host[4096], path[16384]; gethostname (host, 1024); host[1023] = '\0'; getcwd (path, sizeof(path)); E_INFO ("Host: '%s'\n", host); E_INFO ("Directory: '%s'\n", path); } #endif E_INFO("Compiled on %s, at %s\n\n", __DATE__, __TIME__); cmd_ln_parse (arg, argc, argv); unlimit (); kb_init (&kb); fprintf (stdout, "\n"); if (cmd_ln_str ("-ctl")) { tm = ctl_process (cmd_ln_str("-ctl"), cmd_ln_int32("-ctloffset"), cmd_ln_int32("-ctlcount"), utt_decode, &kb); } else if (cmd_ln_str ("-utt")) { tm = ctl_process_utt (cmd_ln_str("-utt"), cmd_ln_int32("-ctlcount"), utt_decode, &kb); } if (kb.matchsegfp) fclose (kb.matchsegfp); if (kb.tot_fr == 0) kb.tot_fr = 1; /* Just to avoid /0 */ E_INFO("SUMMARY: %d fr; %d sen, %d gau/fr, %.1f xCPU; %d hmm/fr, %d wd/fr, %.1f xCPU; tot: %.1f xCPU, %.1f xClk\n", kb.tot_fr, (int32)(kb.tot_sen_eval / kb.tot_fr), (int32)(kb.tot_gau_eval / kb.tot_fr), kb.tm_sen.t_tot_cpu * 100.0 / kb.tot_fr, (int32)(kb.tot_hmm_eval / kb.tot_fr), (int32)(kb.tot_wd_exit / kb.tot_fr), kb.tm_srch.t_tot_cpu * 100.0 / kb.tot_fr, tm.t_tot_cpu * 100.0 / kb.tot_fr, tm.t_tot_elapsed * 100.0 / kb.tot_fr); exit(0); } <file_sep>/SphinxTrain/src/programs/mixw_interp/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <assert.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; #include "cmd_ln_defn.h" cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/11/29 01:43:46 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.3 2004/11/29 01:11:34 egouvea * Fixed license terms in some new files. * * Revision 1.2 2004/08/10 21:58:56 arthchan2003 * Incorporate help and example for the four final tools * * Revision 1.1 2004/06/17 19:39:49 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.14 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.13 1996/08/06 14:03:47 eht * -sildelfn argument to specify silence deletion list * * Revision 1.12 1996/07/29 16:18:48 eht * Make -accumdir optional so that it may be omitted for * debugging purposes * MLLR command line options * -veclen to -ceplen * -minvar to -varfloor (now named consistently w/ the other floors) * added -2passvar switch to allow reestimation based on prior means * * Revision 1.11 1996/03/26 14:03:24 eht * - Added '-timing' argument * - changed doc strings for some arguments * * Revision 1.10 1996/02/02 17:41:47 eht * Add alpha and beta beams * * Revision 1.9 1996/01/26 18:23:49 eht * Reformatted argument specifications * * Revision 1.8 1995/11/30 20:42:07 eht * Add argument for transition matrix reestimation * Add argument for state parameter definition file * * */ <file_sep>/tools/corpusBrowser/src/java/edu/cmu/sphinx/tools/corpusBrowser/WordSpectrogramPanel.java package edu.cmu.sphinx.tools.corpusBrowser; import edu.cmu.sphinx.frontend.Data; import edu.cmu.sphinx.frontend.DataEndSignal; import edu.cmu.sphinx.frontend.DoubleData; import edu.cmu.sphinx.frontend.FrontEnd; import edu.cmu.sphinx.frontend.util.StreamDataSource; import edu.cmu.sphinx.tools.audio.AudioDataInputStream; import edu.cmu.sphinx.tools.audio.SpectrogramPanel; import edu.cmu.sphinx.tools.corpus.Word; import edu.cmu.sphinx.util.props.ConfigurationManager; import edu.cmu.sphinx.util.props.PropertyException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ReplicateScaleFilter; import java.io.IOException; import java.util.ArrayList; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Jan 24, 2006 * Time: 9:53:23 PM */ public class WordSpectrogramPanel extends SpectrogramPanel { private Word word; private double maxIntensity; private double minIntensity; private double [] pitch; private double [] energy; public void setWord(ConfigurationManager cm, Word word) { try { this.word = word; //zoomSet(20.0f); frontEnd = (FrontEnd) cm.lookup("spectrogramFrontEnd"); dataSource = (StreamDataSource) cm.lookup("streamDataSource"); this.audio = word.getRegionOfAudioData().getAudioData(); this.pitch = word.getRegionOfAudioData().getPitchData(); this.energy = word.getRegionOfAudioData().getEnergyData(); audio.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { computeSpectrogram(); } }); setOffset(0.0); } catch (PropertyException e) { throw new Error(e); } catch (InstantiationException e) { throw new Error(e); } catch (IOException e) { throw new Error(e); } } public void setZoom(double zoom) { zoomSet((float) zoom); } public void setOffset(double v) { setOffsetFactor(((maxIntensity - minIntensity) * v) * 100); //+ minIntensity ); } protected void computeSpectrogram() { try { AudioDataInputStream is = new AudioDataInputStream(audio); dataSource.setInputStream(is, "live audio"); /* Run through all the spectra one at a time and convert * them to an log intensity value. */ ArrayList<double[]> intensitiesList = new ArrayList<double[]>(); maxIntensity = Double.MIN_VALUE; minIntensity = Double.MAX_VALUE; Data spectrum = frontEnd.getData(); while (!(spectrum instanceof DataEndSignal)) { if (spectrum instanceof DoubleData) { double[] spectrumData = ((DoubleData) spectrum).getValues(); double[] intensities = new double[spectrumData.length]; for (int i = 0; i < intensities.length; i++) { /* * A very small intensity is, for all intents * and purposes, the same as 0. */ intensities[i] = Math.max(Math.log(spectrumData[i]), 0.0); if (intensities[i] > maxIntensity) { maxIntensity = intensities[i]; } if (intensities[i] < minIntensity) { minIntensity = intensities[i]; } } intensitiesList.add(intensities); } spectrum = frontEnd.getData(); } is.close(); int width = intensitiesList.size(); int height = (intensitiesList.get(0)).length; int maxYIndex = height - 1; Dimension d = new Dimension(width, height); setMinimumSize(d); setMaximumSize(d); setPreferredSize(d); /* Create the image for displaying the data. */ spectrogram = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); /* Set scaleFactor so that the maximum value, after removing * the offset, will be 0xff. */ double scaleFactor = ((0xff + offsetFactor) / maxIntensity); for (int i = 0; i < width; i++) { double[] intensities = intensitiesList.get(i); for (int j = maxYIndex; j >= 0; j--) { /* Adjust the grey value to make a value of 0 to mean * white and a value of 0xff to mean black. */ int grey = (int) (intensities[j] * scaleFactor - offsetFactor); grey = Math.max(grey, 0); grey = 0xff - grey; /* Turn the grey into a pixel value. */ int pixel = ((grey << 16) & 0xff0000) | ((grey << 8) & 0xff00) | (grey & 0xff); spectrogram.setRGB(i, maxYIndex - j, pixel); } int p; int e; int m = i % 10; p = (int)((10-m)*(pitch[i/10]/2) + m*pitch[(i/10)+1]/2)/10; e = (int)((10-m)*(energy[i/10]/100000000) + m*energy[(i/10)+1]/100000000)/10; //p = (int)pitch[i]/2; //e = (int)energy[i]/10000000; spectrogram.setRGB(i, Math.min(maxYIndex - p,maxYIndex), 0xff); spectrogram.setRGB(i, Math.min(maxYIndex - e,maxYIndex), 0xff0000); } ImageFilter scaleFilter = new ReplicateScaleFilter((int) (zoom * width), height); scaledSpectrogram = createImage(new FilteredImageSource(spectrogram.getSource(), scaleFilter)); Dimension sz = getSize(); repaint(0, 0, 0, sz.width - 1, sz.height - 1); } catch (Exception e) { e.printStackTrace(); } } /* protected void computeSpectrogram() { try { AudioDataInputStream is = new AudioDataInputStream(audio); dataSource.setInputStream(is, "live audio"); // Run through all the spectra one at a time and convert // them to an log intensity value. ArrayList intensitiesList = new ArrayList(); double maxIntensity = Double.MIN_VALUE; double minIntensity = Double.MAX_VALUE; Data spectrum = frontEnd.getData(); while (!(spectrum instanceof DataEndSignal)) { if (spectrum instanceof DoubleData) { double[] spectrumData = ((DoubleData) spectrum).getValues(); double[] intensities = new double[spectrumData.length]; for (int i = 0; i < intensities.length; i++) { // A very small intensity is, for all intents // and purposes, the same as 0. intensities[i] = Math.max(Math.log(spectrumData[i]), 0.0); if (intensities[i] > maxIntensity) { maxIntensity = intensities[i]; } if (intensities[i] < minIntensity) { minIntensity = intensities[i]; } } intensitiesList.add(intensities); } spectrum = frontEnd.getData(); } is.close(); int width = intensitiesList.size(); int height = ((double[]) intensitiesList.get(0)).length; int maxYIndex = height - 1; Dimension d = new Dimension(width, height); setMinimumSize(d); setMaximumSize(d); setPreferredSize(d); // Create the image for displaying the data. spectrogram = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Set scaleFactor so that the maximum value, after removing // the offset, will be 0xff. double scaleFactor = ((0xff + offsetFactor) / maxIntensity); int half = (int)(maxIntensity+minIntensity)/2; for (int i = 0; i < width; i++) { double[] intensities = (double[]) intensitiesList.get(i); for (int j = maxYIndex; j >= 0; j--) { // Adjust the grey value to make a value of 0 to mean // white and a value of 0xff to mean black. int mag = (int) (intensities[j] * scaleFactor - offsetFactor); int red = mag; int blue = 0; // (int)maxIntensity - mag; int green; if( mag < half ) { red = 0; green = (int)maxIntensity - (2*mag); } else { green = (2*(mag-half)); blue = 0; } // Turn the grey into a pixel value. int pixel = ((red << 16) & 0xff0000) | ((green << 8) & 0xff00) | (blue & 0xff); spectrogram.setRGB(i, maxYIndex - j, pixel); } } ImageFilter scaleFilter = new ReplicateScaleFilter((int) (zoom * width), height); scaledSpectrogram = createImage(new FilteredImageSource(spectrogram.getSource(), scaleFilter)); Dimension sz = getSize(); repaint(0, 0, 0, sz.width - 1, sz.height - 1); } catch (Exception e) { e.printStackTrace(); } } */ } <file_sep>/SphinxTrain/src/programs/mixw_interp/main.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * This file reads two mixing weight file and interoplates them * using log function * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include "parse_cmd_ln.h" /* The SPHINX-III common library */ #include <s3/common.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3mixw_io.h> #include <sys_compat/file.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s3/s3.h> #include <s3/err.h> #include <stdio.h> #include <math.h> #include <assert.h> static int interp_mixw(void); static int initialize(int argc, char *argv[]) { /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); return S3_SUCCESS; } int interp_mixw() { float32 ***SImixw, ***SDmixw, SIsum, SDsum; float32 silambda; uint32 n_SImixw, n_SDmixw; uint32 n_SIfeat, n_SDfeat; uint32 n_SIdensity, n_SDdensity; const char *SIfn, *SDfn, *outfn; uint32 i, j, k; SIfn = (const char *)cmd_ln_access("-SImixwfn"); E_INFO("Reading %s\n", SIfn); if (s3mixw_read(SIfn, &SImixw, &n_SImixw, &n_SIfeat, &n_SIdensity) != S3_SUCCESS) { return S3_ERROR; } printf("SImixw %u %u %u\n", n_SImixw, n_SIfeat, n_SIdensity); SDfn = (const char *)cmd_ln_access("-SDmixwfn"); E_INFO("Reading %s\n", SDfn); if (s3mixw_read(SDfn, &SDmixw, &n_SDmixw, &n_SDfeat, &n_SDdensity) != S3_SUCCESS) { return S3_ERROR; } silambda = *(float32 *) cmd_ln_access("-SIlambda"); if (silambda < 0 || silambda > 1.0) E_FATAL("silamda value outside range (0,1.0)\n"); printf("SDmixw %u %u %u\n", n_SDmixw, n_SDfeat, n_SDdensity); printf("Interpolating with SI weight %f\n",silambda); if ((n_SImixw != n_SDmixw) | (n_SIfeat != n_SDfeat) | (n_SIdensity != n_SDdensity)) { E_INFO("Mixing weight files are not compatible.\n"); return S3_ERROR; } for (i = 0; i < n_SDmixw; i++) { for (j = 0; j < n_SDfeat; j++) { float32 SIwt = 0; float32 SDwt = 0; for (k = 0, SDsum = 0; k < n_SDdensity; k++) { SDsum += SDmixw[i][j][k]; } /*if (j == 0) printf("%f\t",SDsum);*/ if (SDsum != 0) { SDwt = (1.0 - silambda)/SDsum; } for (k = 0, SIsum = 0; k < n_SIdensity; k++) { SIsum += SImixw[i][j][k]; } /*if (j == 0) printf("%f\n",SIsum);*/ if (SIsum != 0) { SIwt = silambda/SIsum; } for (k = 0; k < n_SDdensity; k++) { SDmixw[i][j][k] = SImixw[i][j][k]*SIwt + SDmixw[i][j][k]*SDwt; } } } outfn = (const char *)cmd_ln_access("-outmixwfn"); E_INFO("Writing %s\n", outfn); if (s3mixw_write(outfn, SDmixw, n_SDmixw, n_SDfeat, n_SDdensity) != S3_SUCCESS) { return S3_ERROR; } return S3_SUCCESS; } int main(int argc, char *argv[]) { if (initialize(argc, argv) != S3_SUCCESS) { E_ERROR("Errors initializing.\n"); return 1; } if (interp_mixw() != S3_SUCCESS) return 1; return 0; } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/executor/ExecutorListener.java package edu.cmu.sphinx.tools.executor; import edu.cmu.sphinx.util.props.PropertySheet; /** * DOCUMENT ME! * * @author <NAME> */ public interface ExecutorListener { public void addedExecutor(PropertySheet executablePS); public void removedExecutor(PropertySheet ps); } <file_sep>/archive_s3/s3.2/src/hmm.h /* * hmm.h -- HMM data structure. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 29-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Modified hmm_t.state to be a run-time array instead of a compile-time * one. Modified compile-time 3 and 5-state versions of hmm_vit_eval * into hmm_vit_eval_3st and hmm_vit_eval_5st, to allow run-time selection. * Removed hmm_init(). * * 08-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added HMM_SKIPARCS compile-time option and hmm_init(). * * 10-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started, based on an earlier version. */ #ifndef _S3_HMM_H_ #define _S3_HMM_H_ #include <libutil/libutil.h> #include "s3types.h" /* * An individual HMM among the HMM search space. An HMM with N emitting states consists * of N+2 internal states including the non-emitting entry (in) and exit (out) states. * For compatibility with Sphinx-II, we assume that the initial or entry state can only * transition to state 0, and the transition matrix is n_emit_state x (n_emit_state+1), * where the extra destination dimension correponds to the final or exit state. */ /* * NOTE: For efficiency, this version is hardwired for two possible HMM topologies: * * 5-state left-to-right HMMs: (0 is the entry state and E is a non-emitting exit state; * the x's indicate allowed transitions between source and destination states): * * 0 1 2 3 4 E (destination-states) * 0 x x x * 1 x x x * 2 x x x * 3 x x x * 4 x x * (source-states) * 5-state topologies that contain a subset of the above transitions should work as well. * * 3-state left-to-right HMMs (similar notation as the 5-state topology above): * * 0 1 2 E (destination-states) * 0 x x x * 1 x x x * 2 x x * (source-states) * 3-state topologies that contain a subset of the above transitions should work as well. */ /* A single state in the HMM */ typedef struct { int32 score; /* State score (path log-likelihood) */ int32 history; /* History index */ } hmm_state_t; typedef struct { hmm_state_t *state; /* Per-state data for emitting states */ hmm_state_t in; /* Non-emitting entry state */ hmm_state_t out; /* Non-emitting exit state */ int32 **tp; /* State transition scores tp[from][to] (logs3 values) */ int32 bestscore; /* Best [emitting] state score in current frame (for pruning) */ } hmm_t; /* * Reset the states of the HMM to the invalid or inactive condition; i.e., scores to * LOGPROB_ZERO and hist to undefined. */ void hmm_clear (hmm_t *h, int32 n_emit_state); /* * Viterbi evaluation of given HMM. (NOTE that if this module were being used for tracking * state segmentations, the dummy, non-emitting exit state would have to be updated separately. * In the Viterbi DP diagram, transitions to the exit state occur from the current time; they * are vertical transitions. Hence they should be made only after the history has been logged * for the emitting states. But we're not bothered with state segmentations, for now. So, we * update the exit state as well.) * Hardwired for 5-state HMMs with topology shown above. * Return value: Best state score after evaluation. */ int32 hmm_vit_eval_5st (hmm_t *hmm, /* In/Out: HMM being updated */ s3senid_t *senid, /* In: Senone ID for each HMM state */ int32 *senscore); /* In: Senone scores, for all senones */ /* * Like hmm_vit_eval_5st, but hardwired for 3-state HMMs with topology shown above. * Return value: Best state score after evaluation. */ int32 hmm_vit_eval_3st (hmm_t *hmm, /* In/Out: HMM being updated */ s3senid_t *senid, /* In: Senone ID for each HMM state */ int32 *senscore); /* In: Senone scores, for all senones */ /* Like hmm_vit_eval, but dump HMM state and relevant senscr to fp first, for debugging */ int32 hmm_dump_vit_eval (hmm_t *hmm, int32 n_emit_state, s3senid_t *senid, int32 *senscr, FILE *fp); /* For debugging */ void hmm_dump (hmm_t *h, int32 n_emit_state, s3senid_t *senid, int32 *senscr, FILE *fp); #endif <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * Command line arguments for mk_mdef_gen * Derived from EHT's parse_cmd_ln routines * * Author: <NAME> *********************************************************************/ #include <s3/cmd_ln.h> #include "parse_cmd_ln.h" #include <stdlib.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <sys_compat/misc.h> #include <sys_compat/file.h> #include <stdio.h> #include <assert.h> void parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ (Copied from Rita's comment and I think it is a pretty good description.) \n\ Multi-function routine to generate mdef for context-independent \n\ training, untied training, and all-triphones mdef for state tying.\n\ Flow: \n\ if (triphonelist) make CI phone list and CD phone list \n\ if alltriphones mdef needed, make mdef \n\ if (rawphonelist) Make ci phone list, \n\ if cimdef needed, make mdef \n\ Generate alltriphones list from dictionary \n\ if alltriphones mdef needed, make mdef \n\ if neither triphonelist or rawphonelist quit \n\ Count triphones and triphone types in transcript \n\ Adjust threshold according to min-occ and maxtriphones \n\ Prune triphone list \n\ Make untied mdef \n\ \n\ Usually, this program is used in \n\ 1) generate CI mdef \n\ 2) generate CD mdef given dictionary and transcription \n\ 3) generate CD mdef given dictionary \n\ Also see examples"; const char examplestr[]= "Example: \n\ Create CI model definition file \n\ mk_mdef_gen -phnlstfn phonefile -ocimdef ci_mdeffile -n_state_pm 3\n\ \n\ Create untied CD model definition file given dictionary and transcription\n\ mk_mdef_gen -phnlstfn rawphonefile -dictfn dict -fdictfn filler_dict \n\ -lsnfn transcription -ountiedmdef untie_mdef -n_state_pm 3 \n\ -maxtriphones 10000 \n\ Create all CD model definition file given only the dictionary \n\ mk_mdef_gen -phnlstfn rawphone -oalltphnmdef untie_mdef -dictfn dict \n\ -fdictfn filler_dict -n_state_pm 3."; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-phnlstfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "List of phones"}, { "-inCImdef", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Input CI model definition file.\n\t\t\tIf given -phnlstfn ignored\n"}, { "-triphnlstfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A SPHINX-III triphone file name.\n\t\t\tIf given -phnlstfn, -incimdef ignored\n" }, { "-inCDmdef", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Input CD model definition file.\n\t\t\tIf given -triphnfn, -phnlstfn, -incimdef ignored\n"}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary"}, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Filler dictionary"}, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Transcripts file"}, { "-n_state_pm", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "3", "No. of states per HMM"}, { "-ocountfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output phone and triphone counts file"}, { "-ocimdef", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output CI model definition file"}, { "-oalltphnmdef", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output all triphone model definition file"}, { "-ountiedmdef", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output untied model definition file"}, { "-minocc", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "Min occurances of a triphone must occur for inclusion in mdef file"}, { "-maxtriphones", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "100000", "Max. number of triphones desired in mdef file"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } } <file_sep>/SphinxTrain/src/programs/prunetree/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ Using prunetree, the bifurcations in the decision trees which \n\ resulted in the minimum increase in likelihood are progressively \n\ removed and replaced by the parent node. The selection of the \n\ branches to be pruned out is done across the entire collection of \n\ decision trees globally."; const char examplestr[] = "Example: \n\ \n\ prunetree \n\ -itreedir input_tree_dir \n\ -nseno 5000 \n\ -otreedir output_tree_dir \n\ -moddefn mdef \n\ -psetfn questions \n\ -minocc 100 "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "CI model definition file" }, { "-psetfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Phone set definition file" }, { "-itreedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Input tree directory" }, { "-otreedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output tree directory" }, { "-nseno", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of senones defined by the output trees"}, { "-minocc", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.0", "Prune nodes w/ fewer than this # of observations"}, { "-allphones", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Prune a single tree for each state of all phones"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2005/06/13 22:18:22 dhdfu * Add -allphones arguments to decision tree and state tying code. Allows senones to be shared across multiple base phones (though they are currently still restricted to the same state). This can improve implicit pronunciation modeling in some cases, such as grapheme-based models, though it usually has little effect. Building the big trees can take a very long time. * * Revision 1.5 2004/11/29 01:43:52 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.4 2004/11/29 01:11:36 egouvea * Fixed license terms in some new files. * * Revision 1.3 2004/11/29 00:49:23 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.2 2004/08/09 06:01:41 arthchan2003 * prunetree help and example * * Revision 1.1 2004/06/17 19:39:50 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcommon/ckd_alloc.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * file: ckd_alloc.c * * traceability: * * description: * * author: * *********************************************************************/ #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <stdio.h> #include <string.h> #include <stdlib.h> char *__ckd_salloc(char *string, char *caller_file, int caller_line) { char *out; out = malloc(strlen(string) + 1); if (out == NULL) { E_FATAL("malloc failed for string %s from %s(%d)\n", string, caller_file, caller_line); } strcpy(out, string); return out; } void *__ckd_calloc(size_t n_elem, size_t elem_size, char *caller_file, int caller_line) { void *mem; mem = calloc(n_elem, elem_size); if (mem == NULL) { E_FATAL("Calloc failed from %s(%d)\n", caller_file, caller_line); } return mem; } void *__ckd_malloc(size_t size, char *caller_file, int caller_line) { void *mem = malloc(size); if (mem == NULL) { E_FATAL("malloc failed %s(%d)\n", caller_file, caller_line); } return mem; } void *__ckd_realloc(void *ptr, size_t new_size, char *caller_file, int caller_line) { void *mem; mem = realloc(ptr, new_size); if (mem == NULL) { E_FATAL("realloc failed %s(%d)\n", caller_file, caller_line); } return mem; } void __ckd_free(void *ptr, char *file, int line) { free(ptr); } void ** __ckd_calloc_2d(size_t d1, size_t d2, size_t elem_size, char *file, int line) { void *store; void **out; size_t i, j; store = calloc(d1 * d2, elem_size); if (store == NULL) { E_FATAL("ckd_calloc_2d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } out = calloc(d1, sizeof(void *)); if (out == NULL) { E_FATAL("ckd_calloc_2d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &((char *)store)[j*elem_size]; } return out; } void __ckd_free_2d(void **arr, char *file, int line) { if (arr == NULL) return; __ckd_free(arr[0], file, line); __ckd_free(arr, file, line); } void *** __ckd_calloc_3d(size_t d1, size_t d2, size_t d3, size_t elem_size, char *file, int line) { void *store; void **tmp1; void ***out; size_t i, j; store = calloc(d1 * d2 * d3, elem_size); if (store == NULL) { E_FATAL("ckd_calloc_3d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } tmp1 = calloc(d1 * d2, sizeof(void *)); if (tmp1 == NULL) { E_FATAL("ckd_calloc_3d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } out = calloc(d1, sizeof(void **)); if (out == NULL) { E_FATAL("ckd_calloc_3d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } for (i = 0, j = 0; i < d1*d2; i++, j += d3) { tmp1[i] = &((char *)store)[j*elem_size]; } for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &tmp1[j]; } return out; } void __ckd_free_3d(void ***arr, char *file, int line) { if (arr == NULL) return; __ckd_free(arr[0][0], file, line); __ckd_free(arr[0], file, line); __ckd_free(arr, file, line); } void **** __ckd_calloc_4d(size_t d1, size_t d2, size_t d3, size_t d4, size_t elem_size, char *file, int line) { void *store; void **tmp1; void ***tmp2; void ****out; size_t i, j; store = calloc(d1 * d2 * d3 * d4, elem_size); if (store == NULL) { E_FATAL("ckd_calloc_4d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } tmp1 = calloc(d1 * d2 * d3, sizeof(void *)); if (tmp1 == NULL) { E_FATAL("ckd_calloc_4d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } tmp2 = ckd_calloc(d1 * d2, sizeof(void **)); if (tmp2 == NULL) { E_FATAL("ckd_calloc_4d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } out = ckd_calloc(d1, sizeof(void ***)); if (out == NULL) { E_FATAL("ckd_calloc_4d failed for caller at %s(%d) at %s(%d)\n", file, line, __FILE__, __LINE__); } for (i = 0, j = 0; i < d1*d2*d3; i++, j += d4) { tmp1[i] = &((char *)store)[j*elem_size]; } for (i = 0, j = 0; i < d1*d2; i++, j += d3) { tmp2[i] = &tmp1[j]; } for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &tmp2[j]; } return out; } void __ckd_free_4d(void ****arr, char *file, int line) { if (arr == NULL) return; /* free the underlying store */ __ckd_free(arr[0][0][0], file, line); /* free the access overhead */ __ckd_free(arr[0][0], file, line); __ckd_free(arr[0], file, line); __ckd_free(arr, file, line); } /* Layers a 3d array access structure over a preallocated storage area */ void *** __ckd_alloc_3d_ptr(int d1, int d2, int d3, void *store, size_t elem_size, char *file, int line) { void **tmp1; void ***out; int i, j; tmp1 = __ckd_calloc(d1 * d2, sizeof(void *), file, line); out = __ckd_calloc(d1, sizeof(void **), file, line); for (i = 0, j = 0; i < d1*d2; i++, j += d3) { tmp1[i] = &((char *)store)[j*elem_size]; } for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &tmp1[j]; } return out; } void ** __ckd_alloc_2d_ptr(int d1, int d2, void *store, size_t elem_size, char *file, int line) { void **out; int i, j; out = (void **)__ckd_calloc(d1, sizeof(void *), file, line); for (i = 0, j = 0; i < d1; i++, j += d2) { out[i] = &((char *)store)[j*elem_size]; } return out; } /* * Log record. Maintained by CVS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 96/06/17 14:30:51 eht * Added allocation functions for multidimensioned arrays * * Revision 1.6 1996/03/06 20:33:56 eht * Include some function prototypes * * Revision 1.5 1996/02/02 17:49:04 eht * Add ckd_salloc() function. * * Revision 1.4 1995/10/09 15:02:03 eht * Changed ckd_alloc interface to get rid of __FILE__, __LINE__ arguments * * Revision 1.3 1995/10/05 12:56:42 eht * Get rid of debugging stuff since there are malloc packages * out there that have tons of this stuff. * * Revision 1.2 1995/06/02 14:52:54 eht * Use pwp's error printing package * * Revision 1.1 1995/02/13 15:47:16 eht * Initial revision * * */ <file_sep>/CLP/src/Prons.cc //------------------------------------------------------------------------------------------- // Prons.cc //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #include <cstdlib> #include <fstream> #include <string> #include <cstdio> #include "Prons.h" #include "common_lattice.h" #include "LineSplitter.h" using namespace std; Prons::Prons(int s): size(s){}; Prons::Prons(const string& filename) { ifstream f; f.open(filename.c_str()); if(f == NULL) { char str[100]; cerr << "ERROR: ReadProns: The required file " << filename << "does not exist or is corupted !!"; size = 0; } else{ int2word.resize(MAX_VOC_SIZE); word_pron.resize(MAX_VOC_SIZE); word_no_prons.resize(MAX_VOC_SIZE); string s; unsigned widx = 0; while(getlineH(f,s)){ int pos1 = s.find(";"); assert(pos1 != string::npos); const string& wp = s.substr(0,pos1); // MOD 6/30/2000 - const added const string& pp = s.substr(pos1+1,string::npos); // MOD 6/30/2000 - const added int no_prons = atoi(pp.c_str()); int pos2 = wp.find("="); const string& word = wp.substr(0,pos2); // MOD 6/30/2000 - const added string pron; if (pos2+1 != string::npos) pron = wp.substr(pos2+1,string::npos); else pron = ""; word2int[word] = widx; int2word[widx] = word; word_pron[widx]= pron; word_no_prons[widx] = no_prons; widx++; } word2int[EPS] = widx; int2word[widx] = EPS; word_pron[widx]= ""; word_no_prons[widx] = 1; size = word2int.size(); f.sync(); } } // //////////////////////////////////////////////////////////////////////////// void Prons::add_word(const string& w) { word2int[w] = size; int2word[size] = w; word_no_prons[size] = DEFAULT_NO_PRONS; word_pron[size] = ""; size = word2int.size(); } // ////////////////////////////////////////////////////////////// int Prons::get_idx(const string& w){ if (word2int.find(w) == word2int.end()){ cerr << "The word " << w << " could not be found in your dictionary " << endl; add_word(w); } return word2int[w]; } // //////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const Prons& P) { os << "#" << endl << "#BEGIN no pron" << endl << "#" << endl; WordIntHMap& m = (WordIntHMap& )P.word2int; // MOD 6/30/2000 - cast added for (WordIntHMapIt ii = m.begin(); ii != m.end(); ii++) os << (*ii).first << "\t" << (*ii).second << "\t" << P.int2word[(*ii).second] << "\t" << P.word_pron[(*ii).second] << " no_prons: " << P.word_no_prons[(*ii).second] << endl; return os; } <file_sep>/SphinxTrain/src/libs/libcep_feat/agc_emax.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: agc_emax.c * * Description: * Approximates the agc_max algorithm using a running estimate * of the max c[0] value. The estimate of the max decays over * time to cope with changing signal power. * * Author: * faa *********************************************************************/ #include <s3/agc_emax.h> #include <s3/prim_type.h> #include <string.h> int agc_emax_proc (float32 *ocep, /* ouput cepstrum frame */ float32 *icep, /* input cepstrum frame */ uint32 cf_cnt) /* Number of coeff's per frame */ { static float64 target_max = 1.0; static float64 max = 1.0; static float64 delta_max = 0.0; static float64 decay = 1.0/3000; static float64 min_max = -0.5; if (icep[0] > target_max) { target_max = icep[0]; if (delta_max < ((target_max - max) / 100.0)) delta_max = ((target_max - max) / 100.0); } if (target_max >= max) { max += delta_max; } else { if (target_max > min_max) target_max -= decay; if (max > min_max) max -= decay; } icep[0] -= max; memcpy((char *)ocep, (char *)icep, sizeof(float)*cf_cnt); return 1; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.3 1995/10/17 13:05:04 eht * Cleaned up code a bit so that it is more ANSI compliant * * Revision 1.2 1995/10/10 12:36:12 eht * Changed to use <s3/prim_type.h> * * Revision 1.1 1995/06/02 20:57:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3.2/src/libutil/case.h /* * case.h -- Upper/lower case conversion routines * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 18-Jun-97 <NAME> (<EMAIL>) at Carnegie Mellon * Added strcmp_nocase, UPPER_CASE and LOWER_CASE definitions. * * 16-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #ifndef _LIBUTIL_CASE_H_ #define _LIBUTIL_CASE_H_ #include "prim_type.h" /* Return upper case form for c */ #define UPPER_CASE(c) ((((c) >= 'a') && ((c) <= 'z')) ? (c-32) : c) /* Return lower case form for c */ #define LOWER_CASE(c) ((((c) >= 'A') && ((c) <= 'Z')) ? (c+32) : c) /* Convert str to all upper case */ void ucase(char *str); /* Convert str to all lower case */ void lcase(char *str); /* * Case insensitive string compare. Return the usual -1, 0, +1, depending on * str1 <, =, > str2 (case insensitive, of course). */ int32 strcmp_nocase (const char *str1, const char *str2); #endif <file_sep>/CLP/include/common.h // -*- C++ -*- #ifndef _common_h_ #define _common_h_ #include <cassert> #include <iostream> #include <iomanip> #include <fstream> #include <cstdlib> #include <climits> #include <string> #include <cmath> using namespace std; int getlineH(istream&, string&); string itoa(int); #endif <file_sep>/CLP/scripts/sausage2fst.py #!/usr/bin/env python # Copyright (c) 2010 Carnegie Mellon University # # You may copy and modify this freely under the same terms as # Sphinx-III """ Convert sausages from confusion network code to OpenFST files """ __author__ = "<NAME> <<EMAIL>>" __version__ = "$Revision$" import openfst import collections import fileinput import itertools import math import sys def fstcompile(infile): fst = openfst.StdVectorFst() symtab = openfst.SymbolTable("symbols") symtab.AddSymbol("&epsilon;") statemap = collections.defaultdict(fst.AddState) for spam in infile: fields = spam.strip().split() if len(fields) == 1: fst.SetFinal(int(fields[0]), 0) elif len(fields) == 2: fst.SetFinal(int(fields[0]), float(fields[1])) elif len(fields) > 2: if len(fields) > 3: prob = float(fields[3]) else: prob = 1.0 if fields[2] == 'eps': fields[2] = '&epsilon;' sym = symtab.AddSymbol(fields[2]) src = statemap[fields[0]] dest = statemap[fields[1]] fst.AddArc(src, sym, sym, -math.log(prob), dest) fst.SetStart(0) fst.SetInputSymbols(symtab) fst.SetOutputSymbols(symtab) return fst if __name__ == "__main__": from optparse import OptionParser optparse = OptionParser(usage="%prog [SAUSAGE]") optparse.add_option("-o", "--outfile") opts, args = optparse.parse_args(sys.argv[1:]) fst = fstcompile(fileinput.input(args)) if opts.outfile: fst.Write(opts.outfile) <file_sep>/SphinxTrain/python/cmusphinx/sendump.py #!/usr/bin/env python import sys import s3mixw import struct import numpy def usage(): print "Usage: %s IN_SENDUMP OUT_MIXW" % sys.argv[0] def readstr(fh): nbytes = struct.unpack('I', fh.read(4))[0] if nbytes == 0: return None else: return fh.read(nbytes) if len(sys.argv) < 3: usage() sys.exit(2) sendump = open(sys.argv[1]) title = readstr(sendump) while True: header = readstr(sendump) if header == None: break # Number of codewords and pdfs r, c = struct.unpack('II', sendump.read(8)) print "rows: %d, columns: %d" % (r,c) # Now read the stuff opdf_8b = numpy.empty((c,4,r)) for i in range(0,4): for j in range(0,r): # Read bytes, expand to ints, shift them up mixw = numpy.fromfile(sendump, 'B', c).astype('i') << 10 # Negate, exponentiate, and untranspose opdf_8b[:,i,j] = numpy.power(1.0001, -mixw) s3mixw.open(sys.argv[2], 'wb').writeall(opdf_8b) <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/mk_untied.h /* ==================================================================== * Copyright (c) 2000 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef MK_UNTIED_H #define MK_UNTIED_H #include <s3/s3.h> #include "heap.h" #include "hash.h" int32 make_ci_list_frm_mdef(char *mdeffile, char ***CIlist, int32 *cilistsize); int32 make_ci_list_cd_hash_frm_phnlist(char *phnlist, char ***CIlist, int32 *cilistsize, hashelement_t ***CDhash, int32 *NCDphones); int32 make_ci_list_cd_hash_frm_mdef(char *mdeffile, char ***CIlist, int32 *cilistsize, hashelement_t ***CDhash, int32 *NCDphones); int32 read_dict(char *dictfile, char *fillerdictfile, dicthashelement_t ***dicthash); int32 make_mdef_from_list(char *mdeffile, char **CIlist, int32 cilistsize, heapelement_t **CDheap, int32 cdheapsize, char *pgm); int32 make_dict_triphone_list (dicthashelement_t **dicthash, hashelement_t ***triphonehash); int32 make_CD_heap(hashelement_t **triphonehash, int32 threshold, heapelement_t ***CDheap, int32 *cdheapsize); int32 find_threshold(hashelement_t **triphonehash); int32 count_triphones (char *transfile, dicthashelement_t **dicthash, hashelement_t **tphnhash, phnhashelement_t ***CIhash); int32 print_counts(char *countfn, phnhashelement_t **CIhash, hashelement_t **CDhash); #endif <file_sep>/archive_s3/s3.0/src/libmain/tmat.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * tmat.h * * * HISTORY * * 11-Mar-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started based on original S3 implementation. */ #ifndef _LIBMAIN_TMAT_H_ #define _LIBMAIN_TMAT_H_ #include "s3types.h" /* * Transition matrix data structure. All phone HMMs are assumed to have the same * topology. */ typedef struct { int32 ***tp; /* The transition matrices; int32 since probs in logs3 domain: tp[tmatid][from-state][to-state] */ int32 n_tmat; /* #matrices */ int32 n_state; /* #source states in matrix (only the emitting states); #destination states = n_state+1, it includes the exit state */ } tmat_t; tmat_t *tmat_init (char *tmatfile, /* In: input file */ float64 tpfloor); /* In: floor value for each non-zero transition probability */ #endif <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/actionproviders/GraphEditProvider.java package edu.cmu.sphinx.tools.confdesigner.actionproviders; import edu.cmu.sphinx.tools.confdesigner.ConfNodeWidget; import org.netbeans.api.visual.action.EditProvider; import org.netbeans.api.visual.widget.Widget; import javax.swing.*; /** * DOCUMENT ME! * * @author <NAME> */ public class GraphEditProvider implements EditProvider { public void edit(Widget widget) { if(!(widget instanceof ConfNodeWidget)) return; ConfNodeWidget nodeWidget = (ConfNodeWidget) widget; String s = JOptionPane.showInputDialog("Pleas enter new component name:", nodeWidget.getLabelWidget().getLabel()); if (s != null && !s.equals("")) nodeWidget.setLabel(s); } } <file_sep>/SphinxTrain/src/programs/cdcn_train/main.c /* ==================================================================== * Copyright (c) 1994-2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /****************************************************************************** * Main routine for computing the distribution for CDCN. * Coded by <NAME>, June 94 ******************************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include "header.h" #include "parse_cmd_ln.h" int main(int argc, char **argv) { vector_t *vector, *buff; float **mean, **variance, *c; float noisec, noisemean[64], noisevar[64]; float atemp, noise_threshold, noise_width; int numnoise, numspch, numvecs, Ndim, Nmodes; int maxframes, vector_alloc; int i, j, k, *nbin, *bin; int superiter, stride; uint32 length, x; parse_cmd_ln(argc, argv); Ndim = cmd_ln_int32("-ceplen"); Nmodes = cmd_ln_int32("-nmodes"); stride = cmd_ln_int32("-stride"); maxframes = cmd_ln_int32("-maxframes"); noise_width = cmd_ln_float32("-noisewidth"); /* FIXME: this will break when we have terabytes of memory... */ if (maxframes == -1) maxframes = INT_MAX; /* * by default I assume the programs is to be run from data * only with no initial set of Gaussians. i.e. go to vq and them * em. */ corpus_set_mfcc_dir(cmd_ln_str("-cepdir")); corpus_set_mfcc_ext(cmd_ln_str("-cepext")); if (corpus_set_ctl_filename(cmd_ln_str("-ctlfn")) != S3_SUCCESS) E_FATAL("Failed to read control file %s\n", cmd_ln_str("-ctlfn")); if (corpus_init() != S3_SUCCESS) E_FATAL("Corpus initialization failed\n"); numvecs = 0; numnoise = 0; for (j = 0; j < Ndim; ++j) { noisemean[j] = 0; noisevar[j] = 0; } /* Read in all frames (you can set a maximum to avoid dying) */ /* Pick a reasonable size (about 60MB) to start with. */ E_INFO("Allocating 100000 frames initially\n"); vector_alloc = 1000000; vector = (vector_t *) ckd_calloc_2d(vector_alloc, Ndim, sizeof(float)); E_INFO("Reading frames... "); while (corpus_next_utt() && (numvecs < maxframes)) { corpus_get_generic_featurevec(&buff, &length, Ndim); for (x = 0; x < length; x += stride) { if (numvecs >= vector_alloc) { vector_alloc = numvecs + 1000000; E_INFOCONT(" (Reallocating to %d frames) ", vector_alloc); vector = ckd_realloc(vector, sizeof(vector_t *) * vector_alloc); vector[0] = ckd_realloc(vector[0], Ndim*sizeof(float)*vector_alloc); for (j = 1; j < vector_alloc; ++j) vector[j] = vector[0] + j * Ndim; } memcpy(vector[numvecs], buff[x], Ndim*sizeof(float)); ++numvecs; } free(buff[0]); ckd_free(buff); } E_INFOCONT("%d vectors in all\n", numvecs); if (numvecs == 0) E_FATAL(("This is silly! You have given me only 0 vectors to compute a DISTRIBUTION!\nI am miffed! I am quitting!\n")); /* * Compute threshold for the noise mode as the minimum c[0] + thresholding */ noise_threshold = vector[0][0]; for (i = 0; i < numvecs; ++i) if (vector[i][0] < noise_threshold) noise_threshold = vector[i][0]; noise_threshold += noise_width; E_INFO("Noise threshold = %f\n", noise_threshold); numnoise = 0; numspch = 0; for (i = 0; i < numvecs; ++i) { if (vector[i][0] <= noise_threshold) { for (j = 0; j < Ndim; ++j) { noisemean[j] += vector[i][j]; noisevar[j] += vector[i][j] * vector[i][j]; } ++numnoise; } else { for (j = 0; j < Ndim; ++j) vector[numspch][j] = vector[i][j]; ++numspch; } } E_INFO ("%d vectors found below noise threshold %f, %d vectors found above it\n", numnoise, noise_threshold, numspch); /* * Compute noise statistics */ for (j = 0; j < Ndim; ++j) { noisemean[j] /= (float) numnoise; noisevar[j] = noisevar[j] / (float) numnoise - noisemean[j] * noisemean[j]; } noisec = (float) numnoise / (float) numvecs; Nmodes -= 1; /* ACCOUNT FOR NOISE MODE : Rest of modes = total modes-1 */ /* * We Vector Quantize to obtain the initial values for the EM. * If this codebook already exists, we skip the VQ and directly * compute the variances and c[]s after obtaining the mean values * as the code words in the existing codebook */ /* * do this only if we are not requesting a restart from a previous * temp statistics file . */ if (cmd_ln_str("-cbfn") == NULL) { /* * allocate the mean and variance and c arrays. */ c = (float *) ckd_calloc(Nmodes, sizeof(float)); mean = (float **) ckd_calloc_2d(Nmodes, Ndim, sizeof(float)); variance = (float **) ckd_calloc_2d(Nmodes, Ndim, sizeof(float)); nbin = (int *) ckd_calloc(Nmodes, sizeof(int)); /* no of vectors in a mode */ /* * The vector_quantize routine performs VQ with a mahalonobis metric * and returns the codes as the means and the wieghts as the variances * of the initial estimates of the modes, which will further be * employed in EM. Note that the variances are purely diagonal * We initialize all initial c[] to be equal */ bin = (int *) ckd_calloc(numspch, sizeof(int)); vector_quantize(mean, Nmodes, vector, numspch, Ndim, bin, cmd_ln_int32("-vqiter"), cmd_ln_float32("-vqthresh")); for (i = 0; i < Nmodes; ++i) c[i] = 1.0 / (float) Nmodes; for (k = 0; k < Nmodes; ++k) { nbin[k] = 0; for (i = 0; i < Ndim; ++i) variance[k][i] = 0; } for (i = 0; i < numspch; ++i) { for (j = 0; j < Ndim; ++j) { atemp = (vector[i][j] - mean[bin[i]][j]); variance[bin[i]][j] += atemp * atemp; } ++nbin[bin[i]]; } for (k = 0; k < Nmodes; ++k) { for (j = 0; j < Ndim; ++j) variance[k][j] /= nbin[k]; } ckd_free(bin); /* We do not need this array anymore */ ckd_free(nbin); /* Chappie not needed anymore */ } else { /* * if initialize = 0 ===> I want to skip the VQ and go to EM * straight */ if (!read_backup_distribution (cmd_ln_str("-cbfn"), &mean, &variance, &c, &Nmodes, Ndim)) E_FATAL(("Unable to read initial distribution\n")); } for (superiter = 0; superiter < 1; ++superiter) { estimate_multi_modals(vector, numspch, Ndim, Nmodes, mean, variance, c, cmd_ln_str("-tmpfn"), cmd_ln_int32("-emiter"), cmd_ln_float32("-emthresh")); if (store_distribution (cmd_ln_str("-outfn"), Nmodes, Ndim, noisec, noisemean, noisevar, c, mean, variance) != 0) { E_FATAL("Unable to open %s to store distribution\n", cmd_ln_str("-tmpfn")); } } ckd_free_2d((void **)vector); ckd_free(c); ckd_free_2d((void **)mean); ckd_free_2d((void **)variance); return 0; } <file_sep>/archive_s3/s3.0/exp/gauden/gausubvq.c /* * gausubvq.c -- Sub-vector cluster Gaussian densities * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 09-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmain/gauden.h> static int32 **parse_subvecs (char *str) { char *strp; int32 n, n2, l; glist_t dimlist; /* List of dimensions in one subvector */ glist_t veclist; /* List of dimlists (subvectors) */ int32 **subvec; gnode_t *gn, *gn2; veclist = NULL; for (strp = str; *strp; ) { dimlist = NULL; for (;;) { if (sscanf (strp, "%d%n", &n, &l) != 1) E_FATAL ("'%s': Couldn't read int32 @pos %d\n", str, strp-str); strp += l; if (*strp == '-') { strp++; if (sscanf (strp, "%d%n", &n2, &l) != 1) E_FATAL ("'%s': Couldn't read int32 @pos %d\n", str, strp-str); strp += l; } else n2 = n; if ((n < 0) || (n > n2)) E_FATAL("'%s': Bad subrange spec ending @pos %d\n", str, strp-str); for (; n <= n2; n++) { if (glist_chkdup_int32 (dimlist, n)) E_FATAL("'%s': Duplicate dimension ending @pos %d\n", str, strp-str); dimlist = glist_add_int32 (dimlist, n); } if ((*strp == '\0') || (*strp == '/')) break; if (*strp != ',') E_FATAL("'%s': Bad delimiter @pos %d\n", str, strp-str); strp++; } veclist = glist_add_ptr (veclist, dimlist); if (*strp == '/') strp++; } /* Convert the glists to arrays; remember that the glists are in reverse order!! */ n = glist_count (veclist); /* #Subvectors */ subvec = (int32 **) ckd_calloc (n+1, sizeof(int32 *)); /* +1 for sentinel */ subvec[n] = NULL; for (--n, gn = veclist; (n >= 0) && gn; gn = gnode_next(gn), --n) { gn2 = (glist_t) gnode_ptr (gn); n2 = glist_count (gn2); /* Length of this subvector */ if (n2 <= 0) E_FATAL("'%s': 0-length subvector\n", str); subvec[n] = (int32 *) ckd_calloc (n2+1, sizeof(int32)); /* +1 for sentinel */ subvec[n][n2] = -1; for (--n2; (n2 >= 0) && gn2; gn2 = gnode_next(gn2), --n2) subvec[n][n2] = gnode_int32 (gn2); assert ((n2 < 0) && (! gn2)); } assert ((n < 0) && (! gn)); /* Free the glists */ for (gn = veclist; gn; gn = gnode_next(gn)) { gn2 = (glist_t) gnode_ptr(gn); glist_free (gn2); } glist_free (veclist); return subvec; } static void usagemsg (char *pgm) { fprintf (stderr, "Usage: %s \\\n", pgm); fprintf (stderr, "\tmeanfile \\\n"); fprintf (stderr, "\tvarfile \\\n"); fprintf (stderr, "\tsubvecs (e.g., 24,0-11/25,12-23/26,27-38) \\\n"); fprintf (stderr, "\tVQsize (#vectors) \\\n"); fprintf (stderr, "\teps (e.g. 0.001; stop if relative decrease in sqerror < epsilon \\\n"); fprintf (stderr, "\ttrials (#trials with different random initializations for each VQ \\\n"); fprintf (stderr, "\toutfile \\\n"); fprintf (stderr, "\t[skipvar]\n"); fflush (stderr); exit(0); } main (int32 argc, char *argv[]) { gauden_t *g; int32 **subvec; int32 i, j, n, m, c, s; int32 svsize, maxiter, maxtrial, trial; float32 **data, **vqmean, **b_vqmean; int32 *datamap, *vqmap, *b_vqmap; int32 vqsize, max_invec, skipvar; float32 epsilon; float64 sqerr, b_sqerr; FILE *fp; if ((argc != 8) && (argc != 9)) usagemsg (argv[0]); maxiter = 100; /* Default */ if ((sscanf (argv[4], "%d", &vqsize) != 1) || (vqsize <= 0)) E_FATAL("Bad VQsize argument: '%s'\n", argv[4]); if ((sscanf (argv[5], "%f", &epsilon) != 1) || (epsilon <= 0.0)) E_FATAL("Bad epsilon argument: '%s'\n", argv[5]); if ((sscanf (argv[6], "%d", &maxtrial) != 1) || (maxtrial <= 0)) E_FATAL("Bad trials argument: '%s'\n", argv[6]); skipvar = 0; if (argc > 8) { if (strcmp (argv[8], "skipvar") == 0) skipvar = 1; } if ((fp = fopen(argv[7], "w")) == NULL) E_FATAL("fopen(%s,w) failed\n", argv[7]); for (i = 0; i < argc-1; i++) fprintf (fp, "# %s \\\n", argv[i]); fprintf (fp, "# %s\n#\n", argv[argc-1]); logs3_init ((float64) 1.0003); /* Load means/vars but DO NOT precompute variance inverses or determinants */ g = gauden_init (argv[1], argv[2], 0.0 /* no varfloor */, FALSE); assert (g->n_feat == 1); gauden_var_nzvec_floor (g, 0.0001); /* Parse subvector spec argument; subvec is null terminated; subvec[x] is -1 terminated */ subvec = parse_subvecs (argv[3]); /* Print header */ for (s = 0; subvec[s]; s++); fprintf (fp, "VQParam %d %d -> %d %d\n", gauden_n_mgau(g), gauden_max_n_mean(g), s, vqsize); for (s = 0; subvec[s]; s++) { for (i = 0; subvec[s][i] >= 0; i++); fprintf (fp, "Subvector %d length %d ", s, i); for (i = 0; subvec[s][i] >= 0; i++) fprintf (fp, " %2d", subvec[s][i]); fprintf (fp, "\n"); } fflush (fp); /* * datamap[] for identifying non-0 input vectors that take part in the clustering process: * datamap[m*max_mean + c] = row index of data[][] containing the copy. * vqmap[] for mapping vq input data to vq output. */ max_invec = gauden_n_mgau(g) * gauden_max_n_mean(g); datamap = (int32 *) ckd_calloc (max_invec, sizeof(int32)); vqmap = (int32 *) ckd_calloc (max_invec, sizeof(int32)); b_vqmap = (int32 *) ckd_calloc (max_invec, sizeof(int32)); /* Copy and cluster each subvector */ for (s = 0; subvec[s]; s++) { E_INFO("Clustering subvector %d\n", s); /* Subvector length */ for (svsize = 0; subvec[s][svsize] >= 0; svsize++); /* Allocate input/output data areas and initialize maps */ data = (float32 **) ckd_calloc_2d (max_invec, svsize*2, sizeof(float32)); vqmean = (float32 **) ckd_calloc_2d (vqsize, svsize*2, sizeof(float32)); b_vqmean = (float32 **) ckd_calloc_2d (vqsize, svsize*2, sizeof(float32)); for (i = 0; i < max_invec; i++) datamap[i] = -1; /* Make a copy of the subvectors from the input data */ n = 0; for (m = 0; m < gauden_n_mgau(g); m++) { /* For each codebook */ assert (gauden_n_mean(g, m, 0) == gauden_n_var(g, m, 0)); for (c = 0; c < gauden_n_mean(g, m, 0); c++) { /* For each codeword */ if (vector_is_zero (g->mgau[m][0].var[c], g->featlen[0])) continue; for (i = 0; i < svsize; i++) { /* Copy the selected dimensions, mean and var */ data[n][i*2] = g->mgau[m][0].mean[c][subvec[s][i]]; data[n][i*2 + 1] = g->mgau[m][0].var[c][subvec[s][i]]; } datamap[m * gauden_max_n_mean(g) + c] = n; n++; } } /* * Make several VQ trials; each should be different since vector_vqgen begins with a * different random initialization each time. */ for (trial = 0; trial < maxtrial; trial++) { E_INFO("Trial %d\n", trial); E_INFO("Sanity check: data[0]:\n"); vector_print (stdout, data[0], svsize*2); for (i = 0; i < max_invec; i++) vqmap[i] = -1; #if 0 { int32 **in; printf ("Input data: %d x %d\n", n, svsize*2); in = (int32 **)data; for (i = 0; i < n; i++) { printf ("%8d:", i); for (j = 0; j < svsize*2; j++) printf (" %08x", in[i][j]); printf ("\n"); } for (i = 0; i < n; i++) { printf ("%15d:", i); for (j = 0; j < svsize*2; j++) printf (" %15.7e", data[i][j]); printf ("\n"); } fflush (stdout); } #endif /* VQ the subvector copy built above */ if (skipvar) sqerr = vector_vqgen2 (data, n, svsize*2, vqsize, epsilon, maxiter, vqmean, vqmap); else sqerr = vector_vqgen (data, n, svsize*2, vqsize, epsilon, maxiter, vqmean, vqmap); if ((trial == 0) || (sqerr < b_sqerr)) { b_sqerr = sqerr; memcpy (b_vqmap, vqmap, max_invec * sizeof(int32)); for (i = 0; i < vqsize; i++) memcpy (b_vqmean[i], vqmean[i], svsize*2 * sizeof(float32)); } } /* Output VQ */ fprintf (fp, "Codebook %d Sqerr %e\n", s, b_sqerr); for (m = 0; m < vqsize; m++) vector_print (fp, b_vqmean[m], svsize*2); fprintf (fp, "Map %d\n", s); for (i = 0; i < max_invec; i += gauden_max_n_mean(g)) { for (j = 0; j < gauden_max_n_mean(g); j++) { if (datamap[i+j] < 0) fprintf (fp, " -1"); else fprintf (fp, " %d", b_vqmap[datamap[i+j]]); } fprintf (fp, "\n"); } fflush (fp); /* Cleanup */ ckd_free_2d ((void **) data); ckd_free_2d ((void **) vqmean); ckd_free_2d ((void **) b_vqmean); } fprintf (fp, "End\n"); fclose (fp); exit(0); } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/SceneController.java package edu.cmu.sphinx.tools.confdesigner; import edu.cmu.sphinx.tools.confdesigner.util.SceneSerializer; import edu.cmu.sphinx.tools.executor.Executable; import edu.cmu.sphinx.tools.executor.ExecutorListener; import edu.cmu.sphinx.util.props.*; import org.netbeans.api.visual.widget.EventProcessingType; import javax.swing.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.Introspector; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * DOCUMENT ME! * * @author <NAME> */ public class SceneController { private ConfigurationManager cm; private ConfigScene scene; public static final String LAYOUT_SUFFIX = ".layout"; private List<ExecutorListener> executorListeners = new ArrayList<ExecutorListener>(); private boolean isChanged; public SceneController(ConfigScene scene) { scene.acceptProvider.setController(this); setScene(scene); setCm(new ConfigurationManager()); } public void setScene(final ConfigScene scene) { assert scene != null; this.scene = scene; JComponent sceneView = scene.getView(); sceneView.setFocusable(true); sceneView.setEnabled(true); scene.setKeyEventProcessingType(EventProcessingType.ALL_WIDGETS); sceneView.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DELETE) { scene.removeSelectedObjects(); } } }); // scene.addObjectSceneListener(new ObjectSceneListenerAdapter() { // // public void objectRemoved(ObjectSceneEvent event, Object removedObject) { // // Set<?> selectedObjects = scene.getSelectedObjects(); // // remove all selected nodes // for (Object selectedObject : selectedObjects.toArray()) { // if (selectedObject instanceof ConfNode) { // cm.removeConfigurable(((ConfNode) selectedObject).getInstanceName()); // } // } // } // }, ObjectSceneEventType.OBJECT_REMOVED); } public void save(File cmLocation) { ConfigurationManagerUtils.save(cm, cmLocation); SceneSerializer.saveLayout(getScene(), new File(cmLocation.getAbsolutePath() + LAYOUT_SUFFIX)); } public ConfigurationManager getCm() { return cm; } public void setCm(ConfigurationManager cm) { assert cm != null; if (this.cm != null) { for (ConfEdge edge : scene.getEdges().toArray(new ConfEdge[]{})) { scene.removeEdge(edge); } for (ConfNode confNode : scene.getNodes().toArray(new ConfNode[]{})) { scene.removeNode(confNode); } scene.validate(); } this.cm = cm; // remove all content from the graph and build up a new one new GraphLoader(this).loadScene(cm, executorListeners, cm.getComponentNames()); isChanged = false; cm.addConfigurationChangeListener(new ConfigurationChangeListener() { public void configurationChanged(String configurableName, String propertyName, ConfigurationManager cm) { PropertySheet ps = cm.getPropertySheet(configurableName); // handle graph rerouting PropertySheet.PropertyType type = ps.getType(propertyName); ConfNode confNode = scene.findNodeByName(configurableName); if (type.equals(PropertySheet.PropertyType.COMP)) { String propVal = (String) ps.getRaw(propertyName); ConfPin pin = confNode.getPin(propertyName); // remove the according edge if (propVal == null) { Collection<ConfEdge> confEdges = scene.findPinEdges(pin, false, true); assert confEdges.size() <= 1 : "more than one connection to a property pin won't define anything meaningful"; if (!confEdges.isEmpty()) scene.removeEdge(confEdges.iterator().next()); } else { // add a new graph connection // ConfNode sourceNode = scene.findNodeByName(propVal); // ConfPin sourcePin = sourceNode.getThisPin(); // // scene.addEdge(new ConfEdge(sourcePin, pin)); } } else if (type.equals(PropertySheet.PropertyType.COMPLIST)) { List<String> propList = (List<String>) ps.getRaw(propertyName); // // remove all edges which are not in the list List<ConfPin> listPins = confNode.getListPins(propertyName); for (ConfPin listPin : listPins) { Collection<ConfEdge> pinEdges = scene.findPinEdges(listPin, false, true); if (!pinEdges.isEmpty()) { ConfEdge edge = pinEdges.iterator().next(); String instanceName = scene.getPinNode(edge.getSource()).getInstanceName(); if (!propList.contains(instanceName)) { scene.removeEdge(edge); } } } scene.validate(); // ensure that there is at least one empty pin while (GraphLoader.getUnusedListPins(confNode, propertyName, scene).size() > 1) { List<ConfPin> unusedPins = GraphLoader.getUnusedListPins(confNode, propertyName, scene); ConfPin remPin = unusedPins.iterator().next(); confNode.revoveListPin(remPin); scene.removePin(remPin); // scene.validate(); } if (GraphLoader.getUnusedListPins(confNode, propertyName, scene).size() == 0) { List<ConfPin> pins = confNode.getListPins(propertyName); Class<? extends Configurable> classType = pins.iterator().next().getType(); confNode.addInputPin(scene, propertyName, pins.size() + 1, classType); } // ensure that listPins are numbered in increasing order listPins = confNode.getListPins(propertyName); for (int i = 0; i < listPins.size(); i++) { ConfPin confPin = listPins.get(i); confPin.setListPosition(i + 1); PortWidget widget = (PortWidget) scene.findWidget(confPin); widget.getLabelWidget().setLabel(confPin.toString()); } assert GraphLoader.getUnusedListPins(confNode, propertyName, scene).size() == 1; } scene.validate(); } public void componentAdded(ConfigurationManager cm, PropertySheet ps) { String configurableName = ps.getInstanceName(); addNode(cm.getPropertySheet(configurableName), configurableName); } public void componentRemoved(ConfigurationManager configurationManager, PropertySheet ps) { scene.removeNode((ConfNode) scene.findObject(scene.findWidgetByName(ps.getInstanceName()))); scene.validate(); if (ConfigurationManagerUtils.isImplementingInterface(ps.getConfigurableClass(), Executable.class)) { for (ExecutorListener executorListener : executorListeners) executorListener.removedExecutor(ps); } } public void componentRenamed(ConfigurationManager configurationManager, PropertySheet propertySheet, String oldName) { scene.validate(); // todo what could be done here? } }); scene.connectProvider.setCM(cm); scene.inplaceProvider.setCM(cm); } // add a new node which was not registered to the current configuration manager public String addNode(Class<? extends Configurable> confClass, String compName) { // create a new instance name if no name was given if (compName == null) { String[] strings = confClass.getName().split("[.]"); compName = Introspector.decapitalize(strings[strings.length - 1]); if (cm.getComponentNames().contains(compName)) { int counter = 1; while (cm.getComponentNames().contains(compName + counter)) counter++; compName += counter; } } cm.addConfigurable(confClass, compName); return compName; } public ConfNode addNode(PropertySheet propSheet, String compName) { ConfNode node = new ConfNode(compName, propSheet); scene.addNode(node); createPropertyPins(node, scene); if (ConfigurationManagerUtils.isImplementingInterface(propSheet.getConfigurableClass(), Executable.class)) { for (ExecutorListener executorListener : executorListeners) { executorListener.addedExecutor(propSheet); } } return node; } public void createPropertyPins(ConfNode node, ConfigScene scene) { PropertySheet ps = node.getPropSheet(); // create the connection pin which allows to connect this component to other components node.addOutputPin(scene, ps.getConfigurableClass()); // create all pins for (String propName : ps.getRegisteredProperties()) { PropertySheet.PropertyType propType = ps.getType(propName); Class<? extends Configurable> type; try { if (propType == PropertySheet.PropertyType.COMP) { type = ((S4Component) ps.getProperty(propName, S4Component.class).getAnnotation()).type(); node.addInputPin(scene, propName, type); } else if (propType == PropertySheet.PropertyType.COMPLIST) { type = ((S4ComponentList) ps.getProperty(propName, S4ComponentList.class).getAnnotation()).type(); node.addInputPin(scene, propName, 1, type); } } catch (PropertyException e) { e.printStackTrace(); } } } /** Adds a new listener. */ public void addExecutorListener(ExecutorListener l) { if (l == null) return; executorListeners.add(l); } /** Removes a listener. */ public void removeExecutorListener(ExecutorListener l) { if (l == null) return; executorListeners.remove(l); } public void setCm(File cmLocation) { try { if (cmLocation == null) setCm(new ConfigurationManager()); else { setCm(new ConfigurationManager(cmLocation.toURI().toURL())); File layoutFile = new File(cmLocation.getAbsolutePath() + LAYOUT_SUFFIX); if (layoutFile.isFile()) SceneSerializer.loadLayout(getScene(), layoutFile); } } catch (IOException e) { e.printStackTrace(); } catch (PropertyException e) { e.printStackTrace(); } } public ConfigScene getScene() { return scene; } } <file_sep>/SphinxTrain/include/s3/clapack_lite.h #ifndef __CLAPACK_LITE_H #define __CLAPACK_LITE_H #include <s3/f2c.h> /* Subroutine */ int sgesv_(integer *n, integer *nrhs, real *a, integer *lda, integer *ipiv, real *b, integer *ldb, integer *info); /* Subroutine */ int ssyevd_(char *jobz, char *uplo, integer *n, real *a, integer *lda, real *w, real *work, integer *lwork, integer *iwork, integer *liwork, integer *info); /* Subroutine */ int sgelsd_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, real *b, integer *ldb, real *s, real *rcond, integer * rank, real *work, integer *lwork, integer *iwork, integer *info); /* Subroutine */ int sgetrf_(integer *m, integer *n, real *a, integer *lda, integer *ipiv, integer *info); /* Subroutine */ int spotrf_(char *uplo, integer *n, real *a, integer *lda, integer *info); /* Subroutine */ int sgesdd_(char *jobz, integer *m, integer *n, real *a, integer *lda, real *s, real *u, integer *ldu, real *vt, integer *ldvt, real *work, integer *lwork, integer *iwork, integer *info); /* Subroutine */ int sgeev_(char *jobvl, char *jobvr, integer * n, real * a, integer * lda, real * wr, real * wi, real * vl, integer * ldvl, real * vr, integer * ldvr, real * work, integer * lwork, integer * info); #endif /* __CLAPACK_LITE_H */ <file_sep>/SphinxTrain/src/libs/libcep_feat/s2_ddcep.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_ddcep.c * * Description: * Computes the 2nd order difference cepstrum: * ddcep: < dcep[t+1] - dcep[t-1] > * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include "s2_ddcep.h" #include <s3/s2_param.h> #include <string.h> static uint32 veclen = 13; void s2_ddcep_set_veclen(uint32 l) { veclen = l; } void s2_sec_ord_dcep_frame(vector_t ddcep, vector_t power, vector_t *mfcc) { int32 w; int32 k; float32 d1; float32 d2; w = S2_SHORT_DIFFW; /* diff cep + 1 */ d1 = mfcc[w + 1][0] - mfcc[-w + 1][0]; /* diff cep - 1 */ d2 = mfcc[-1 + w][0] - mfcc[-1 - w][0]; power[2] = d1 - d2; for (k = 1; k < veclen; k++) { d1 = mfcc[w + 1][k] - mfcc[-w + 1][k]; d2 = mfcc[w - 1][k] - mfcc[-w - 1][k]; ddcep[k-1] = d1 - d2; } } void s2_sec_ord_dcep_feat(vector_t **out, vector_t *mfcc, uint32 n_frame) { uint32 i, k; /* compute the long duration diff cepstrum */ for (i = S2_2ND_ORD_DIFFW; i < n_frame - S2_2ND_ORD_DIFFW; i++) { s2_sec_ord_dcep_frame(out[i][S2_2DCEP_FEATURE], out[i][S2_POW_FEATURE], &mfcc[i]); } for (i = 0; i < S2_2ND_ORD_DIFFW; i++) { out[i][S2_POW_FEATURE][2] = out[S2_2ND_ORD_DIFFW][S2_POW_FEATURE][2]; memcpy(out[i][S2_2DCEP_FEATURE], out[S2_2ND_ORD_DIFFW][S2_2DCEP_FEATURE], sizeof(float32) * (veclen-1)); } for (i = n_frame-1, k = n_frame - S2_2ND_ORD_DIFFW - 1; i >= n_frame - S2_2ND_ORD_DIFFW; i--) { out[i][S2_POW_FEATURE][2] = out[k][S2_POW_FEATURE][2]; memcpy(out[i][S2_2DCEP_FEATURE], out[k][S2_2DCEP_FEATURE], sizeof(float32) * (veclen-1)); } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.3 1996/08/05 12:53:10 eht * Include <string.h> for prototype * * Revision 1.2 1996/03/25 15:36:31 eht * Changes to allow for settable input feature length * * Revision 1.1 1995/12/14 20:12:58 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcommon/two_class.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: two_class.c * * Description: * * Author: * *********************************************************************/ #include <s3/two_class.h> #include <s3/ckd_alloc.h> #include <s3/enum_subset.h> #include <s3/metric.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/cmd_ln.h> #include <s3/div.h> #include <string.h> float64 two_class(float32 ****mixw_occ, /* ADDITION FOR CONTINUOUS_TREES */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_dist, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 *bclust, float32 mwfloor) { uint32 *clust; uint32 *set; float32 **a_dist; float32 **b_dist; float32 ***m_dist; float64 einc, b_einc; float64 norm; float64 a_wt, b_wt; uint32 i, s, j, k, l; /* ADDITION FOR CONTINUOUS_TREES */ float32 ***m_means=0; float32 ***m_vars=0; float32 **a_means=0; float32 **a_vars=0; float32 **b_means=0; float32 **b_vars=0; float32 varfloor=0; float64 root_ent=0; float64 a_ent; float64 b_ent; char* type; uint32 continuous,sumveclen=0; type = (char *)cmd_ln_access("-ts2cbfn"); if (strcmp(type,".semi.")!=0 && strcmp(type,".cont.") != 0) E_FATAL("Type %s unsupported; trees can only be built on types .semi. or .cont.\n",type); if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; if (continuous == 1) { varfloor = *(float32 *)cmd_ln_access("-varfloor"); for(i=0,sumveclen=0; i < n_stream; i++) sumveclen += veclen[i]; m_means = (float32 ***)ckd_calloc_3d(n_state, n_stream, sumveclen, sizeof(float32)); m_vars = (float32 ***)ckd_calloc_3d(n_state, n_stream, sumveclen, sizeof(float32)); a_means = (float32 **)ckd_calloc_2d(n_stream, sumveclen, sizeof(float32)); a_vars = (float32 **)ckd_calloc_2d(n_stream, sumveclen, sizeof(float32)); b_means = (float32 **)ckd_calloc_2d(n_stream, sumveclen, sizeof(float32)); b_vars = (float32 **)ckd_calloc_2d(n_stream, sumveclen, sizeof(float32)); root_ent = 0; } /* END OF ADDITIONS FOR CONTINUOUS_TREES */ clust = ckd_calloc(n_dist, sizeof(uint32)); set = ckd_calloc(n_dist-1, sizeof(uint32)); m_dist = (float32 ***)ckd_calloc_3d(n_state, n_stream, n_density, sizeof(float32)); /* Create 1-class merged distribution */ for (s = 0; s < n_state; s++) { for (i = 0; i < n_dist; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { m_dist[s][j][k] += mixw_occ[i][s][j][k]; } } } /* ADDITION FOR CONTINUOUS_TREES FOR THE CONTINUOUS CASE */ if (continuous == 1) { for (i = 0; i < n_dist; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < veclen[j]; k++) { m_means[s][j][k] += mixw_occ[i][s][j][0] * means[i][s][j][k]; m_vars[s][j][k] += mixw_occ[i][s][j][0] * (vars[i][s][j][k] + means[i][s][j][k]*means[i][s][j][k]); } } } } /* END ADDITION FOR CONTINUOUS_TREES */ for (k = 0, norm = 0; k < n_density; k++) { norm += m_dist[s][0][k]; } norm = 1.0 / norm; for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { m_dist[s][j][k] *= norm; if (m_dist[s][j][k] < mwfloor) m_dist[s][j][k] = mwfloor; } } /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { for (j = 0; j < n_stream; j++) { for (k = 0; k < veclen[j]; k++) { m_means[s][j][k] *= norm; m_vars[s][j][k] = m_vars[s][j][k]*norm - m_means[s][j][k]*m_means[s][j][k]; if (m_vars[s][j][k] < varfloor) m_vars[s][j][k] = varfloor; } /* 1 / norm is the count */ root_ent += (1.0/norm) * (float64)stwt[s] * ent_cont(m_means[s][j],m_vars[s][j],veclen[j]); } } /* END ADDITION FOR CONTINUOUS_TREES */ } a_dist = (float32 **)ckd_calloc_2d(n_stream, n_density, sizeof(float32)); b_dist = (float32 **)ckd_calloc_2d(n_stream, n_density, sizeof(float32)); /* * Explore all subsets S of length 1 .. (n_dist-1) * * dist i in S => class A * dist i not in S => class B */ for (i = 1, b_einc = -1.0e+50; i < n_dist; i++) { /* Generate the initial subset definition [0..i-1] */ for (j = 0; j < i; j++) { set[j] = j; } /* Check all subsets of length(i) */ do { for (j = 0; j < i; j++) { clust[set[j]] = TRUE; } for (s = 0, einc = 0; s < n_state; s++) { /* Given cluster definition, create A and B distributions */ for (j = 0; j < n_dist; j++) { if (clust[j]) { for (k = 0; k < n_stream; k++) { for (l = 0; l < n_density; l++) { a_dist[k][l] += mixw_occ[j][s][k][l]; } } } else { for (k = 0; k < n_stream; k++) { for (l = 0; l < n_density; l++) { b_dist[k][l] += mixw_occ[j][s][k][l]; } } } /* ADDITIONS FOR CONTINUOUS_TREES to handle continuous HMMs */ if (continuous == 1) { if (clust[j]) { for (k = 0; k < n_stream; k++) { for (l = 0; l < veclen[k]; l++) { a_means[k][l] += mixw_occ[j][s][k][0] * means[j][s][k][l]; a_vars[k][l] += mixw_occ[j][s][k][0] * (vars[j][s][k][l] + means[j][s][k][l]*means[j][s][k][l]); } } } else { for (k = 0; k < n_stream; k++) { for (l = 0; l < veclen[k]; l++) { b_means[k][l] += mixw_occ[j][s][k][0] * means[j][s][k][l]; b_vars[k][l] += mixw_occ[j][s][k][0] * (vars[j][s][k][l] + means[j][s][k][l]*means[j][s][k][l]); } } } } /* END ADDITIONS FOR CONTINUOUS_TREES */ } for (l = 0, a_wt = 0; l < n_density; l++) { a_wt += a_dist[0][l]; } norm = 1.0 / a_wt; for (k = 0; k < n_stream; k++) { for (l = 0; l < n_density; l++) { a_dist[k][l] *= norm; } } /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { a_ent = 0; for (k = 0; k < n_stream; k++) { for (l = 0; l < veclen[k]; l++) { a_means[k][l] *= norm; a_vars[k][l] *= norm; a_vars[k][l] -= a_means[k][l]*a_means[k][l]; if (a_vars[k][l] < varfloor) a_vars[k][l] = varfloor; } a_ent += ent_cont(a_means[k],a_vars[k],veclen[k]); } a_ent *= a_wt; einc += (float64)stwt[s] * a_ent; } /* END ADDITION FOR CONTINUOUS_TREES */ for (k = 0, b_wt = 0; k < n_density; k++) { b_wt += b_dist[0][k]; } norm = 1.0 / b_wt; for (k = 0; k < n_stream; k++) { for (l = 0; l < n_density; l++) { b_dist[k][l] *= norm; } } /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { b_ent = 0; for (k = 0; k < n_stream; k++) { for (l = 0; l < veclen[k]; l++) { b_means[k][l] *= norm; b_vars[k][l] *= norm; b_vars[k][l] -= b_means[k][l]*b_means[k][l]; if (b_vars[k][l] < varfloor) b_vars[k][l] = varfloor; } b_ent += ent_cont(b_means[k],b_vars[k],veclen[k]); } b_ent *= b_wt; einc += (float64)stwt[s] * b_ent; } /* END ADDITION FOR CONTINUOUS_TREES */ /* MODIFICATION FOR CONTINUOUS_TREES - Handle for continuous HMMs */ /* Compute the weighted entropy increase of merging the two clusters */ if (continuous != 1) { einc += (float64)stwt[s] * wt_ent_inc(a_dist, a_wt, b_dist, b_wt, m_dist[s], n_stream, n_density); } /* END MODIFICATION FOR CONTINUOUS_TREES */ /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { memset(&a_means[0][0], 0, sizeof(float32) * n_stream * sumveclen); memset(&a_vars[0][0], 0, sizeof(float32) * n_stream * sumveclen); memset(&b_means[0][0], 0, sizeof(float32) * n_stream * sumveclen); memset(&b_vars[0][0], 0, sizeof(float32) * n_stream * sumveclen); } /* END ADDITION FOR CONTINUOUS_TREES */ memset(&a_dist[0][0], 0, sizeof(float32) * n_stream * n_density); memset(&b_dist[0][0], 0, sizeof(float32) * n_stream * n_density); } /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { einc -= root_ent; } /* END ADDITION FOR CONTINUOUS_TREES */ /* Maximize the weighted entropy increase of the merge */ if (einc > b_einc) { b_einc = einc; for (j = 0; j < n_dist; j++) { bclust[j] = clust[j]; } } /* Zero clust for next iteration */ memset(clust, 0, sizeof(uint32) * n_dist); } while (next_subset(set, n_dist, i)); } ckd_free((void *)clust); ckd_free((void *)set); ckd_free_2d((void **)a_dist); ckd_free_2d((void **)b_dist); ckd_free_3d((void ***)m_dist); /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { ckd_free_3d((void ***)m_means); ckd_free_3d((void ***)m_vars); ckd_free_3d((void ***)a_means); ckd_free_3d((void ***)a_vars); ckd_free_3d((void ***)b_means); ckd_free_3d((void ***)b_vars); } /* END ADDITION FOR CONTINUOUS_TREES */ return b_einc; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libio/share_ctl.c /* ==================================================================== * Copyright (c) 2004 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: share_ctl.c * * Description: * * Author: * *********************************************************************/ #include <s3/prim_type.h> #include <s3/swap.h> #include <s3/bo_magic.h> #include <s3/s3.h> #include <sys_compat/file.h> static uint32 blk_sz; static uint32 buf_id; static int state_fd; int share_ctl_set_block_size(uint32 sz) { blk_sz = sz; return S3_SUCCESS; } int share_ctl_set_buf_id(uint32 id) { buf_id = id; return S3_SUCCESS; } int share_ctl_set_state_file(const char *file_name) { state_fd = open(file_name, O_CREAT | O_RDWR, 0755); if (state_fd < 0) { E_FATAL_SYSTEM("Couldn't open ctl file state file %s\n", file_name); } return S3_SUCCESS; } int share_ctl_init_state_file() { uint32 magic = BYTE_ORDER_MAGIC; uint32 zero = 0; if (write(state_fd, &magic, sizeof(uint32)) < 0) E_FATAL_SYSTEM("write failed"); if (write(state_fd, &zero, sizeof(uint32)) < 0) E_FATAL_SYSTEM("write failed"); lseek(state_fd, (off_t)0, SEEK_SET); return S3_SUCCESS; } int share_ctl_next_utts(uint32 *offset, uint32 *run) { uint32 magic; uint32 i_offset; uint32 o_offset; uint32 ns; int ret; struct flock lck; lck.l_type = F_WRLCK; lck.l_whence = SEEK_SET; lck.l_start = 0; lck.l_len = 2 * sizeof(uint32); /* Get an exclusive lock on the file */ if (fcntl(state_fd, F_SETLKW, &lck) < 0) { E_FATAL_SYSTEM("file lock failed"); } printf("*** in crit sec ***\n"); /* read the byte order magic number */ ret = read(state_fd, &magic, sizeof(uint32)); if (ret < 0) E_FATAL_SYSTEM("read failed"); else if (ret < sizeof(uint32)) { E_FATAL("Expected to read %u bytes, but got %u instead\n", sizeof(uint32), ret); } if (magic != BYTE_ORDER_MAGIC) { /* seems to need swap */ SWAP_INT32(&magic); if (magic != BYTE_ORDER_MAGIC) { E_FATAL("Couldn't create magic # by swapping\n"); } ns = TRUE; } else ns = FALSE; ret = read(state_fd, &i_offset, sizeof(uint32)); if (ret < 0) E_FATAL_SYSTEM("read failed"); else if (ret < sizeof(uint32)) { E_FATAL("Expected to read %u bytes, but got %u instead\n", sizeof(uint32), ret); } if (ns) SWAP_INT32(&i_offset); o_offset = i_offset + blk_sz; printf("i_offset= %u\n", i_offset); sleep(30); lseek(state_fd, (off_t)0, SEEK_SET); if (write(state_fd, &magic, sizeof(uint32)) < 0) E_FATAL_SYSTEM("write failed"); if (write(state_fd, &o_offset, sizeof(uint32)) < 0) E_FATAL_SYSTEM("write failed"); lck.l_type = F_UNLCK; if (fcntl(state_fd, F_SETLK, &lck) < 0) { E_FATAL_SYSTEM("file unlock failed"); } lseek(state_fd, (off_t)0, SEEK_SET); printf("*** out crit sec ***\n"); *offset = i_offset; *run = blk_sz; return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/11/29 01:11:17 egouvea * Fixed license terms in some new files. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/tests/tidigits/Makefile # ==================================================================== # # Sphinx III # # ==================================================================== TOP=`(cd ../../..; pwd)` DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = # LIVEDECSRCS = # MAINSRCS = # OTHERSRCS = main.c # LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile LIBNAME= tests BINDIR = $(TOP)/bin/$(MACHINE) tidigits: rm -f gmake-tidigits.results $(BINDIR)/s3decode-anytopo ARGS.tidigits > gmake-tidigits.results $(BINDIR)/align -ref tidigits.ref -hyp tidigits.match > tidigits.align tidigits_quick: rm -f gmake-tidigits-quick.results $(BINDIR)/s3decode-anytopo ARGS.tidigits-quick > gmake-tidigits-quick.results $(BINDIR)/align -ref tidigits-quick.ref -hyp tidigits-quick.match > tidigits-quick.align <file_sep>/SphinxTrain/src/libs/libcommon/quest.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: quest.c * * Description: * * Author: * *********************************************************************/ #include <s3/quest.h> #include <s3/bquest_io.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <string.h> #include <assert.h> #include <ctype.h> char * s3parse_quest(pset_t *pset, uint32 n_pset, quest_t *q, char *in_str) { char *s, *sp; uint32 i; s = in_str; /* skip leading whitespace */ for (; *s != '\0' && isspace((int)*s); s++); if (*s == '\0') /* Nothing to parse */ return s; if (*s == '!') { q->neg = TRUE; ++s; if (*s == '\0') { E_ERROR("question syntax error"); return NULL; } } else q->neg = FALSE; sp = strchr(s, ' '); if (sp == NULL) { E_ERROR("Expected space after question name\n"); return NULL; } *sp = '\0'; for (i = 0; i < n_pset; i++) { if (strcmp(s, pset[i].name) == 0) { q->pset = i; q->member = pset[i].member; q->posn = pset[i].posn; break; } } if (i == n_pset) { E_ERROR("Unknown question %s\n", s); return NULL; } s = sp+1; *sp = ' '; /* undo set to null */ /* skip whitespace */ for (; *s != '\0' && isspace((int)*s); s++); if (s[0] == '-') { if (s[1] == '1') { q->ctxt = -1; } s += 2; } else if (s[0] == '0') { q->ctxt = 0; s++; } else if (s[0] == '1') { q->ctxt = 1; s++; } /* skip trailing whitespace, if any */ for (; *s != '\0' && isspace((int)*s); s++); return s; } static uint32 count_quest_in_conj(pset_t *pset, uint32 n_pset, char *in_str) { quest_t tmp; quest_t *q = &tmp; char *t; uint32 n_quest; n_quest = 0; t = in_str; for (; *t != '\0' && isspace((int)*t); t++); if (*t == ')') { E_ERROR("Empty conjunction\n"); return 0; } while (t && *t != ')' && *t != '\0') { t = s3parse_quest(pset, n_pset, q, t); ++n_quest; for (; t && *t != '\0' && isspace((int)*t); t++); } if (t == NULL) { E_ERROR("Error while parsing conjunction: %s\n", in_str); return 0; } if (*t != ')') { E_ERROR("Error while parsing conjunction: %s\n", in_str); return 0; } return n_quest; } char * s3parse_conj(pset_t *pset, uint32 n_pset, quest_t **term, uint32 *n_simple_q, char *in_str) { quest_t *termlst; char *s; uint32 n_quest; uint32 i; s = in_str; if (*s == '\0') return s; /* skip leading whitespace */ for (; *s != '\0' && isspace((int)*s); s++); if (*s == '\0') return s; if (*s == '(') { ++s; } else { E_ERROR("Expected '(' before conjunction\n"); return NULL; } for (; *s != '\0' && isspace((int)*s); s++); if (*s == '\0') { E_ERROR("No terms and close paren in conjunction\n", in_str); return NULL; } n_quest = count_quest_in_conj(pset, n_pset, s); *n_simple_q = n_quest; termlst = (quest_t *)ckd_calloc(n_quest, sizeof(quest_t)); *term = termlst; for (i = 0; i < n_quest; i++) { s = s3parse_quest(pset, n_pset, &termlst[i], s); for (; *s != '\0' && isspace((int)*s); s++); } assert(*s == ')'); s++; return s; } static uint32 s3cnt_q_term(char *in_str) { char *s; uint32 n_term; s = in_str; /* skip any leading whitespace */ for (; *s != '\0' && isspace((int)*s); s++); /* assume everything is well-formed for the moment. * later processing will catch syntax errors * which should be unlikely anyway since this stuff * is most likely machine generated */ for (s++, n_term = 0; *s && (s = strchr(s, '(')); n_term++, s++); return n_term; } int s3parse_comp_quest(pset_t *pset, uint32 n_pset, comp_quest_t *q, char *in_str) { char *s; uint32 i; s = in_str; for (; *s != '\0' && isspace((int)*s); s++); if (*s == '\0') { E_ERROR("Empty string seen for composite question\n"); return S3_ERROR; } if (*s != '(') { E_ERROR("Composite question does not begin with '(' : %s\n", in_str); return S3_ERROR; } q->sum_len = s3cnt_q_term(in_str); q->conj_q = (quest_t **)ckd_calloc(q->sum_len, sizeof(quest_t *)); q->prod_len = (uint32 *)ckd_calloc(q->sum_len, sizeof(uint32)); ++s; /* skip the open paren */ i = 0; do { s = s3parse_conj(pset, n_pset, &q->conj_q[i], &q->prod_len[i], s); ++i; } while (s && *s && *s == '('); if (s == NULL) { E_ERROR("Error while parsing %s\n", in_str); return S3_ERROR; } return S3_SUCCESS; } static void parse_simple_q(quest_t *q, char *q_str) { int i; int len; uint32 pset; assert(q != NULL); assert(q_str != NULL); len = strlen(q_str); /* skip leading whitespace */ for (i = 0; i < len && isspace((int)q_str[i]); i++); if (i == len) return; if (q_str[i] == '~') { q->neg = TRUE; i++; } else { q->neg = FALSE; } pset = atoi(&q_str[i]); if (pset >= 400) { q->ctxt = 1; pset -= 400; } else if (pset < 400) { q->ctxt = -1; } q->pset = pset; /* HACK to get around WDBNDRY question context */ if (pset < 3) q->ctxt = 0; } char * parse_conj(quest_t **term, uint32 *n_simple_q, char *q_str) { char *t, *eot; int n_q; char t_str[64]; char *simp_q_str; quest_t *out; int i; /* copy the next product into t_str */ eot = strchr(q_str, '|'); if (eot) { strncpy(t_str, q_str, (eot - q_str)); t_str[(eot - q_str)] = '\0'; } else { strcpy(t_str, q_str); } /* count the # of terms in the product */ t = t_str-1; n_q = 1; do { t = strchr(t+1, '&'); if (t) { n_q++; } } while (t); /* allocate a simple question for each term in product */ out = ckd_calloc(n_q, sizeof(quest_t)); *term = out; *n_simple_q = n_q; /* parse each simple question */ simp_q_str = strtok(t_str, "&"); i = 0; do { parse_simple_q(&out[i], simp_q_str); simp_q_str = strtok(NULL, "&"); i++; } while (simp_q_str); return eot; } uint32 cnt_q_term(char *q_str) { char *t; uint32 n_term; t = q_str-1; n_term = 1; do { t = strchr(t+1, '|'); if (t) ++n_term; } while (t); return n_term; } void parse_compound_q(comp_quest_t *q, char *q_str) { char *rem_q_str; uint32 i; q->sum_len = cnt_q_term(q_str); q->conj_q = ckd_calloc(q->sum_len, sizeof(quest_t *)); q->prod_len = ckd_calloc(q->sum_len, sizeof(uint32)); i = 0; rem_q_str = q_str-1; do { rem_q_str = parse_conj(&q->conj_q[i], &q->prod_len[i], rem_q_str+1); ++i; } while (rem_q_str); } void print_quest(FILE *fp, pset_t *pset, quest_t *q) { if (pset == NULL) { fprintf(fp, "%s%d %d", (q->neg ? "!" : ""), q->pset, q->ctxt); } else { fprintf(fp, "%s%s %d", (q->neg ? "!" : ""), pset[q->pset].name, q->ctxt); } } int eval_quest(quest_t *q, uint32 *feat, uint32 n_feat) { uint32 ctxt; int ret = FALSE; ctxt = q->ctxt + 1; if (q->member) ret = q->member[feat[ctxt]]; else if (q->posn) ret = q->posn[feat[n_feat-1]]; else { E_FATAL("Ill-formed question\n"); } if (q->neg) ret = !ret; #if 0 E_INFO("eval: (%s%u %d) %u -> %u\n", (q->neg ? "!" : ""), q->pset, q->ctxt, (q->member ? q->member[feat[ctxt]] : q->posn[feat[n_feat-1]]), ret); #endif return ret; } int eval_comp_quest(comp_quest_t *q, uint32 *feat, uint32 n_feat) { int i, j; for (i = 0; i < q->sum_len; i++) { for (j = 0; j < q->prod_len[i]; j++) { if (!eval_quest(&q->conj_q[i][j], feat, n_feat)) break; } /* One of the terms in the disjunction * is satisfied; so the whole is satisfied */ if (j == q->prod_len[i]) return TRUE; } /* visited all terms in the disjunction and none * were satisified; so neither is the disjunction */ return FALSE; } void print_comp_quest(FILE *fp, pset_t *pset, comp_quest_t *q) { int i, j; fprintf(fp, "("); for (i = 0; i < q->sum_len; i++) { fprintf(fp, "("); print_quest(fp, pset, &q->conj_q[i][0]); for (j = 1; j < q->prod_len[i]; j++) { fprintf(fp, " "); print_quest(fp, pset, &q->conj_q[i][j]); } fprintf(fp, ")"); } fprintf(fp, ")"); } int is_subset(quest_t *a, quest_t *b, uint32 n_phone) { uint32 p; int f_a, f_b; if (a->member && b->member) { if (a->ctxt != b->ctxt) return FALSE; for (p = 0; p < n_phone; p++) { if (a->neg) f_a = !a->member[p]; else f_a = a->member[p]; if (b->neg) f_b = !b->member[p]; else f_b = b->member[p]; if (f_a && (f_a != f_b)) { break; } } if (p != n_phone) return FALSE; else return TRUE; } else if ((a->member && b->posn) || (a->posn && b->member)) { /* one question about word boundary * and the other is about phone context * so not a subset */ return FALSE; } else if (a->posn && b->posn) { /* Not handled at the moment */ return FALSE; } return FALSE; } int simplify_conj(quest_t *conj, uint32 n_term, uint32 n_phone) { uint32 i, j; int *del, exist_del = FALSE; assert(n_term != 0); if (n_term == 1) /* Only one term; nothing to do */ return 1; del = ckd_calloc(n_term, sizeof(int)); /* Search for all pairs (i,j) where * term_i is a subset of term_j. Mark * all such term_j's for deletion since * term_i && term_j == term_i */ for (i = 0; i < n_term; i++) { for (j = 0; j < n_term; j++) { if ((i != j) && (!del[i] || !del[j])) { if (is_subset(&conj[i], &conj[j], n_phone)) { /* mark the superset for deletion */ del[j] = TRUE; exist_del = TRUE; } } } } /* compact the conjunction by removing * term_j's that are marked for deletion. */ for (i = 0, j = 0; j < n_term; i++, j++) { if (del[j]) { /* move j to the next * non-deleted term (if any) */ for (j++; del[j] && (j < n_term); j++); if (j == n_term) break; } if (i != j) { conj[i] = conj[j]; } } ckd_free(del); return i; /* return new n_term */ } int simplify_comp_quest(comp_quest_t *q, uint32 n_phone) { int i; int ret = FALSE; int prod_len; for (i = 0; i < q->sum_len; i++) { prod_len = simplify_conj(q->conj_q[i], q->prod_len[i], n_phone); if (prod_len < q->prod_len[i]) { assert(!(prod_len > q->prod_len[i])); q->prod_len[i] = prod_len; ret = TRUE; } } /* TRUE if there is at least one term in the composite * question that was simplified */ return ret; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2003/11/18 21:07:25 egouvea * Got rid of warning casting the argument to "isspace". * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.3 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.2 96/06/17 14:40:41 eht * *** empty log message *** * * Revision 1.1 1996/03/25 15:31:39 eht * Initial revision * * */ <file_sep>/archive_s3/s3.2/src/libutil/filename.c /* * filename.c -- File and path name operations. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 30-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "filename.h" /* Strip off all leading pathname components */ void path2basename (char *path, char *base) { int32 i, l; l = strlen(path); for (i = l-1; (i >= 0) && (path[i] != '/'); --i); strcpy (base, path+i+1); } /* Strip off the shortest trailing .xyz suffix */ void strip_fileext (char *path, char *root) { int32 i, l; l = strlen(path); for (i = l-1; (i >= 0) && (path[i] != '.'); --i); if (i < 0) strcpy (root, path); /* Didn't find a . */ else { path[i] = '\0'; strcpy (root, path); path[i] = '.'; } } <file_sep>/archive_s3/s3.0/pgm/makedict/makedict.c /* * makedict.c -- Make a dictionary for the given vocab, using the given dictionaries. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 23-Apr-1998 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * Vocab input file should contain one or two "words" per line. If two words, the * 2nd word is used to look up the given dictionaries for pronunciations. But once * pronunciations are found in one dictionary, the remaining are not searched (to * avoid extract duplicate pronunciations). * Vocab input file is assumed to contain a unique set of words, no duplicates. */ #include <libutil/libutil.h> #include <libmain/dict.h> main (int32 argc, char *argv[]) { dict_t **d; int32 i, k, p, wid; char line[16384], *wp[1024]; if (argc < 2) { E_INFO("Usage: %s dictfile [dictfile ...] < vocabfile\n", argv[0]); exit(0); } d = (dict_t **) ckd_calloc (argc-1, sizeof(dict_t *)); for (i = 1; i < argc; i++) d[i-1] = dict_init (NULL, argv[i], NULL, 0); while (fgets (line, sizeof(line), stdin) != NULL) { if ((k = str2words (line, wp, 1024)) < 0) E_FATAL("Line too long: %s\n", line); if (k > 2) E_FATAL("Vocab entry contains too many words\n"); if (k == 0) continue; if (k == 1) wp[1] = wp[0]; /* Look up word in each dictionary until found */ k = 0; for (i = 0; (i < argc-1) && (k == 0); i++) { wid = dict_wordid (d[i], wp[1]); if (NOT_WID(wid)) continue; for (wid = dict_basewid(d[i], wid); IS_WID(wid); wid = dict_nextalt(d[i], wid)) { k++; if (k == 1) printf ("%s\t", wp[0]); else printf ("%s(%d)\t", wp[0], k); for (p = 0; p < dict_pronlen(d[i], wid); p++) printf (" %s", dict_ciphone_str (d[i], wid, p)); printf ("\n"); } } if (k == 0) E_ERROR("No pronunciation for: '%s'\n", wp[0]); } } <file_sep>/SphinxTrain/src/programs/init_mixw/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/s3.h> #include <sys_compat/misc.h> #include <sys_compat/file.h> #include <stdio.h> #include <assert.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ Initialization of mixture weight "; const char examplestr[] = "Example: \n\ \n\ init_mixw -src_moddeffn src_moddeffn -src_ts2cbfn .semi. -src_mixwfn \n\ src_mixwfn -src_meanfn src_meanfn -src_varfn src_varfn -src_tmatfn \n\ src_tmatfn -dest_moddeffn dest_moddeffn -dest_ts2cbfn \n\ .semi. -dest_mixwfn dest_mixwfn -dest_me anfn dest_meanfn -dest_varfn \n\ dest_varfn -dest_tmatfn dest_tmatfn"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-src_moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source model definition file name"}, { "-src_ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source state definition file name"}, { "-src_mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source mixing weight file name"}, { "-src_meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source mean file name"}, { "-src_varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source variance file name"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Source and destination are full covariance matrices"}, { "-src_tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source transition matrix file name"}, { "-dest_moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination model definition file name"}, { "-dest_ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination state definition file name"}, { "-dest_mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination mixing weight file name"}, { "-dest_meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination mean file name"}, { "-dest_varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination variance file name"}, { "-dest_tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The destination transition matrix file name"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ exit(1); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2004/11/29 01:43:46 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/08/10 22:15:08 arthchan2003 * help and example for init_mixw, I think this is the last one before quick_count and wave2feat, we need to think of what we should for those two little babies...... * * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 1995/10/05 12:54:02 eht * Initial revision * * Revision 1.2 1995/09/07 19:59:50 eht * Include defn for TRUE/FALSE * * Revision 1.1 1995/06/02 20:55:11 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libfeat/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../../Makefile.defines VPATH = .:.. TARGET = libfeat.a OBJS = feat.o $(TARGET): $(OBJS) ar crv $@ $? ranlib $@ install: $(TARGET) mv $(TARGET) $(S3LIBDIR) clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# feattest: feat.c cc -g -DFEAT_TEST=1 -L. -L$(S3LIBDIR) -o feattest feat.c -lio -lutil <file_sep>/SphinxTrain/src/programs/mk_s3tmat/mk_s3tmat.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: mk_s3tmat.c * * Description: * Make a SPHINX-III transition matrix file from SPHINX-II * HMM files. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/model_def_io.h> #include <s3/acmod_set.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s2_read_tmat.h> #include <s3/s3tmat_io.h> #include <s3/s2_param.h> #include <s3/s3.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> int main(int argc, char *argv[]) { float32 ***tmat; model_def_t *mdef; uint32 n_mdef; char comment[4192]; time_t t; parse_cmd_ln(argc, argv); E_INFO("Reading %s\n", cmd_ln_access("-moddeffn")); if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { exit(1); } n_mdef = mdef->n_defn; E_INFO("%d models defined\n", n_mdef); tmat = s2_read_tmat(cmd_ln_access("-hmmdir"), mdef->acmod_set, *(float32 *)cmd_ln_access("-floor")); t = time(NULL); sprintf(comment, "Generated on %s\n\tmoddeffn: %s\n\tfloor: %e\n\thmmdir: %s\n\n\n\n\n\n\n\n\n", ctime(&t), (const char *)cmd_ln_access("-moddeffn"), *(float32 *)cmd_ln_access("-floor"), (const char *)cmd_ln_access("-hmmdir")); E_INFO("Writing %s\n", cmd_ln_access("-tmatfn")); if (s3tmat_write(cmd_ln_access("-tmatfn"), tmat, acmod_set_n_ci(mdef->acmod_set), /* total # transition matrices */ S2_N_STATE) != S3_SUCCESS) { E_ERROR_SYSTEM("Couldn't write transition matrix file"); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 19:17:25 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:23 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/03/07 08:56:06 eht * - use E_*() routines for error and info output * - deal w/ new i/o routines * * Revision 1.1 97/01/21 13:04:17 eht * Initial revision * * */ <file_sep>/pocketsphinx/test/unit/test_glextree.c #include <pocketsphinx.h> #include <stdio.h> #include <string.h> #include <time.h> #include "pocketsphinx_internal.h" #include "glextree.h" #include "test_macros.h" int main(int argc, char *argv[]) { dict_t *dict; dict2pid_t *d2p; bin_mdef_t *mdef; glextree_t *tree; hmm_context_t *ctx; logmath_t *lmath; tmat_t *tmat; int i; TEST_ASSERT(mdef = bin_mdef_read(NULL, MODELDIR "/hmm/en_US/hub4wsj_sc_8k/mdef")); TEST_ASSERT(dict = dict_init(cmd_ln_init(NULL, NULL, FALSE, "-dict", DATADIR "/turtle.dic", "-dictcase", "no", NULL), mdef)); TEST_ASSERT(d2p = dict2pid_build(mdef, dict)); lmath = logmath_init(1.0001, 0, TRUE); tmat = tmat_init(MODELDIR "/hmm/en_US/hub4wsj_sc_8k/transition_matrices", lmath, 1e-5, TRUE); ctx = hmm_context_init(bin_mdef_n_emit_state(mdef), tmat->tp, NULL, mdef->sseq); TEST_ASSERT(tree = glextree_build(ctx, dict, d2p, NULL, NULL)); /* Check that a path exists for all dictionary words. */ for (i = 0; i < dict_size(dict); ++i) TEST_ASSERT(glextree_has_word(tree, i)); dict_free(dict); dict2pid_free(d2p); bin_mdef_free(mdef); tmat_free(tmat); hmm_context_free(ctx); glextree_free(tree); return 0; } <file_sep>/SphinxTrain/src/libs/libio/s3phseg_io.c /* ==================================================================== * Copyright (c) 2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3phseg_io.c * * Description: * SPHINX-III phone segmentation file I/O functions * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3phseg_io.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <stdio.h> #include <string.h> int s3phseg_read(const char *fn, acmod_set_t *acmod_set, s3phseg_t **out_phseg) { FILE *fp; char txt[512]; s3phseg_t *plist = NULL; int n; if ((fp = fopen(fn, "r")) == NULL) { E_ERROR("Failed to open phseg file %s\n", fn); return S3_ERROR; } /* Should be a header of column names */ while ((n = fscanf(fp, "%511s", txt))) { if (n == EOF) { E_ERROR("Failed to read column headers from phseg file\n"); goto error_out; } if (!strcmp(txt, "Phone")) break; } /* Get each line */ while (!feof(fp)) { unsigned int sf, ef; int score; acmod_id_t ci, phone; s3phseg_t *phseg; char *c, *cc; n = fscanf(fp, "%u %u %d", &sf, &ef, &score); if (n < 3) /* We probably hit EOF or "Total score" */ break; fgets(txt, sizeof(txt), fp); /* Remove newline. */ if (txt[strlen(txt)-1] == '\n') txt[strlen(txt)-1] = '\0'; /* Find the base phone. */ cc = txt + strspn(txt, " \t"); if ((c = strchr(cc, ' '))) *c = '\0'; if ((ci = phone = acmod_set_name2id(acmod_set, txt)) == NO_ACMOD) { E_ERROR("Unknown CI phone (%s) in phseg file\n", txt); goto error_out; } /* Restore the space and find the triphone if necessary. */ if (c) *c = ' '; if (acmod_set->n_multi != 0 && !acmod_set_has_attrib(acmod_set, phone, "filler")) { if ((phone = acmod_set_name2id(acmod_set, txt)) == NO_ACMOD) { /* This might be too verbose. */ E_WARN("Unknown triphone (%s) in phseg file\n", txt); /* Back off to CI phone. */ phone = ci; } } phseg = ckd_calloc(1, sizeof(*phseg)); phseg->next = plist; phseg->phone = phone; phseg->sf = sf; phseg->ef = ef; phseg->score = score; plist = phseg; } fclose(fp); if (out_phseg) { s3phseg_t *next, *last = NULL; /* Now reverse the list. */ while (plist) { next = plist->next; *out_phseg = plist; (*out_phseg)->next = last; last = *out_phseg; plist = next; } } else s3phseg_free(plist); return S3_SUCCESS; error_out: fclose(fp); return S3_ERROR; } int s3phseg_write(const char *fn, acmod_set_t *acmod_set, s3phseg_t *phseg) { FILE *fp; if ((fp = fopen(fn, "w")) == NULL) return S3_ERROR; fprintf (fp, "\t%5s %5s %9s %s\n", "SFrm", "EFrm", "SegAScr", "Phone"); for (; phseg; phseg = phseg->next) { fprintf(fp, "\t%5d %5d %9d %s\n", phseg->sf, phseg->ef, phseg->score, acmod_set_id2name(acmod_set, phseg->phone)); } fclose (fp); return S3_SUCCESS; } void s3phseg_free(s3phseg_t *phseg) { s3phseg_t *next; while (phseg) { next = phseg->next; ckd_free(phseg); phseg = next; } } <file_sep>/SphinxTrain/src/programs/agg_seg/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ agg_seg accumulate feature vectors and use the accumulated values to quantize \n\ the vector space. This functionality is useful in semi-continuous training \n\ initialization. Feature vectors are skipped according to the option -stride. \n\ \n\ Some options are specific to Sphinx-2.\n\ Please type -example yes to get an example argument list."; const char examplestr[]= "Example: \n\ \n\ agg_seg -segdmpdirs segdmpdir -segdmpfn dumpfile -segtype all -ctlfn \n\ ctl -cepdir cepdir -cepext .mfc -ceplen 13 -stride 10 "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-segdmpdirs", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Segment dump directories" }, { "-segdmpfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Segment dump file" }, { "-segidxfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Segment index into the dump file." }, { "-segtype", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "st", "Type of segments to dump. {all,st,phn}" }, { "-cntfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Per id count file" }, { "-ddcodeext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "xcode", "Extension of the VQ 2nd difference cepstrum files"}, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Lexical transcript file (contains all utts in ctl file)" }, { "-sentdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of sent (lexical transcript) files" }, { "-sentext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Extension of sent (lexical transcript) files" }, { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The control file name (enumerates utts in corpus)" }, { "-mllrctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Lists the MLLR transforms for each utterance" }, { "-mllrdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Directory for MLLR matrices" }, { "-nskip", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "The number of utterances to skip in the control file"}, { "-runlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "-1", "The number of utterances to process after skipping"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition file containing all the triphones in the corpus. State/transition matrix definitions are ignored." }, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied state to codebook mapping file (may be '.semi.' or '.cont.')"}, { "-cb2mllrfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".1cls.", "codebook to MLLR class mapping file (may be '.1cls.')"}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Lexicon containing all the words in the lexical transcripts."}, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Lexicon containing all the filler words in the lexical transcripts."}, { "-segdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the state segmentation files"}, { "-segext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "v8_seg", "Extension of the state segmentation files"}, { "-ccodedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the VQ cepstrum files"}, { "-ccodeext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "ccode", "Extension of the VQ cepstrum files"}, { "-dcodedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the VQ difference cepstrum files"}, { "-dcodeext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "d2code", "Extension of the VQ cepstrum files"}, { "-pcodedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the VQ power files"}, { "-pcodeext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "p3code", "Extension of the VQ power files"}, { "-ddcodedir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the VQ 2nd difference cepstrum files"}, { "-ddcodeext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "xcode", "Extension of the VQ 2nd difference cepstrum files"}, { "-cepdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the cepstrum files"}, { "-cepext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_EXTENSION, "Extension of the cepstrum files"}, { "-ceplen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_CEP_LENGTH, "# of coefficients per cepstrum frame"}, { "-cepwin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "sliding window of features to concatenate (for -feat 1s_c ONLY)"}, { "-agc", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "max", "The type of automatic gain control to do {max|emax}"}, { "-cmn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "current", "The do cepstral mean normalization based on {current|prior} utterance(s)"}, { "-varnorm", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Normalize utterance by its variance"}, { "-silcomp", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "none", "Do silence compression based on {current|prior} utterance"}, { "-feat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_TYPE, "Feature set to compute"}, { "-svspec", CMD_LN_STRING, CMD_LN_NO_VALIDATION, NULL, "Split single stream features into subvectors according to this specification."}, { "-ldafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File containing an LDA transformation matrix."}, { "-ldadim", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "29", "# of output dimensions for LDA"}, { "-cachesz", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "200", "Feature cache size in Mb"}, { "-stride", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "Take every -stride'th frame when producing dmp" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/11/29 01:43:44 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.6 2004/11/29 00:49:19 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.5 2004/08/08 01:20:37 arthchan2003 * agg_seg help and example strings * * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 96/03/25 15:45:23 eht * Development version * * Revision 1.2 1996/03/04 16:01:06 eht * *** empty log message *** * * Revision 1.1 1995/12/15 18:37:07 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcommon/cmu6_lts_rules.c /*************************************************************************/ /* */ /* Language Technologies Institute */ /* Carnegie Mellon University */ /* Copyright (c) 2001 */ /* All Rights Reserved. */ /* */ /* Permission is hereby granted, free of charge, to use and distribute */ /* this software and its documentation without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of this work, and to */ /* permit persons to whom this work is furnished to do so, subject to */ /* the following conditions: */ /* 1. The code must retain the above copyright notice, this list of */ /* conditions and the following disclaimer. */ /* 2. Any modifications must be clearly marked as such. */ /* 3. Original authors' names are not deleted. */ /* 4. The authors' names are not used to endorse or promote products */ /* derived from this software without specific prior written */ /* permission. */ /* */ /* CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK */ /* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */ /* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ /* SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE */ /* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */ /* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */ /* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */ /* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */ /* THIS SOFTWARE. */ /* */ /*************************************************************************/ /* Author: <NAME> (<EMAIL>) */ /* <NAME> (<EMAIL>) */ /* Date: January 2001 */ /*************************************************************************/ /* */ /* CMU(6) letter to sound rule decision graphs */ /* */ /*************************************************************************/ /*******************************************************/ /** Autogenerated llts rules (regex) for cmu6 */ /** from /home/awb/projects/lts/cmu6/regex */ /*******************************************************/ #include <stdlib.h> #include "s3/lts.h" #include "cmu6_lts_rules.h" static const cst_lts_model cmu6_lts_model[] = { /** letter a **/ 4, 'r', LTS_STATE_a_2 , LTS_STATE_a_1 , 6, '0', LTS_STATE_a_4 , LTS_STATE_a_3 , 3, 'e', LTS_STATE_a_6 , LTS_STATE_a_5 , 4, 'u', LTS_STATE_a_8 , LTS_STATE_a_7 , 4, 'y', LTS_STATE_a_10 , LTS_STATE_a_9 , 3, 'w', LTS_STATE_a_12 , LTS_STATE_a_11 , 5, 't', LTS_STATE_a_14 , LTS_STATE_a_13 , 3, 'e', LTS_STATE_a_16 , LTS_STATE_a_15 , 3, 'e', LTS_STATE_a_18 , LTS_STATE_a_17 , 4, '#', LTS_STATE_a_20 , LTS_STATE_a_19 , 3, 'w', LTS_STATE_a_22 , LTS_STATE_a_21 , 1, '0', LTS_STATE_a_24 , LTS_STATE_a_23 , 5, 'e', LTS_STATE_a_26 , LTS_STATE_a_25 , 5, 'n', LTS_STATE_a_28 , LTS_STATE_a_27 , 2, 'h', LTS_STATE_a_29 , LTS_STATE_a_28 , 5, 'e', LTS_STATE_a_31 , LTS_STATE_a_30 , 2, 'r', LTS_STATE_a_33 , LTS_STATE_a_32 , 5, 'e', LTS_STATE_a_35 , LTS_STATE_a_34 , 5, 't', LTS_STATE_a_28 , LTS_STATE_a_36 , 3, 'e', LTS_STATE_a_38 , LTS_STATE_a_37 , 3, 'e', LTS_STATE_a_40 , LTS_STATE_a_39 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_41 , 2, 'a', LTS_STATE_a_43 , LTS_STATE_a_42 , 5, 'y', LTS_STATE_a_45 , LTS_STATE_a_44 , 5, 'r', LTS_STATE_a_47 , LTS_STATE_a_46 , 5, 'd', LTS_STATE_a_49 , LTS_STATE_a_48 , 255, 1, 0,0 , 0,0 , 5, 'm', LTS_STATE_a_52 , LTS_STATE_a_51 , 255, 0, 0,0 , 0,0 , 255, 2, 0,0 , 0,0 , 4, 'i', LTS_STATE_a_54 , LTS_STATE_a_53 , 4, 'g', LTS_STATE_a_56 , LTS_STATE_a_55 , 4, 'n', LTS_STATE_a_58 , LTS_STATE_a_57 , 1, '#', LTS_STATE_a_60 , LTS_STATE_a_59 , 5, 'g', LTS_STATE_a_62 , LTS_STATE_a_61 , 1, '0', LTS_STATE_a_64 , LTS_STATE_a_63 , 1, 'u', LTS_STATE_a_29 , LTS_STATE_a_65 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_66 , 4, 'u', LTS_STATE_a_68 , LTS_STATE_a_67 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_69 , 2, 'l', LTS_STATE_a_69 , LTS_STATE_a_70 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_71 , 255, 3, 0,0 , 0,0 , 1, 'l', LTS_STATE_a_73 , LTS_STATE_a_72 , 5, 'i', LTS_STATE_a_75 , LTS_STATE_a_74 , 3, 'n', LTS_STATE_a_26 , LTS_STATE_a_76 , 5, 'a', LTS_STATE_a_78 , LTS_STATE_a_77 , 2, '#', LTS_STATE_a_80 , LTS_STATE_a_79 , 5, 'i', LTS_STATE_a_26 , LTS_STATE_a_81 , 1, '0', LTS_STATE_a_83 , LTS_STATE_a_82 , 2, 'w', LTS_STATE_a_28 , LTS_STATE_a_84 , 2, 'r', LTS_STATE_a_29 , LTS_STATE_a_85 , 5, 'i', LTS_STATE_a_87 , LTS_STATE_a_86 , 5, 'r', LTS_STATE_a_89 , LTS_STATE_a_88 , 6, '#', LTS_STATE_a_91 , LTS_STATE_a_90 , 1, '0', LTS_STATE_a_93 , LTS_STATE_a_92 , 4, 'b', LTS_STATE_a_95 , LTS_STATE_a_94 , 1, '#', LTS_STATE_a_97 , LTS_STATE_a_96 , 4, 'k', LTS_STATE_a_99 , LTS_STATE_a_98 , 5, 't', LTS_STATE_a_101 , LTS_STATE_a_100 , 1, '0', LTS_STATE_a_103 , LTS_STATE_a_102 , 2, '#', LTS_STATE_a_105 , LTS_STATE_a_104 , 1, '#', LTS_STATE_a_64 , LTS_STATE_a_106 , 255, 4, 0,0 , 0,0 , 6, 'e', LTS_STATE_a_108 , LTS_STATE_a_107 , 4, 'w', LTS_STATE_a_110 , LTS_STATE_a_109 , 4, 'd', LTS_STATE_a_28 , LTS_STATE_a_111 , 1, 'o', LTS_STATE_a_112 , LTS_STATE_a_108 , 255, 5, 0,0 , 0,0 , 2, 'y', LTS_STATE_a_69 , LTS_STATE_a_113 , 2, 'p', LTS_STATE_a_42 , LTS_STATE_a_114 , 1, 't', LTS_STATE_a_73 , LTS_STATE_a_42 , 255, 6, 0,0 , 0,0 , 5, 'e', LTS_STATE_a_116 , LTS_STATE_a_115 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_117 , 2, 'c', LTS_STATE_a_26 , LTS_STATE_a_118 , 5, 'i', LTS_STATE_a_120 , LTS_STATE_a_119 , 3, 'p', LTS_STATE_a_26 , LTS_STATE_a_121 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_28 , 3, 'n', LTS_STATE_a_26 , LTS_STATE_a_122 , 1, '0', LTS_STATE_a_83 , LTS_STATE_a_123 , 1, '#', LTS_STATE_a_83 , LTS_STATE_a_124 , 255, 7, 0,0 , 0,0 , 1, 's', LTS_STATE_a_126 , LTS_STATE_a_125 , 1, '#', LTS_STATE_a_28 , LTS_STATE_a_127 , 4, 'y', LTS_STATE_a_129 , LTS_STATE_a_128 , 6, 'o', LTS_STATE_a_131 , LTS_STATE_a_130 , 5, 'n', LTS_STATE_a_133 , LTS_STATE_a_132 , 3, 'z', LTS_STATE_a_134 , LTS_STATE_a_26 , 3, 'w', LTS_STATE_a_136 , LTS_STATE_a_135 , 4, 't', LTS_STATE_a_138 , LTS_STATE_a_137 , 1, '#', LTS_STATE_a_140 , LTS_STATE_a_139 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_141 , 1, 'i', LTS_STATE_a_143 , LTS_STATE_a_142 , 1, '#', LTS_STATE_a_28 , LTS_STATE_a_69 , 1, 'c', LTS_STATE_a_28 , LTS_STATE_a_144 , 5, 'd', LTS_STATE_a_101 , LTS_STATE_a_145 , 4, 't', LTS_STATE_a_147 , LTS_STATE_a_146 , 1, 'b', LTS_STATE_a_42 , LTS_STATE_a_28 , 6, 'n', LTS_STATE_a_149 , LTS_STATE_a_148 , 255, 8, 0,0 , 0,0 , 1, '#', LTS_STATE_a_151 , LTS_STATE_a_150 , 3, 'c', LTS_STATE_a_153 , LTS_STATE_a_152 , 2, 'n', LTS_STATE_a_155 , LTS_STATE_a_154 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_83 , 255, 9, 0,0 , 0,0 , 1, 'o', LTS_STATE_a_112 , LTS_STATE_a_156 , 255, 10, 0,0 , 0,0 , 1, '#', LTS_STATE_a_158 , LTS_STATE_a_157 , 3, 'l', LTS_STATE_a_83 , LTS_STATE_a_159 , 4, 'n', LTS_STATE_a_161 , LTS_STATE_a_160 , 255, 11, 0,0 , 0,0 , 1, 'c', LTS_STATE_a_28 , LTS_STATE_a_69 , 1, 'l', LTS_STATE_a_163 , LTS_STATE_a_162 , 5, 'r', LTS_STATE_a_165 , LTS_STATE_a_164 , 6, 'l', LTS_STATE_a_167 , LTS_STATE_a_166 , 6, 'z', LTS_STATE_a_28 , LTS_STATE_a_168 , 2, 'e', LTS_STATE_a_26 , LTS_STATE_a_169 , 5, 'e', LTS_STATE_a_171 , LTS_STATE_a_170 , 6, 's', LTS_STATE_a_173 , LTS_STATE_a_172 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_174 , 3, 'h', LTS_STATE_a_176 , LTS_STATE_a_175 , 5, '#', LTS_STATE_a_28 , LTS_STATE_a_177 , 1, 'r', LTS_STATE_a_83 , LTS_STATE_a_28 , 5, 'l', LTS_STATE_a_179 , LTS_STATE_a_178 , 6, '#', LTS_STATE_a_180 , LTS_STATE_a_127 , 255, 12, 0,0 , 0,0 , 2, '#', LTS_STATE_a_182 , LTS_STATE_a_181 , 5, 'a', LTS_STATE_a_184 , LTS_STATE_a_183 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_185 , 4, 't', LTS_STATE_a_187 , LTS_STATE_a_186 , 5, 'l', LTS_STATE_a_189 , LTS_STATE_a_188 , 3, 't', LTS_STATE_a_191 , LTS_STATE_a_190 , 255, 13, 0,0 , 0,0 , 6, 'd', LTS_STATE_a_193 , LTS_STATE_a_192 , 4, 't', LTS_STATE_a_195 , LTS_STATE_a_194 , 3, 'i', LTS_STATE_a_197 , LTS_STATE_a_196 , 3, 'u', LTS_STATE_a_199 , LTS_STATE_a_198 , 3, 'i', LTS_STATE_a_28 , LTS_STATE_a_200 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_201 , 6, 'r', LTS_STATE_a_42 , LTS_STATE_a_202 , 1, 't', LTS_STATE_a_204 , LTS_STATE_a_203 , 2, 'n', LTS_STATE_a_42 , LTS_STATE_a_205 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_206 , 2, 'd', LTS_STATE_a_101 , LTS_STATE_a_28 , 5, 'o', LTS_STATE_a_28 , LTS_STATE_a_207 , 1, 'c', LTS_STATE_a_42 , LTS_STATE_a_208 , 5, 'e', LTS_STATE_a_28 , LTS_STATE_a_209 , 4, 'g', LTS_STATE_a_42 , LTS_STATE_a_28 , 5, 'l', LTS_STATE_a_211 , LTS_STATE_a_210 , 3, 'h', LTS_STATE_a_83 , LTS_STATE_a_212 , 2, '#', LTS_STATE_a_214 , LTS_STATE_a_213 , 6, 'a', LTS_STATE_a_83 , LTS_STATE_a_215 , 1, '#', LTS_STATE_a_83 , LTS_STATE_a_216 , 255, 14, 0,0 , 0,0 , 2, 'b', LTS_STATE_a_218 , LTS_STATE_a_217 , 4, 'n', LTS_STATE_a_220 , LTS_STATE_a_219 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_221 , 1, 'e', LTS_STATE_a_155 , LTS_STATE_a_83 , 2, 'n', LTS_STATE_a_223 , LTS_STATE_a_222 , 1, 'c', LTS_STATE_a_28 , LTS_STATE_a_224 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_225 , 3, 'd', LTS_STATE_a_226 , LTS_STATE_a_73 , 5, 't', LTS_STATE_a_228 , LTS_STATE_a_227 , 2, 'q', LTS_STATE_a_83 , LTS_STATE_a_229 , 6, 't', LTS_STATE_a_28 , LTS_STATE_a_230 , 2, 'c', LTS_STATE_a_28 , LTS_STATE_a_231 , 6, 'o', LTS_STATE_a_233 , LTS_STATE_a_232 , 3, 'u', LTS_STATE_a_26 , LTS_STATE_a_234 , 5, 'o', LTS_STATE_a_236 , LTS_STATE_a_235 , 6, 'e', LTS_STATE_a_28 , LTS_STATE_a_237 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_238 , 2, '#', LTS_STATE_a_239 , LTS_STATE_a_28 , 6, 's', LTS_STATE_a_241 , LTS_STATE_a_240 , 6, 'y', LTS_STATE_a_26 , LTS_STATE_a_242 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_243 , 2, 'e', LTS_STATE_a_28 , LTS_STATE_a_244 , 2, 'b', LTS_STATE_a_246 , LTS_STATE_a_245 , 2, 'p', LTS_STATE_a_28 , LTS_STATE_a_247 , 2, 'h', LTS_STATE_a_248 , LTS_STATE_a_28 , 1, '#', LTS_STATE_a_250 , LTS_STATE_a_249 , 3, 'w', LTS_STATE_a_252 , LTS_STATE_a_251 , 5, 'o', LTS_STATE_a_254 , LTS_STATE_a_253 , 6, 's', LTS_STATE_a_231 , LTS_STATE_a_255 , 6, 'z', LTS_STATE_a_257 , LTS_STATE_a_256 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_258 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_259 , 6, '#', LTS_STATE_a_261 , LTS_STATE_a_260 , 3, 'm', LTS_STATE_a_262 , LTS_STATE_a_42 , 1, 'a', LTS_STATE_a_264 , LTS_STATE_a_263 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_265 , 6, 's', LTS_STATE_a_267 , LTS_STATE_a_266 , 4, 't', LTS_STATE_a_269 , LTS_STATE_a_268 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_42 , 2, 't', LTS_STATE_a_29 , LTS_STATE_a_83 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_270 , 4, 'l', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_271 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_272 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_273 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_274 , 6, '#', LTS_STATE_a_42 , LTS_STATE_a_275 , 1, '#', LTS_STATE_a_28 , LTS_STATE_a_276 , 4, 't', LTS_STATE_a_277 , LTS_STATE_a_28 , 4, 's', LTS_STATE_a_28 , LTS_STATE_a_278 , 2, 'c', LTS_STATE_a_69 , LTS_STATE_a_279 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_280 , 1, 't', LTS_STATE_a_28 , LTS_STATE_a_281 , 5, 's', LTS_STATE_a_69 , LTS_STATE_a_282 , 6, '#', LTS_STATE_a_284 , LTS_STATE_a_283 , 3, 'n', LTS_STATE_a_108 , LTS_STATE_a_285 , 2, 'c', LTS_STATE_a_83 , LTS_STATE_a_286 , 5, 't', LTS_STATE_a_83 , LTS_STATE_a_287 , 5, 'n', LTS_STATE_a_83 , LTS_STATE_a_288 , 5, 's', LTS_STATE_a_29 , LTS_STATE_a_289 , 2, 'e', LTS_STATE_a_155 , LTS_STATE_a_290 , 1, 'e', LTS_STATE_a_112 , LTS_STATE_a_108 , 5, 'c', LTS_STATE_a_108 , LTS_STATE_a_291 , 4, 'l', LTS_STATE_a_293 , LTS_STATE_a_292 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_294 , 4, 'u', LTS_STATE_a_64 , LTS_STATE_a_295 , 1, 'a', LTS_STATE_a_28 , LTS_STATE_a_296 , 1, 'i', LTS_STATE_a_69 , LTS_STATE_a_28 , 1, '#', LTS_STATE_a_28 , LTS_STATE_a_297 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_298 , 2, 'i', LTS_STATE_a_73 , LTS_STATE_a_42 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_299 , 2, 'q', LTS_STATE_a_83 , LTS_STATE_a_300 , 1, 'r', LTS_STATE_a_26 , LTS_STATE_a_301 , 1, 'c', LTS_STATE_a_303 , LTS_STATE_a_302 , 255, 15, 0,0 , 0,0 , 6, 'a', LTS_STATE_a_26 , LTS_STATE_a_304 , 3, 's', LTS_STATE_a_29 , LTS_STATE_a_305 , 3, 'r', LTS_STATE_a_26 , LTS_STATE_a_306 , 5, 'y', LTS_STATE_a_308 , LTS_STATE_a_307 , 6, 'l', LTS_STATE_a_310 , LTS_STATE_a_309 , 2, '#', LTS_STATE_a_312 , LTS_STATE_a_311 , 3, 'v', LTS_STATE_a_314 , LTS_STATE_a_313 , 3, 'p', LTS_STATE_a_28 , LTS_STATE_a_26 , 6, 'b', LTS_STATE_a_101 , LTS_STATE_a_315 , 3, 'h', LTS_STATE_a_28 , LTS_STATE_a_29 , 6, 'i', LTS_STATE_a_317 , LTS_STATE_a_316 , 6, 'o', LTS_STATE_a_26 , LTS_STATE_a_101 , 1, '#', LTS_STATE_a_83 , LTS_STATE_a_318 , 5, 'c', LTS_STATE_a_28 , LTS_STATE_a_319 , 5, 'd', LTS_STATE_a_127 , LTS_STATE_a_28 , 1, '#', LTS_STATE_a_320 , LTS_STATE_a_28 , 255, 16, 0,0 , 0,0 , 5, 'o', LTS_STATE_a_322 , LTS_STATE_a_321 , 3, 'o', LTS_STATE_a_324 , LTS_STATE_a_323 , 4, 'w', LTS_STATE_a_326 , LTS_STATE_a_325 , 4, 'l', LTS_STATE_a_328 , LTS_STATE_a_327 , 5, 'r', LTS_STATE_a_329 , LTS_STATE_a_42 , 2, '#', LTS_STATE_a_42 , LTS_STATE_a_330 , 2, 'a', LTS_STATE_a_332 , LTS_STATE_a_331 , 6, 'n', LTS_STATE_a_334 , LTS_STATE_a_333 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, '0', LTS_STATE_a_336 , LTS_STATE_a_335 , 3, 'n', LTS_STATE_a_338 , LTS_STATE_a_337 , 5, 'o', LTS_STATE_a_28 , LTS_STATE_a_339 , 5, 'a', LTS_STATE_a_29 , LTS_STATE_a_42 , 2, 'e', LTS_STATE_a_73 , LTS_STATE_a_42 , 6, 'g', LTS_STATE_a_29 , LTS_STATE_a_340 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_341 , 6, 'e', LTS_STATE_a_42 , LTS_STATE_a_342 , 4, 'k', LTS_STATE_a_344 , LTS_STATE_a_343 , 4, 't', LTS_STATE_a_346 , LTS_STATE_a_345 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_347 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_42 , 2, 'a', LTS_STATE_a_349 , LTS_STATE_a_348 , 2, 'i', LTS_STATE_a_351 , LTS_STATE_a_350 , 1, 'a', LTS_STATE_a_42 , LTS_STATE_a_69 , 6, 'r', LTS_STATE_a_353 , LTS_STATE_a_352 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_69 , 2, '#', LTS_STATE_a_355 , LTS_STATE_a_354 , 2, 'm', LTS_STATE_a_42 , LTS_STATE_a_356 , 5, 'r', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'l', LTS_STATE_a_28 , LTS_STATE_a_69 , 2, 'g', LTS_STATE_a_69 , LTS_STATE_a_357 , 4, 'l', LTS_STATE_a_28 , LTS_STATE_a_358 , 5, 'h', LTS_STATE_a_28 , LTS_STATE_a_359 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_360 , 5, 's', LTS_STATE_a_362 , LTS_STATE_a_361 , 5, 'd', LTS_STATE_a_108 , LTS_STATE_a_363 , 3, 's', LTS_STATE_a_83 , LTS_STATE_a_364 , 6, 'e', LTS_STATE_a_366 , LTS_STATE_a_365 , 5, 'd', LTS_STATE_a_83 , LTS_STATE_a_367 , 5, 'r', LTS_STATE_a_369 , LTS_STATE_a_368 , 5, 'l', LTS_STATE_a_29 , LTS_STATE_a_83 , 2, 'o', LTS_STATE_a_155 , LTS_STATE_a_370 , 6, 'o', LTS_STATE_a_108 , LTS_STATE_a_371 , 4, 's', LTS_STATE_a_373 , LTS_STATE_a_372 , 3, 'h', LTS_STATE_a_374 , LTS_STATE_a_69 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_375 , 4, 'i', LTS_STATE_a_28 , LTS_STATE_a_376 , 4, 'k', LTS_STATE_a_28 , LTS_STATE_a_377 , 1, 'o', LTS_STATE_a_69 , LTS_STATE_a_378 , 1, 'c', LTS_STATE_a_42 , LTS_STATE_a_379 , 1, '#', LTS_STATE_a_381 , LTS_STATE_a_380 , 1, '#', LTS_STATE_a_29 , LTS_STATE_a_382 , 1, 'e', LTS_STATE_a_384 , LTS_STATE_a_383 , 6, '#', LTS_STATE_a_386 , LTS_STATE_a_385 , 3, 's', LTS_STATE_a_29 , LTS_STATE_a_231 , 6, 'c', LTS_STATE_a_388 , LTS_STATE_a_387 , 3, 'c', LTS_STATE_a_26 , LTS_STATE_a_389 , 2, 'i', LTS_STATE_a_26 , LTS_STATE_a_390 , 5, 'u', LTS_STATE_a_392 , LTS_STATE_a_391 , 6, '#', LTS_STATE_a_26 , LTS_STATE_a_393 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_394 , 3, 'p', LTS_STATE_a_28 , LTS_STATE_a_395 , 6, 'n', LTS_STATE_a_28 , LTS_STATE_a_231 , 3, 'm', LTS_STATE_a_231 , LTS_STATE_a_396 , 6, 't', LTS_STATE_a_26 , LTS_STATE_a_397 , 6, 'e', LTS_STATE_a_28 , LTS_STATE_a_26 , 2, '#', LTS_STATE_a_399 , LTS_STATE_a_398 , 3, 'm', LTS_STATE_a_401 , LTS_STATE_a_400 , 3, 'm', LTS_STATE_a_26 , LTS_STATE_a_402 , 2, 'h', LTS_STATE_a_83 , LTS_STATE_a_403 , 5, 's', LTS_STATE_a_405 , LTS_STATE_a_404 , 6, 'e', LTS_STATE_a_28 , LTS_STATE_a_127 , 5, 'l', LTS_STATE_a_407 , LTS_STATE_a_406 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_408 , 4, 'w', LTS_STATE_a_410 , LTS_STATE_a_409 , 2, 'j', LTS_STATE_a_29 , LTS_STATE_a_28 , 4, 'l', LTS_STATE_a_412 , LTS_STATE_a_411 , 5, 'a', LTS_STATE_a_414 , LTS_STATE_a_413 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_415 , 6, 'o', LTS_STATE_a_289 , LTS_STATE_a_83 , 6, 'e', LTS_STATE_a_26 , LTS_STATE_a_42 , 6, '#', LTS_STATE_a_42 , LTS_STATE_a_416 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_417 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_69 , 6, 'a', LTS_STATE_a_419 , LTS_STATE_a_418 , 4, 't', LTS_STATE_a_421 , LTS_STATE_a_420 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_422 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_423 , 3, 'u', LTS_STATE_a_42 , LTS_STATE_a_424 , 2, 'i', LTS_STATE_a_42 , LTS_STATE_a_425 , 6, 'a', LTS_STATE_a_427 , LTS_STATE_a_426 , 2, 'a', LTS_STATE_a_26 , LTS_STATE_a_428 , 3, 'g', LTS_STATE_a_69 , LTS_STATE_a_42 , 1, 'u', LTS_STATE_a_69 , LTS_STATE_a_429 , 4, 'y', LTS_STATE_a_42 , LTS_STATE_a_430 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_431 , 4, 'w', LTS_STATE_a_83 , LTS_STATE_a_432 , 3, 'u', LTS_STATE_a_42 , LTS_STATE_a_433 , 4, 'w', LTS_STATE_a_83 , LTS_STATE_a_434 , 1, '0', LTS_STATE_a_42 , LTS_STATE_a_435 , 1, 'l', LTS_STATE_a_29 , LTS_STATE_a_436 , 3, 'n', LTS_STATE_a_438 , LTS_STATE_a_437 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_439 , 6, 'o', LTS_STATE_a_42 , LTS_STATE_a_440 , 2, 'l', LTS_STATE_a_248 , LTS_STATE_a_441 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_42 , 6, 'n', LTS_STATE_a_443 , LTS_STATE_a_442 , 1, 'a', LTS_STATE_a_445 , LTS_STATE_a_444 , 5, 's', LTS_STATE_a_69 , LTS_STATE_a_28 , 5, 't', LTS_STATE_a_446 , LTS_STATE_a_28 , 1, 'h', LTS_STATE_a_28 , LTS_STATE_a_69 , 4, 'f', LTS_STATE_a_69 , LTS_STATE_a_447 , 2, 's', LTS_STATE_a_28 , LTS_STATE_a_448 , 6, 't', LTS_STATE_a_83 , LTS_STATE_a_449 , 3, 'n', LTS_STATE_a_83 , LTS_STATE_a_450 , 6, 't', LTS_STATE_a_451 , LTS_STATE_a_83 , 5, 's', LTS_STATE_a_453 , LTS_STATE_a_452 , 5, 'b', LTS_STATE_a_64 , LTS_STATE_a_454 , 6, 't', LTS_STATE_a_456 , LTS_STATE_a_455 , 5, 'l', LTS_STATE_a_458 , LTS_STATE_a_457 , 3, 'l', LTS_STATE_a_83 , LTS_STATE_a_459 , 1, '0', LTS_STATE_a_461 , LTS_STATE_a_460 , 1, '#', LTS_STATE_a_112 , LTS_STATE_a_108 , 4, 'u', LTS_STATE_a_106 , LTS_STATE_a_462 , 3, 'a', LTS_STATE_a_231 , LTS_STATE_a_463 , 2, 't', LTS_STATE_a_464 , LTS_STATE_a_69 , 1, 'n', LTS_STATE_a_466 , LTS_STATE_a_465 , 4, 'o', LTS_STATE_a_28 , LTS_STATE_a_467 , 4, 't', LTS_STATE_a_28 , LTS_STATE_a_468 , 2, 'r', LTS_STATE_a_28 , LTS_STATE_a_469 , 1, 'e', LTS_STATE_a_42 , LTS_STATE_a_470 , 6, 'e', LTS_STATE_a_472 , LTS_STATE_a_471 , 5, 'a', LTS_STATE_a_474 , LTS_STATE_a_473 , 3, 'p', LTS_STATE_a_29 , LTS_STATE_a_475 , 2, 'c', LTS_STATE_a_477 , LTS_STATE_a_476 , 2, 'r', LTS_STATE_a_101 , LTS_STATE_a_26 , 3, 'v', LTS_STATE_a_29 , LTS_STATE_a_478 , 3, 'c', LTS_STATE_a_26 , LTS_STATE_a_479 , 1, 'i', LTS_STATE_a_26 , LTS_STATE_a_480 , 2, 'a', LTS_STATE_a_28 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_29 , LTS_STATE_a_26 , 2, 's', LTS_STATE_a_26 , LTS_STATE_a_481 , 3, 'h', LTS_STATE_a_483 , LTS_STATE_a_482 , 6, 's', LTS_STATE_a_231 , LTS_STATE_a_28 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_26 , 6, 's', LTS_STATE_a_231 , LTS_STATE_a_484 , 3, 'c', LTS_STATE_a_26 , LTS_STATE_a_485 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_486 , 6, 'b', LTS_STATE_a_101 , LTS_STATE_a_487 , 6, 'm', LTS_STATE_a_26 , LTS_STATE_a_28 , 3, 'n', LTS_STATE_a_231 , LTS_STATE_a_488 , 3, 'g', LTS_STATE_a_101 , LTS_STATE_a_489 , 6, 'o', LTS_STATE_a_231 , LTS_STATE_a_29 , 3, 'p', LTS_STATE_a_29 , LTS_STATE_a_101 , 5, 't', LTS_STATE_a_28 , LTS_STATE_a_29 , 5, 'r', LTS_STATE_a_28 , LTS_STATE_a_490 , 6, '#', LTS_STATE_a_127 , LTS_STATE_a_28 , 1, '0', LTS_STATE_a_492 , LTS_STATE_a_491 , 4, 'b', LTS_STATE_a_494 , LTS_STATE_a_493 , 4, 't', LTS_STATE_a_496 , LTS_STATE_a_495 , 4, 'l', LTS_STATE_a_498 , LTS_STATE_a_497 , 5, 'a', LTS_STATE_a_69 , LTS_STATE_a_499 , 5, 'a', LTS_STATE_a_501 , LTS_STATE_a_500 , 5, 'a', LTS_STATE_a_503 , LTS_STATE_a_502 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_504 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_69 , 5, 't', LTS_STATE_a_506 , LTS_STATE_a_505 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_73 , 3, 'p', LTS_STATE_a_42 , LTS_STATE_a_28 , 6, 'v', LTS_STATE_a_508 , LTS_STATE_a_507 , 2, '#', LTS_STATE_a_510 , LTS_STATE_a_509 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_511 , 1, '0', LTS_STATE_a_513 , LTS_STATE_a_512 , 3, 'n', LTS_STATE_a_29 , LTS_STATE_a_514 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_515 , 1, 'i', LTS_STATE_a_516 , LTS_STATE_a_42 , 1, 'e', LTS_STATE_a_101 , LTS_STATE_a_517 , 5, 's', LTS_STATE_a_519 , LTS_STATE_a_518 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_520 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_521 , 1, '0', LTS_STATE_a_42 , LTS_STATE_a_522 , 2, '#', LTS_STATE_a_524 , LTS_STATE_a_523 , 2, '#', LTS_STATE_a_526 , LTS_STATE_a_525 , 4, 'l', LTS_STATE_a_528 , LTS_STATE_a_527 , 1, 't', LTS_STATE_a_530 , LTS_STATE_a_529 , 4, 'x', LTS_STATE_a_101 , LTS_STATE_a_531 , 2, 'i', LTS_STATE_a_533 , LTS_STATE_a_532 , 4, 'l', LTS_STATE_a_29 , LTS_STATE_a_534 , 3, 'r', LTS_STATE_a_536 , LTS_STATE_a_535 , 2, 'e', LTS_STATE_a_42 , LTS_STATE_a_537 , 1, 'c', LTS_STATE_a_42 , LTS_STATE_a_538 , 2, 's', LTS_STATE_a_540 , LTS_STATE_a_539 , 3, 'l', LTS_STATE_a_73 , LTS_STATE_a_541 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_542 , 3, 'h', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'd', LTS_STATE_a_28 , LTS_STATE_a_543 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_28 , 1, 'b', LTS_STATE_a_28 , LTS_STATE_a_101 , 5, 'l', LTS_STATE_a_101 , LTS_STATE_a_544 , 6, 'h', LTS_STATE_a_106 , LTS_STATE_a_545 , 3, 'h', LTS_STATE_a_64 , LTS_STATE_a_546 , 3, 'b', LTS_STATE_a_64 , LTS_STATE_a_547 , 3, 'f', LTS_STATE_a_83 , LTS_STATE_a_108 , 5, 't', LTS_STATE_a_548 , LTS_STATE_a_83 , 2, 'k', LTS_STATE_a_64 , LTS_STATE_a_83 , 2, 'k', LTS_STATE_a_64 , LTS_STATE_a_549 , 5, 'r', LTS_STATE_a_83 , LTS_STATE_a_550 , 5, 's', LTS_STATE_a_83 , LTS_STATE_a_499 , 3, 'g', LTS_STATE_a_552 , LTS_STATE_a_551 , 6, 'i', LTS_STATE_a_83 , LTS_STATE_a_553 , 6, 'e', LTS_STATE_a_106 , LTS_STATE_a_83 , 2, 'c', LTS_STATE_a_83 , LTS_STATE_a_554 , 6, 'u', LTS_STATE_a_83 , LTS_STATE_a_555 , 4, 'i', LTS_STATE_a_557 , LTS_STATE_a_556 , 3, 'v', LTS_STATE_a_559 , LTS_STATE_a_558 , 1, 'n', LTS_STATE_a_29 , LTS_STATE_a_83 , 2, 's', LTS_STATE_a_561 , LTS_STATE_a_560 , 3, 'h', LTS_STATE_a_563 , LTS_STATE_a_562 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_564 , 1, 'e', LTS_STATE_a_69 , LTS_STATE_a_565 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_566 , 1, 't', LTS_STATE_a_42 , LTS_STATE_a_567 , 3, 'l', LTS_STATE_a_569 , LTS_STATE_a_568 , 3, 'b', LTS_STATE_a_570 , LTS_STATE_a_29 , 5, 'o', LTS_STATE_a_572 , LTS_STATE_a_571 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_573 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_574 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_575 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_576 , 3, 'p', LTS_STATE_a_26 , LTS_STATE_a_577 , 3, 'f', LTS_STATE_a_26 , LTS_STATE_a_578 , 3, 'l', LTS_STATE_a_580 , LTS_STATE_a_579 , 2, 'u', LTS_STATE_a_26 , LTS_STATE_a_581 , 5, 'k', LTS_STATE_a_29 , LTS_STATE_a_582 , 6, 'o', LTS_STATE_a_583 , LTS_STATE_a_29 , 6, 'u', LTS_STATE_a_28 , LTS_STATE_a_584 , 3, 'k', LTS_STATE_a_26 , LTS_STATE_a_101 , 6, '#', LTS_STATE_a_26 , LTS_STATE_a_585 , 6, 'e', LTS_STATE_a_26 , LTS_STATE_a_586 , 6, 'c', LTS_STATE_a_231 , LTS_STATE_a_587 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_588 , 2, 'l', LTS_STATE_a_590 , LTS_STATE_a_589 , 3, 'o', LTS_STATE_a_592 , LTS_STATE_a_591 , 4, 'l', LTS_STATE_a_594 , LTS_STATE_a_593 , 6, 'y', LTS_STATE_a_596 , LTS_STATE_a_595 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_597 , 6, 's', LTS_STATE_a_599 , LTS_STATE_a_598 , 6, 'r', LTS_STATE_a_601 , LTS_STATE_a_600 , 2, 't', LTS_STATE_a_603 , LTS_STATE_a_602 , 2, 's', LTS_STATE_a_605 , LTS_STATE_a_604 , 5, 'c', LTS_STATE_a_29 , LTS_STATE_a_83 , 5, 'o', LTS_STATE_a_607 , LTS_STATE_a_606 , 6, '#', LTS_STATE_a_609 , LTS_STATE_a_608 , 5, 'o', LTS_STATE_a_611 , LTS_STATE_a_610 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_612 , 5, 'h', LTS_STATE_a_83 , LTS_STATE_a_613 , 4, 'c', LTS_STATE_a_615 , LTS_STATE_a_614 , 4, 's', LTS_STATE_a_42 , LTS_STATE_a_29 , 6, 'e', LTS_STATE_a_617 , LTS_STATE_a_616 , 4, 't', LTS_STATE_a_619 , LTS_STATE_a_618 , 4, 'z', LTS_STATE_a_29 , LTS_STATE_a_620 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_621 , 4, 'g', LTS_STATE_a_623 , LTS_STATE_a_622 , 3, 'u', LTS_STATE_a_624 , LTS_STATE_a_42 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_42 , 4, 'z', LTS_STATE_a_101 , LTS_STATE_a_625 , 2, '#', LTS_STATE_a_231 , LTS_STATE_a_29 , 2, 'r', LTS_STATE_a_626 , LTS_STATE_a_42 , 1, 'd', LTS_STATE_a_101 , LTS_STATE_a_42 , 5, 'a', LTS_STATE_a_28 , LTS_STATE_a_627 , 6, 't', LTS_STATE_a_29 , LTS_STATE_a_628 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_629 , 3, 'l', LTS_STATE_a_630 , LTS_STATE_a_42 , 6, 't', LTS_STATE_a_69 , LTS_STATE_a_631 , 1, '#', LTS_STATE_a_633 , LTS_STATE_a_632 , 6, 'k', LTS_STATE_a_635 , LTS_STATE_a_634 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_636 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_637 , 4, 'n', LTS_STATE_a_639 , LTS_STATE_a_638 , 1, '0', LTS_STATE_a_641 , LTS_STATE_a_640 , 3, 'g', LTS_STATE_a_643 , LTS_STATE_a_642 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_42 , 1, '0', LTS_STATE_a_645 , LTS_STATE_a_644 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_646 , 4, 'l', LTS_STATE_a_29 , LTS_STATE_a_42 , 4, 'c', LTS_STATE_a_29 , LTS_STATE_a_647 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_648 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_649 , 1, 'i', LTS_STATE_a_69 , LTS_STATE_a_650 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_651 , 1, 'e', LTS_STATE_a_653 , LTS_STATE_a_652 , 3, 's', LTS_STATE_a_332 , LTS_STATE_a_42 , 3, 'r', LTS_STATE_a_29 , LTS_STATE_a_654 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_42 , 6, 'o', LTS_STATE_a_28 , LTS_STATE_a_655 , 6, 'g', LTS_STATE_a_69 , LTS_STATE_a_656 , 2, 'e', LTS_STATE_a_658 , LTS_STATE_a_657 , 3, 'r', LTS_STATE_a_64 , LTS_STATE_a_83 , 5, 's', LTS_STATE_a_660 , LTS_STATE_a_659 , 2, 't', LTS_STATE_a_64 , LTS_STATE_a_83 , 3, 'r', LTS_STATE_a_83 , LTS_STATE_a_64 , 5, 'b', LTS_STATE_a_83 , LTS_STATE_a_661 , 3, 's', LTS_STATE_a_663 , LTS_STATE_a_662 , 5, 'c', LTS_STATE_a_64 , LTS_STATE_a_664 , 6, 't', LTS_STATE_a_83 , LTS_STATE_a_665 , 1, 'o', LTS_STATE_a_155 , LTS_STATE_a_666 , 6, 'm', LTS_STATE_a_231 , LTS_STATE_a_83 , 4, 'o', LTS_STATE_a_668 , LTS_STATE_a_667 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_28 , 3, 'j', LTS_STATE_a_231 , LTS_STATE_a_69 , 2, 'i', LTS_STATE_a_231 , LTS_STATE_a_69 , 3, 'h', LTS_STATE_a_670 , LTS_STATE_a_669 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_671 , 3, 'g', LTS_STATE_a_673 , LTS_STATE_a_672 , 255, 17, 0,0 , 0,0 , 3, 'u', LTS_STATE_a_29 , LTS_STATE_a_674 , 4, 'm', LTS_STATE_a_28 , LTS_STATE_a_675 , 1, 'e', LTS_STATE_a_28 , LTS_STATE_a_69 , 2, 'o', LTS_STATE_a_42 , LTS_STATE_a_676 , 3, 'p', LTS_STATE_a_678 , LTS_STATE_a_677 , 2, 'u', LTS_STATE_a_28 , LTS_STATE_a_679 , 1, 'e', LTS_STATE_a_231 , LTS_STATE_a_29 , 2, 's', LTS_STATE_a_681 , LTS_STATE_a_680 , 3, 'h', LTS_STATE_a_26 , LTS_STATE_a_29 , 3, 'h', LTS_STATE_a_683 , LTS_STATE_a_682 , 2, 'g', LTS_STATE_a_28 , LTS_STATE_a_684 , 6, '#', LTS_STATE_a_101 , LTS_STATE_a_685 , 6, 'e', LTS_STATE_a_26 , LTS_STATE_a_101 , 1, '#', LTS_STATE_a_687 , LTS_STATE_a_686 , 1, '#', LTS_STATE_a_26 , LTS_STATE_a_688 , 6, 'e', LTS_STATE_a_26 , LTS_STATE_a_689 , 6, 't', LTS_STATE_a_26 , LTS_STATE_a_690 , 3, 'i', LTS_STATE_a_28 , LTS_STATE_a_691 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_692 , 5, 'b', LTS_STATE_a_29 , LTS_STATE_a_693 , 3, 'm', LTS_STATE_a_28 , LTS_STATE_a_694 , 3, 'l', LTS_STATE_a_28 , LTS_STATE_a_695 , 6, 'c', LTS_STATE_a_101 , LTS_STATE_a_696 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_697 , 6, 'e', LTS_STATE_a_699 , LTS_STATE_a_698 , 1, 'n', LTS_STATE_a_28 , LTS_STATE_a_700 , 1, 'c', LTS_STATE_a_127 , LTS_STATE_a_701 , 4, 'n', LTS_STATE_a_703 , LTS_STATE_a_702 , 5, 't', LTS_STATE_a_705 , LTS_STATE_a_704 , 4, 'e', LTS_STATE_a_28 , LTS_STATE_a_706 , 5, 'a', LTS_STATE_a_708 , LTS_STATE_a_707 , 4, 'l', LTS_STATE_a_710 , LTS_STATE_a_709 , 3, 'c', LTS_STATE_a_28 , LTS_STATE_a_69 , 1, '0', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'g', LTS_STATE_a_712 , LTS_STATE_a_711 , 4, 'g', LTS_STATE_a_231 , LTS_STATE_a_713 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_714 , 1, 'd', LTS_STATE_a_42 , LTS_STATE_a_715 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_716 , 5, 's', LTS_STATE_a_718 , LTS_STATE_a_717 , 6, '#', LTS_STATE_a_720 , LTS_STATE_a_719 , 3, 't', LTS_STATE_a_83 , LTS_STATE_a_721 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_722 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_723 , 3, 'v', LTS_STATE_a_725 , LTS_STATE_a_724 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 'm', LTS_STATE_a_727 , LTS_STATE_a_726 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_728 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_729 , 3, 'p', LTS_STATE_a_730 , LTS_STATE_a_83 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_731 , 5, 'h', LTS_STATE_a_83 , LTS_STATE_a_101 , 6, 'c', LTS_STATE_a_733 , LTS_STATE_a_732 , 4, 'n', LTS_STATE_a_735 , LTS_STATE_a_734 , 4, 's', LTS_STATE_a_42 , LTS_STATE_a_736 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_737 , 3, 't', LTS_STATE_a_739 , LTS_STATE_a_738 , 3, 'm', LTS_STATE_a_741 , LTS_STATE_a_740 , 4, 'w', LTS_STATE_a_83 , LTS_STATE_a_742 , 2, 'i', LTS_STATE_a_101 , LTS_STATE_a_743 , 255, 18, 0,0 , 0,0 , 1, 'o', LTS_STATE_a_42 , LTS_STATE_a_744 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_101 , 6, 's', LTS_STATE_a_42 , LTS_STATE_a_745 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_746 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_28 , 2, 'p', LTS_STATE_a_42 , LTS_STATE_a_747 , 1, 'o', LTS_STATE_a_42 , LTS_STATE_a_748 , 1, '0', LTS_STATE_a_750 , LTS_STATE_a_749 , 6, 'r', LTS_STATE_a_752 , LTS_STATE_a_751 , 3, 'v', LTS_STATE_a_754 , LTS_STATE_a_753 , 4, 'c', LTS_STATE_a_29 , LTS_STATE_a_755 , 6, 'n', LTS_STATE_a_42 , LTS_STATE_a_756 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_757 , 4, 'x', LTS_STATE_a_101 , LTS_STATE_a_758 , 2, '0', LTS_STATE_a_101 , LTS_STATE_a_759 , 2, 'o', LTS_STATE_a_29 , LTS_STATE_a_760 , 2, '#', LTS_STATE_a_42 , LTS_STATE_a_231 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_761 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_42 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_762 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_763 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_764 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_741 , 3, 'i', LTS_STATE_a_766 , LTS_STATE_a_765 , 2, 'u', LTS_STATE_a_69 , LTS_STATE_a_767 , 1, 't', LTS_STATE_a_69 , LTS_STATE_a_42 , 1, 't', LTS_STATE_a_42 , LTS_STATE_a_768 , 2, 'e', LTS_STATE_a_248 , LTS_STATE_a_769 , 3, 'g', LTS_STATE_a_42 , LTS_STATE_a_248 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_248 , 5, 'h', LTS_STATE_a_28 , LTS_STATE_a_770 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_28 , 2, 't', LTS_STATE_a_106 , LTS_STATE_a_771 , 6, 'e', LTS_STATE_a_772 , LTS_STATE_a_83 , 3, 'h', LTS_STATE_a_108 , LTS_STATE_a_773 , 3, 'h', LTS_STATE_a_64 , LTS_STATE_a_106 , 6, 'i', LTS_STATE_a_64 , LTS_STATE_a_774 , 6, '#', LTS_STATE_a_83 , LTS_STATE_a_775 , 5, 't', LTS_STATE_a_155 , LTS_STATE_a_83 , 5, 'd', LTS_STATE_a_112 , LTS_STATE_a_776 , 6, 'e', LTS_STATE_a_83 , LTS_STATE_a_777 , 2, 'a', LTS_STATE_a_155 , LTS_STATE_a_778 , 4, 'e', LTS_STATE_a_629 , LTS_STATE_a_779 , 2, 'a', LTS_STATE_a_28 , LTS_STATE_a_106 , 3, 'w', LTS_STATE_a_781 , LTS_STATE_a_780 , 1, 'l', LTS_STATE_a_563 , LTS_STATE_a_782 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_783 , 2, 'a', LTS_STATE_a_101 , LTS_STATE_a_69 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_563 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_784 , 1, '#', LTS_STATE_a_28 , LTS_STATE_a_785 , 3, 'l', LTS_STATE_a_787 , LTS_STATE_a_786 , 5, 'k', LTS_STATE_a_789 , LTS_STATE_a_788 , 5, 'a', LTS_STATE_a_791 , LTS_STATE_a_790 , 2, 'c', LTS_STATE_a_28 , LTS_STATE_a_792 , 3, 'h', LTS_STATE_a_29 , LTS_STATE_a_793 , 3, 'c', LTS_STATE_a_794 , LTS_STATE_a_29 , 2, 'g', LTS_STATE_a_26 , LTS_STATE_a_28 , 6, 'c', LTS_STATE_a_26 , LTS_STATE_a_28 , 6, 'y', LTS_STATE_a_29 , LTS_STATE_a_795 , 2, 'a', LTS_STATE_a_796 , LTS_STATE_a_29 , 1, 'e', LTS_STATE_a_26 , LTS_STATE_a_797 , 3, 'h', LTS_STATE_a_26 , LTS_STATE_a_798 , 3, 'm', LTS_STATE_a_26 , LTS_STATE_a_799 , 6, 'u', LTS_STATE_a_26 , LTS_STATE_a_800 , 1, '#', LTS_STATE_a_26 , LTS_STATE_a_28 , 1, 'a', LTS_STATE_a_28 , LTS_STATE_a_801 , 5, 'c', LTS_STATE_a_803 , LTS_STATE_a_802 , 5, 'p', LTS_STATE_a_231 , LTS_STATE_a_29 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_804 , 3, 'p', LTS_STATE_a_805 , LTS_STATE_a_26 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_806 , 3, 't', LTS_STATE_a_231 , LTS_STATE_a_807 , 3, 'd', LTS_STATE_a_101 , LTS_STATE_a_808 , 3, 'f', LTS_STATE_a_26 , LTS_STATE_a_809 , 2, 't', LTS_STATE_a_28 , LTS_STATE_a_810 , 1, '#', LTS_STATE_a_127 , LTS_STATE_a_28 , 5, 'a', LTS_STATE_a_812 , LTS_STATE_a_811 , 5, 'g', LTS_STATE_a_814 , LTS_STATE_a_813 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_28 , 2, 'c', LTS_STATE_a_28 , LTS_STATE_a_101 , 4, 'n', LTS_STATE_a_816 , LTS_STATE_a_815 , 5, 't', LTS_STATE_a_818 , LTS_STATE_a_817 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_819 , 4, 'h', LTS_STATE_a_821 , LTS_STATE_a_820 , 6, '#', LTS_STATE_a_823 , LTS_STATE_a_822 , 2, 'a', LTS_STATE_a_825 , LTS_STATE_a_824 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_826 , 2, 'u', LTS_STATE_a_69 , LTS_STATE_a_827 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_828 , 3, 'i', LTS_STATE_a_830 , LTS_STATE_a_829 , 5, 'a', LTS_STATE_a_231 , LTS_STATE_a_831 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_832 , 5, 't', LTS_STATE_a_83 , LTS_STATE_a_833 , 5, 'a', LTS_STATE_a_29 , LTS_STATE_a_834 , 3, 'm', LTS_STATE_a_83 , LTS_STATE_a_835 , 4, 'e', LTS_STATE_a_837 , LTS_STATE_a_836 , 6, 'r', LTS_STATE_a_839 , LTS_STATE_a_838 , 6, 'n', LTS_STATE_a_841 , LTS_STATE_a_840 , 4, 'c', LTS_STATE_a_73 , LTS_STATE_a_842 , 5, 'd', LTS_STATE_a_844 , LTS_STATE_a_843 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_845 , 6, 's', LTS_STATE_a_69 , LTS_STATE_a_846 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_847 , 5, 'l', LTS_STATE_a_231 , LTS_STATE_a_83 , 5, 'g', LTS_STATE_a_101 , LTS_STATE_a_848 , 6, 't', LTS_STATE_a_850 , LTS_STATE_a_849 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_851 , 1, '0', LTS_STATE_a_853 , LTS_STATE_a_852 , 1, '0', LTS_STATE_a_854 , LTS_STATE_a_69 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_231 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_855 , 4, 'n', LTS_STATE_a_857 , LTS_STATE_a_856 , 4, 'l', LTS_STATE_a_859 , LTS_STATE_a_858 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_860 , 4, 'n', LTS_STATE_a_42 , LTS_STATE_a_29 , 4, 'y', LTS_STATE_a_42 , LTS_STATE_a_861 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_248 , 4, 'c', LTS_STATE_a_42 , LTS_STATE_a_862 , 6, 'n', LTS_STATE_a_42 , LTS_STATE_a_863 , 3, 'n', LTS_STATE_a_42 , LTS_STATE_a_864 , 6, 'e', LTS_STATE_a_42 , LTS_STATE_a_69 , 6, 'i', LTS_STATE_a_42 , LTS_STATE_a_865 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_866 , 4, 'm', LTS_STATE_a_868 , LTS_STATE_a_867 , 2, 's', LTS_STATE_a_870 , LTS_STATE_a_869 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_871 , 6, 'l', LTS_STATE_a_873 , LTS_STATE_a_872 , 4, 'l', LTS_STATE_a_874 , LTS_STATE_a_563 , 4, 's', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 'b', LTS_STATE_a_42 , LTS_STATE_a_69 , 3, 'b', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'j', LTS_STATE_a_69 , LTS_STATE_a_875 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_876 , 1, '#', LTS_STATE_a_69 , LTS_STATE_a_877 , 3, 'l', LTS_STATE_a_879 , LTS_STATE_a_878 , 4, 'h', LTS_STATE_a_69 , LTS_STATE_a_880 , 4, 'l', LTS_STATE_a_101 , LTS_STATE_a_881 , 4, 'c', LTS_STATE_a_883 , LTS_STATE_a_882 , 2, 'e', LTS_STATE_a_42 , LTS_STATE_a_884 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_885 , 1, 't', LTS_STATE_a_69 , LTS_STATE_a_886 , 1, 'd', LTS_STATE_a_42 , LTS_STATE_a_887 , 3, 'p', LTS_STATE_a_42 , LTS_STATE_a_888 , 1, 'u', LTS_STATE_a_28 , LTS_STATE_a_889 , 1, 'r', LTS_STATE_a_29 , LTS_STATE_a_890 , 3, 'l', LTS_STATE_a_106 , LTS_STATE_a_83 , 3, 'r', LTS_STATE_a_64 , LTS_STATE_a_772 , 5, 's', LTS_STATE_a_64 , LTS_STATE_a_891 , 5, 'm', LTS_STATE_a_64 , LTS_STATE_a_892 , 5, 't', LTS_STATE_a_83 , LTS_STATE_a_64 , 6, '#', LTS_STATE_a_83 , LTS_STATE_a_893 , 2, 'r', LTS_STATE_a_155 , LTS_STATE_a_83 , 4, 'k', LTS_STATE_a_895 , LTS_STATE_a_894 , 3, 'g', LTS_STATE_a_69 , LTS_STATE_a_896 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_897 , 1, 'u', LTS_STATE_a_69 , LTS_STATE_a_898 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'w', LTS_STATE_a_29 , LTS_STATE_a_899 , 4, 'f', LTS_STATE_a_28 , LTS_STATE_a_900 , 1, 'u', LTS_STATE_a_902 , LTS_STATE_a_901 , 1, 'i', LTS_STATE_a_42 , LTS_STATE_a_903 , 5, 'a', LTS_STATE_a_905 , LTS_STATE_a_904 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_906 , 2, 'p', LTS_STATE_a_28 , LTS_STATE_a_907 , 6, 'g', LTS_STATE_a_26 , LTS_STATE_a_28 , 1, 'o', LTS_STATE_a_28 , LTS_STATE_a_908 , 3, 'u', LTS_STATE_a_29 , LTS_STATE_a_909 , 6, 'e', LTS_STATE_a_29 , LTS_STATE_a_910 , 1, 'n', LTS_STATE_a_29 , LTS_STATE_a_911 , 3, 'v', LTS_STATE_a_28 , LTS_STATE_a_231 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_28 , 3, 'l', LTS_STATE_a_26 , LTS_STATE_a_912 , 2, 's', LTS_STATE_a_26 , LTS_STATE_a_29 , 6, 'l', LTS_STATE_a_26 , LTS_STATE_a_913 , 2, 'a', LTS_STATE_a_28 , LTS_STATE_a_914 , 6, 'a', LTS_STATE_a_916 , LTS_STATE_a_915 , 3, 'm', LTS_STATE_a_918 , LTS_STATE_a_917 , 6, 't', LTS_STATE_a_101 , LTS_STATE_a_919 , 6, 'n', LTS_STATE_a_28 , LTS_STATE_a_26 , 6, 'm', LTS_STATE_a_28 , LTS_STATE_a_920 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_921 , 3, 'p', LTS_STATE_a_26 , LTS_STATE_a_922 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_923 , 6, 'n', LTS_STATE_a_127 , LTS_STATE_a_924 , 4, 'l', LTS_STATE_a_926 , LTS_STATE_a_925 , 6, '#', LTS_STATE_a_928 , LTS_STATE_a_927 , 6, '#', LTS_STATE_a_930 , LTS_STATE_a_929 , 6, 'e', LTS_STATE_a_932 , LTS_STATE_a_931 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_933 , 5, 'y', LTS_STATE_a_26 , LTS_STATE_a_934 , 5, 'd', LTS_STATE_a_936 , LTS_STATE_a_935 , 6, 'e', LTS_STATE_a_83 , LTS_STATE_a_937 , 6, 'n', LTS_STATE_a_231 , LTS_STATE_a_938 , 4, 'e', LTS_STATE_a_940 , LTS_STATE_a_939 , 6, '#', LTS_STATE_a_941 , LTS_STATE_a_29 , 6, 's', LTS_STATE_a_83 , LTS_STATE_a_942 , 3, 'b', LTS_STATE_a_83 , LTS_STATE_a_943 , 1, '0', LTS_STATE_a_945 , LTS_STATE_a_944 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_946 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_947 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_948 , 2, 'i', LTS_STATE_a_950 , LTS_STATE_a_949 , 4, 'e', LTS_STATE_a_952 , LTS_STATE_a_951 , 2, 'd', LTS_STATE_a_954 , LTS_STATE_a_953 , 5, 'o', LTS_STATE_a_29 , LTS_STATE_a_955 , 6, 'l', LTS_STATE_a_563 , LTS_STATE_a_956 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_957 , 5, 'l', LTS_STATE_a_83 , LTS_STATE_a_69 , 5, 'a', LTS_STATE_a_29 , LTS_STATE_a_958 , 4, 'h', LTS_STATE_a_960 , LTS_STATE_a_959 , 3, 'm', LTS_STATE_a_28 , LTS_STATE_a_961 , 6, 's', LTS_STATE_a_963 , LTS_STATE_a_962 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_964 , 6, 's', LTS_STATE_a_966 , LTS_STATE_a_965 , 3, 'p', LTS_STATE_a_231 , LTS_STATE_a_967 , 4, 'n', LTS_STATE_a_563 , LTS_STATE_a_101 , 5, 'v', LTS_STATE_a_969 , LTS_STATE_a_968 , 6, 'a', LTS_STATE_a_231 , LTS_STATE_a_970 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_971 , 6, 'm', LTS_STATE_a_231 , LTS_STATE_a_972 , 3, 't', LTS_STATE_a_231 , LTS_STATE_a_973 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_974 , 1, '0', LTS_STATE_a_976 , LTS_STATE_a_975 , 2, 'q', LTS_STATE_a_29 , LTS_STATE_a_977 , 4, 's', LTS_STATE_a_757 , LTS_STATE_a_978 , 1, '#', LTS_STATE_a_980 , LTS_STATE_a_979 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_981 , 3, 'd', LTS_STATE_a_101 , LTS_STATE_a_563 , 1, 'c', LTS_STATE_a_69 , LTS_STATE_a_982 , 2, 'o', LTS_STATE_a_29 , LTS_STATE_a_983 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_984 , 2, 's', LTS_STATE_a_29 , LTS_STATE_a_42 , 1, 'r', LTS_STATE_a_101 , LTS_STATE_a_29 , 3, 'f', LTS_STATE_a_231 , LTS_STATE_a_985 , 4, 'k', LTS_STATE_a_42 , LTS_STATE_a_986 , 2, 'e', LTS_STATE_a_42 , LTS_STATE_a_987 , 3, 'b', LTS_STATE_a_28 , LTS_STATE_a_988 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_989 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_990 , 4, 'i', LTS_STATE_a_28 , LTS_STATE_a_991 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_992 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_993 , 3, 'r', LTS_STATE_a_995 , LTS_STATE_a_994 , 3, 'p', LTS_STATE_a_42 , LTS_STATE_a_996 , 3, 'x', LTS_STATE_a_101 , LTS_STATE_a_997 , 3, 'm', LTS_STATE_a_999 , LTS_STATE_a_998 , 3, 'l', LTS_STATE_a_1001 , LTS_STATE_a_1000 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_1002 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_1003 , 2, 'n', LTS_STATE_a_69 , LTS_STATE_a_29 , 2, 'i', LTS_STATE_a_530 , LTS_STATE_a_42 , 1, 'm', LTS_STATE_a_42 , LTS_STATE_a_1004 , 4, 'm', LTS_STATE_a_1006 , LTS_STATE_a_1005 , 2, '#', LTS_STATE_a_42 , LTS_STATE_a_69 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_1007 , 2, 'p', LTS_STATE_a_42 , LTS_STATE_a_1008 , 1, 'l', LTS_STATE_a_73 , LTS_STATE_a_1009 , 1, 'e', LTS_STATE_a_69 , LTS_STATE_a_42 , 1, 'd', LTS_STATE_a_69 , LTS_STATE_a_42 , 3, 'n', LTS_STATE_a_42 , LTS_STATE_a_1010 , 3, 'r', LTS_STATE_a_1012 , LTS_STATE_a_1011 , 2, 'n', LTS_STATE_a_1013 , LTS_STATE_a_28 , 5, 'd', LTS_STATE_a_83 , LTS_STATE_a_1014 , 6, 'e', LTS_STATE_a_64 , LTS_STATE_a_83 , 6, 'u', LTS_STATE_a_29 , LTS_STATE_a_1015 , 6, 'k', LTS_STATE_a_83 , LTS_STATE_a_1016 , 4, 'h', LTS_STATE_a_1018 , LTS_STATE_a_1017 , 3, 'i', LTS_STATE_a_563 , LTS_STATE_a_1019 , 3, 'f', LTS_STATE_a_101 , LTS_STATE_a_1020 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_231 , 1, 'e', LTS_STATE_a_69 , LTS_STATE_a_1021 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_1022 , 4, 'l', LTS_STATE_a_28 , LTS_STATE_a_1023 , 2, 'r', LTS_STATE_a_42 , LTS_STATE_a_1024 , 2, 'r', LTS_STATE_a_28 , LTS_STATE_a_42 , 1, 'a', LTS_STATE_a_73 , LTS_STATE_a_42 , 5, 'o', LTS_STATE_a_1026 , LTS_STATE_a_1025 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_1027 , 2, 'm', LTS_STATE_a_29 , LTS_STATE_a_231 , 5, 'o', LTS_STATE_a_28 , LTS_STATE_a_1028 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_1029 , 3, 'l', LTS_STATE_a_29 , LTS_STATE_a_1030 , 6, 'i', LTS_STATE_a_231 , LTS_STATE_a_29 , 2, 'i', LTS_STATE_a_231 , LTS_STATE_a_1031 , 6, 'd', LTS_STATE_a_26 , LTS_STATE_a_28 , 6, 't', LTS_STATE_a_1033 , LTS_STATE_a_1032 , 1, 'u', LTS_STATE_a_28 , LTS_STATE_a_1034 , 6, 'o', LTS_STATE_a_1036 , LTS_STATE_a_1035 , 5, 'j', LTS_STATE_a_29 , LTS_STATE_a_1037 , 3, 's', LTS_STATE_a_231 , LTS_STATE_a_910 , 6, 'e', LTS_STATE_a_231 , LTS_STATE_a_1038 , 3, 'g', LTS_STATE_a_231 , LTS_STATE_a_1039 , 6, 'z', LTS_STATE_a_28 , LTS_STATE_a_1040 , 3, 's', LTS_STATE_a_26 , LTS_STATE_a_1041 , 6, 'u', LTS_STATE_a_231 , LTS_STATE_a_1042 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_29 , 6, '#', LTS_STATE_a_1043 , LTS_STATE_a_127 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_1044 , 5, 's', LTS_STATE_a_1046 , LTS_STATE_a_1045 , 6, 'b', LTS_STATE_a_1048 , LTS_STATE_a_1047 , 4, 'h', LTS_STATE_a_231 , LTS_STATE_a_29 , 5, 'c', LTS_STATE_a_1050 , LTS_STATE_a_1049 , 5, 'a', LTS_STATE_a_1052 , LTS_STATE_a_1051 , 6, '#', LTS_STATE_a_101 , LTS_STATE_a_1053 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_1054 , 4, 'm', LTS_STATE_a_1056 , LTS_STATE_a_1055 , 5, 't', LTS_STATE_a_1058 , LTS_STATE_a_1057 , 5, 'm', LTS_STATE_a_1060 , LTS_STATE_a_1059 , 6, 'e', LTS_STATE_a_83 , LTS_STATE_a_1061 , 6, 'a', LTS_STATE_a_83 , LTS_STATE_a_1062 , 6, 'm', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'w', LTS_STATE_a_83 , LTS_STATE_a_1063 , 2, 'c', LTS_STATE_a_69 , LTS_STATE_a_1064 , 2, 'r', LTS_STATE_a_231 , LTS_STATE_a_1065 , 2, 'h', LTS_STATE_a_83 , LTS_STATE_a_1066 , 3, 'f', LTS_STATE_a_83 , LTS_STATE_a_1067 , 4, 'b', LTS_STATE_a_1069 , LTS_STATE_a_1068 , 6, 'i', LTS_STATE_a_1071 , LTS_STATE_a_1070 , 6, 't', LTS_STATE_a_231 , LTS_STATE_a_1072 , 4, 'd', LTS_STATE_a_29 , LTS_STATE_a_1073 , 1, 'o', LTS_STATE_a_69 , LTS_STATE_a_1074 , 3, 'l', LTS_STATE_a_1076 , LTS_STATE_a_1075 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_1077 , 3, 'w', LTS_STATE_a_1079 , LTS_STATE_a_1078 , 3, 'r', LTS_STATE_a_28 , LTS_STATE_a_1080 , 2, 'c', LTS_STATE_a_83 , LTS_STATE_a_1081 , 6, 'n', LTS_STATE_a_1083 , LTS_STATE_a_1082 , 4, 'c', LTS_STATE_a_1085 , LTS_STATE_a_1084 , 6, 'c', LTS_STATE_a_563 , LTS_STATE_a_1086 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_1087 , 3, 'c', LTS_STATE_a_1089 , LTS_STATE_a_1088 , 4, 'n', LTS_STATE_a_1091 , LTS_STATE_a_1090 , 6, 'a', LTS_STATE_a_1093 , LTS_STATE_a_1092 , 3, 'h', LTS_STATE_a_28 , LTS_STATE_a_1094 , 6, 'o', LTS_STATE_a_1096 , LTS_STATE_a_1095 , 4, 'n', LTS_STATE_a_1098 , LTS_STATE_a_1097 , 3, 'f', LTS_STATE_a_42 , LTS_STATE_a_1099 , 4, 't', LTS_STATE_a_1101 , LTS_STATE_a_1100 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1102 , 4, 'v', LTS_STATE_a_69 , LTS_STATE_a_1103 , 6, 'e', LTS_STATE_a_1105 , LTS_STATE_a_1104 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_1106 , 3, 'v', LTS_STATE_a_231 , LTS_STATE_a_1107 , 3, 'b', LTS_STATE_a_29 , LTS_STATE_a_1108 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_1109 , 3, 's', LTS_STATE_a_101 , LTS_STATE_a_1110 , 4, 'n', LTS_STATE_a_29 , LTS_STATE_a_1111 , 6, 'u', LTS_STATE_a_42 , LTS_STATE_a_1112 , 6, 's', LTS_STATE_a_1114 , LTS_STATE_a_1113 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_1115 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_1116 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_1117 , 4, 'z', LTS_STATE_a_42 , LTS_STATE_a_194 , 4, 'l', LTS_STATE_a_1119 , LTS_STATE_a_1118 , 2, 'i', LTS_STATE_a_1121 , LTS_STATE_a_1120 , 2, 's', LTS_STATE_a_29 , LTS_STATE_a_1122 , 2, 'l', LTS_STATE_a_42 , LTS_STATE_a_1123 , 4, 'n', LTS_STATE_a_29 , LTS_STATE_a_101 , 1, '#', LTS_STATE_a_1125 , LTS_STATE_a_1124 , 2, 'b', LTS_STATE_a_29 , LTS_STATE_a_1126 , 3, 'n', LTS_STATE_a_42 , LTS_STATE_a_1127 , 1, '0', LTS_STATE_a_1128 , LTS_STATE_a_42 , 2, 'r', LTS_STATE_a_42 , LTS_STATE_a_69 , 6, 'z', LTS_STATE_a_29 , LTS_STATE_a_1129 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1130 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_874 , 6, 'n', LTS_STATE_a_1132 , LTS_STATE_a_1131 , 6, 'l', LTS_STATE_a_1134 , LTS_STATE_a_1133 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_1135 , 2, 'd', LTS_STATE_a_42 , LTS_STATE_a_1136 , 6, 't', LTS_STATE_a_1138 , LTS_STATE_a_1137 , 6, 'y', LTS_STATE_a_42 , LTS_STATE_a_1139 , 3, 'h', LTS_STATE_a_1141 , LTS_STATE_a_1140 , 4, 'b', LTS_STATE_a_42 , LTS_STATE_a_69 , 2, '#', LTS_STATE_a_1143 , LTS_STATE_a_1142 , 1, '0', LTS_STATE_a_42 , LTS_STATE_a_1144 , 1, 'c', LTS_STATE_a_69 , LTS_STATE_a_42 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_1145 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'l', LTS_STATE_a_1147 , LTS_STATE_a_1146 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_1148 , 3, 'g', LTS_STATE_a_1149 , LTS_STATE_a_42 , 3, 'g', LTS_STATE_a_42 , LTS_STATE_a_1150 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_1151 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_1152 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_28 , 5, 'r', LTS_STATE_a_83 , LTS_STATE_a_1153 , 6, 'i', LTS_STATE_a_83 , LTS_STATE_a_1154 , 6, 'l', LTS_STATE_a_83 , LTS_STATE_a_1155 , 4, 'm', LTS_STATE_a_1157 , LTS_STATE_a_1156 , 2, 'r', LTS_STATE_a_1158 , LTS_STATE_a_69 , 2, 'c', LTS_STATE_a_1160 , LTS_STATE_a_1159 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_1161 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_1162 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_1163 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_28 , 3, 's', LTS_STATE_a_28 , LTS_STATE_a_1164 , 6, '#', LTS_STATE_a_1166 , LTS_STATE_a_1165 , 6, '#', LTS_STATE_a_1167 , LTS_STATE_a_28 , 3, 'h', LTS_STATE_a_1169 , LTS_STATE_a_1168 , 1, 'e', LTS_STATE_a_28 , LTS_STATE_a_1170 , 5, '#', LTS_STATE_a_28 , LTS_STATE_a_1171 , 3, 'i', LTS_STATE_a_28 , LTS_STATE_a_1172 , 1, 's', LTS_STATE_a_29 , LTS_STATE_a_1173 , 1, 'm', LTS_STATE_a_29 , LTS_STATE_a_1174 , 1, 'a', LTS_STATE_a_28 , LTS_STATE_a_26 , 3, 't', LTS_STATE_a_28 , LTS_STATE_a_1175 , 5, 'q', LTS_STATE_a_1177 , LTS_STATE_a_1176 , 5, 't', LTS_STATE_a_1179 , LTS_STATE_a_1178 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_1180 , 6, 'i', LTS_STATE_a_29 , LTS_STATE_a_1181 , 6, 'c', LTS_STATE_a_28 , LTS_STATE_a_1182 , 2, '#', LTS_STATE_a_1183 , LTS_STATE_a_101 , 3, 'k', LTS_STATE_a_26 , LTS_STATE_a_1184 , 3, 'c', LTS_STATE_a_1186 , LTS_STATE_a_1185 , 5, 'y', LTS_STATE_a_127 , LTS_STATE_a_28 , 4, 'w', LTS_STATE_a_1188 , LTS_STATE_a_1187 , 3, 'w', LTS_STATE_a_1190 , LTS_STATE_a_1189 , 6, 'k', LTS_STATE_a_29 , LTS_STATE_a_69 , 3, 'b', LTS_STATE_a_712 , LTS_STATE_a_1191 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_42 , 6, 's', LTS_STATE_a_1193 , LTS_STATE_a_1192 , 6, 'e', LTS_STATE_a_1195 , LTS_STATE_a_1194 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_1196 , 2, 'u', LTS_STATE_a_29 , LTS_STATE_a_1197 , 6, 'i', LTS_STATE_a_42 , LTS_STATE_a_1198 , 3, 'r', LTS_STATE_a_1199 , LTS_STATE_a_42 , 5, 'r', LTS_STATE_a_1201 , LTS_STATE_a_1200 , 5, 'a', LTS_STATE_a_1203 , LTS_STATE_a_1202 , 5, 'n', LTS_STATE_a_1205 , LTS_STATE_a_1204 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1206 , 5, 'u', LTS_STATE_a_69 , LTS_STATE_a_1207 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_231 , 6, 'r', LTS_STATE_a_83 , LTS_STATE_a_29 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1208 , 4, 'o', LTS_STATE_a_28 , LTS_STATE_a_1209 , 1, 'a', LTS_STATE_a_134 , LTS_STATE_a_42 , 2, 'n', LTS_STATE_a_29 , LTS_STATE_a_1210 , 2, 's', LTS_STATE_a_1212 , LTS_STATE_a_1211 , 3, 'c', LTS_STATE_a_83 , LTS_STATE_a_1213 , 3, 'h', LTS_STATE_a_1215 , LTS_STATE_a_1214 , 1, 'b', LTS_STATE_a_42 , LTS_STATE_a_1216 , 6, 'r', LTS_STATE_a_1218 , LTS_STATE_a_1217 , 4, 'l', LTS_STATE_a_231 , LTS_STATE_a_69 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_1219 , 4, 'n', LTS_STATE_a_29 , LTS_STATE_a_69 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_938 , 1, 'n', LTS_STATE_a_42 , LTS_STATE_a_1220 , 1, 'g', LTS_STATE_a_73 , LTS_STATE_a_42 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_1221 , 2, 'a', LTS_STATE_a_1223 , LTS_STATE_a_1222 , 5, 'g', LTS_STATE_a_101 , LTS_STATE_a_1224 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_28 , 2, 'g', LTS_STATE_a_1226 , LTS_STATE_a_1225 , 4, 'g', LTS_STATE_a_69 , LTS_STATE_a_1227 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1228 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_1229 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_1230 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1231 , 5, 'l', LTS_STATE_a_1232 , LTS_STATE_a_29 , 5, 'p', LTS_STATE_a_101 , LTS_STATE_a_1233 , 3, 'o', LTS_STATE_a_28 , LTS_STATE_a_1234 , 5, 'g', LTS_STATE_a_1236 , LTS_STATE_a_1235 , 6, 'e', LTS_STATE_a_29 , LTS_STATE_a_1237 , 5, 'r', LTS_STATE_a_28 , LTS_STATE_a_29 , 5, 'n', LTS_STATE_a_28 , LTS_STATE_a_1238 , 6, 'n', LTS_STATE_a_1240 , LTS_STATE_a_1239 , 4, 'b', LTS_STATE_a_563 , LTS_STATE_a_1241 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_29 , 3, 'j', LTS_STATE_a_69 , LTS_STATE_a_563 , 4, 'b', LTS_STATE_a_1243 , LTS_STATE_a_1242 , 4, 'n', LTS_STATE_a_1245 , LTS_STATE_a_1244 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_1246 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_29 , 4, 'h', LTS_STATE_a_69 , LTS_STATE_a_1247 , 6, '#', LTS_STATE_a_83 , LTS_STATE_a_1248 , 5, 't', LTS_STATE_a_83 , LTS_STATE_a_1249 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_1250 , 6, 'o', LTS_STATE_a_1252 , LTS_STATE_a_1251 , 6, 'e', LTS_STATE_a_231 , LTS_STATE_a_1253 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_1254 , 6, 'y', LTS_STATE_a_69 , LTS_STATE_a_1255 , 5, 'm', LTS_STATE_a_83 , LTS_STATE_a_1256 , 1, '#', LTS_STATE_a_1258 , LTS_STATE_a_1257 , 6, 'k', LTS_STATE_a_609 , LTS_STATE_a_1259 , 4, 'o', LTS_STATE_a_28 , LTS_STATE_a_1260 , 3, 'b', LTS_STATE_a_69 , LTS_STATE_a_1261 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1262 , 3, 'v', LTS_STATE_a_231 , LTS_STATE_a_69 , 2, '#', LTS_STATE_a_1263 , LTS_STATE_a_101 , 2, '#', LTS_STATE_a_231 , LTS_STATE_a_42 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_1264 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_69 , 2, 'g', LTS_STATE_a_1266 , LTS_STATE_a_1265 , 1, '#', LTS_STATE_a_29 , LTS_STATE_a_1267 , 2, '#', LTS_STATE_a_1269 , LTS_STATE_a_1268 , 3, 't', LTS_STATE_a_29 , LTS_STATE_a_1270 , 4, 's', LTS_STATE_a_29 , LTS_STATE_a_42 , 5, 'c', LTS_STATE_a_42 , LTS_STATE_a_1271 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_1272 , 6, 'o', LTS_STATE_a_1274 , LTS_STATE_a_1273 , 4, 'b', LTS_STATE_a_1276 , LTS_STATE_a_1275 , 4, 't', LTS_STATE_a_1278 , LTS_STATE_a_1277 , 2, 'p', LTS_STATE_a_231 , LTS_STATE_a_1279 , 2, 'g', LTS_STATE_a_42 , LTS_STATE_a_1280 , 4, 'v', LTS_STATE_a_1281 , LTS_STATE_a_101 , 3, 'h', LTS_STATE_a_42 , LTS_STATE_a_1282 , 2, 'f', LTS_STATE_a_42 , LTS_STATE_a_1283 , 6, 'i', LTS_STATE_a_69 , LTS_STATE_a_1284 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_1285 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_1286 , 4, 'n', LTS_STATE_a_1288 , LTS_STATE_a_1287 , 4, 'z', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'k', LTS_STATE_a_42 , LTS_STATE_a_1289 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_42 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_272 , 4, 'y', LTS_STATE_a_42 , LTS_STATE_a_1290 , 3, 'g', LTS_STATE_a_42 , LTS_STATE_a_1291 , 1, 'e', LTS_STATE_a_42 , LTS_STATE_a_1292 , 3, 'f', LTS_STATE_a_42 , LTS_STATE_a_1097 , 2, 'n', LTS_STATE_a_73 , LTS_STATE_a_42 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_69 , 1, 'i', LTS_STATE_a_248 , LTS_STATE_a_1293 , 1, 'o', LTS_STATE_a_248 , LTS_STATE_a_332 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_83 , 3, 'f', LTS_STATE_a_1295 , LTS_STATE_a_1294 , 6, 's', LTS_STATE_a_83 , LTS_STATE_a_1296 , 4, 'a', LTS_STATE_a_28 , LTS_STATE_a_1297 , 2, 'g', LTS_STATE_a_101 , LTS_STATE_a_1298 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_29 , 3, 'y', LTS_STATE_a_563 , LTS_STATE_a_1299 , 3, 'h', LTS_STATE_a_69 , LTS_STATE_a_563 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_1300 , 2, 'o', LTS_STATE_a_231 , LTS_STATE_a_1301 , 2, 'i', LTS_STATE_a_29 , LTS_STATE_a_1302 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_73 , 5, '#', LTS_STATE_a_1304 , LTS_STATE_a_1303 , 3, 'y', LTS_STATE_a_29 , LTS_STATE_a_1305 , 2, 'i', LTS_STATE_a_231 , LTS_STATE_a_29 , 1, 'd', LTS_STATE_a_28 , LTS_STATE_a_1306 , 1, 's', LTS_STATE_a_101 , LTS_STATE_a_28 , 6, '#', LTS_STATE_a_28 , LTS_STATE_a_1307 , 1, 'h', LTS_STATE_a_28 , LTS_STATE_a_1308 , 2, 'a', LTS_STATE_a_1309 , LTS_STATE_a_29 , 2, 'e', LTS_STATE_a_231 , LTS_STATE_a_1310 , 3, 'u', LTS_STATE_a_231 , LTS_STATE_a_1311 , 1, 'e', LTS_STATE_a_26 , LTS_STATE_a_28 , 6, 'i', LTS_STATE_a_1313 , LTS_STATE_a_1312 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_231 , 5, 'd', LTS_STATE_a_1315 , LTS_STATE_a_1314 , 3, 'm', LTS_STATE_a_231 , LTS_STATE_a_1316 , 5, 't', LTS_STATE_a_231 , LTS_STATE_a_1317 , 6, 'h', LTS_STATE_a_29 , LTS_STATE_a_401 , 6, 'm', LTS_STATE_a_28 , LTS_STATE_a_1318 , 6, 'n', LTS_STATE_a_1320 , LTS_STATE_a_1319 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_1321 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_1322 , 6, 'a', LTS_STATE_a_231 , LTS_STATE_a_101 , 5, 't', LTS_STATE_a_1324 , LTS_STATE_a_1323 , 6, 'k', LTS_STATE_a_29 , LTS_STATE_a_83 , 6, '#', LTS_STATE_a_1326 , LTS_STATE_a_1325 , 5, 'k', LTS_STATE_a_1328 , LTS_STATE_a_1327 , 6, 'y', LTS_STATE_a_69 , LTS_STATE_a_1329 , 3, 'w', LTS_STATE_a_1331 , LTS_STATE_a_1330 , 5, 't', LTS_STATE_a_69 , LTS_STATE_a_1332 , 6, 'y', LTS_STATE_a_69 , LTS_STATE_a_1333 , 2, 'f', LTS_STATE_a_231 , LTS_STATE_a_1334 , 5, 'd', LTS_STATE_a_1336 , LTS_STATE_a_1335 , 1, 't', LTS_STATE_a_29 , LTS_STATE_a_1337 , 6, 'l', LTS_STATE_a_101 , LTS_STATE_a_1338 , 1, 'a', LTS_STATE_a_42 , LTS_STATE_a_1339 , 4, 'w', LTS_STATE_a_1341 , LTS_STATE_a_1340 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1342 , 5, 'u', LTS_STATE_a_69 , LTS_STATE_a_1343 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_1344 , 6, 'l', LTS_STATE_a_101 , LTS_STATE_a_1345 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_563 , LTS_STATE_a_101 , 5, 'p', LTS_STATE_a_101 , LTS_STATE_a_1346 , 6, 'i', LTS_STATE_a_29 , LTS_STATE_a_101 , 4, 'g', LTS_STATE_a_1348 , LTS_STATE_a_1347 , 3, 'd', LTS_STATE_a_29 , LTS_STATE_a_231 , 3, 'w', LTS_STATE_a_83 , LTS_STATE_a_1349 , 1, 'n', LTS_STATE_a_83 , LTS_STATE_a_1350 , 2, 'e', LTS_STATE_a_1352 , LTS_STATE_a_1351 , 4, 'v', LTS_STATE_a_1354 , LTS_STATE_a_1353 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_1355 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_1356 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_1227 , 6, 'g', LTS_STATE_a_69 , LTS_STATE_a_1357 , 3, 'i', LTS_STATE_a_42 , LTS_STATE_a_1358 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_1359 , 3, 'u', LTS_STATE_a_1361 , LTS_STATE_a_1360 , 3, 'v', LTS_STATE_a_29 , LTS_STATE_a_1362 , 5, 'k', LTS_STATE_a_83 , LTS_STATE_a_29 , 4, 'n', LTS_STATE_a_1364 , LTS_STATE_a_1363 , 6, 'a', LTS_STATE_a_69 , LTS_STATE_a_1365 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 't', LTS_STATE_a_101 , LTS_STATE_a_1366 , 6, 'm', LTS_STATE_a_563 , LTS_STATE_a_1367 , 6, 'e', LTS_STATE_a_29 , LTS_STATE_a_1368 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 'l', LTS_STATE_a_101 , LTS_STATE_a_83 , 4, 'o', LTS_STATE_a_1370 , LTS_STATE_a_1369 , 3, 'v', LTS_STATE_a_1372 , LTS_STATE_a_1371 , 6, 'e', LTS_STATE_a_1374 , LTS_STATE_a_1373 , 5, 'l', LTS_STATE_a_29 , LTS_STATE_a_1375 , 5, 't', LTS_STATE_a_28 , LTS_STATE_a_1376 , 4, 'k', LTS_STATE_a_69 , LTS_STATE_a_1377 , 4, 'x', LTS_STATE_a_101 , LTS_STATE_a_1378 , 4, 'h', LTS_STATE_a_29 , LTS_STATE_a_69 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_1379 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'k', LTS_STATE_a_1381 , LTS_STATE_a_1380 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1382 , 3, 'f', LTS_STATE_a_42 , LTS_STATE_a_1383 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_1384 , 5, 'u', LTS_STATE_a_1386 , LTS_STATE_a_1385 , 5, 'k', LTS_STATE_a_83 , LTS_STATE_a_1387 , 3, 's', LTS_STATE_a_1389 , LTS_STATE_a_1388 , 6, 'e', LTS_STATE_a_1390 , LTS_STATE_a_83 , 3, 'b', LTS_STATE_a_231 , LTS_STATE_a_29 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1391 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1392 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_1393 , 5, 'r', LTS_STATE_a_29 , LTS_STATE_a_1394 , 6, 's', LTS_STATE_a_1396 , LTS_STATE_a_1395 , 2, 'q', LTS_STATE_a_29 , LTS_STATE_a_1397 , 6, 'm', LTS_STATE_a_1399 , LTS_STATE_a_1398 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1400 , 4, 'l', LTS_STATE_a_1402 , LTS_STATE_a_1401 , 4, 'l', LTS_STATE_a_1404 , LTS_STATE_a_1403 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_1405 , 3, 'n', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'l', LTS_STATE_a_1406 , LTS_STATE_a_42 , 4, 'c', LTS_STATE_a_42 , LTS_STATE_a_101 , 1, 'o', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_1408 , LTS_STATE_a_1407 , 3, 'm', LTS_STATE_a_1410 , LTS_STATE_a_1409 , 3, 'x', LTS_STATE_a_101 , LTS_STATE_a_1411 , 1, 't', LTS_STATE_a_42 , LTS_STATE_a_1412 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_1413 , 4, 'm', LTS_STATE_a_1415 , LTS_STATE_a_1414 , 2, 'n', LTS_STATE_a_101 , LTS_STATE_a_42 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_1416 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1417 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_1418 , 6, 'a', LTS_STATE_a_563 , LTS_STATE_a_1419 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_42 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_1420 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_42 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_42 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_1421 , 6, 'y', LTS_STATE_a_1423 , LTS_STATE_a_1422 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_1424 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_1426 , LTS_STATE_a_1425 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_1427 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_42 , 4, 'k', LTS_STATE_a_42 , LTS_STATE_a_1428 , 3, 'g', LTS_STATE_a_29 , LTS_STATE_a_1429 , 3, 'l', LTS_STATE_a_29 , LTS_STATE_a_1430 , 6, 'h', LTS_STATE_a_83 , LTS_STATE_a_1431 , 5, 's', LTS_STATE_a_83 , LTS_STATE_a_64 , 3, 'p', LTS_STATE_a_83 , LTS_STATE_a_64 , 4, 'z', LTS_STATE_a_231 , LTS_STATE_a_1432 , 3, 'h', LTS_STATE_a_672 , LTS_STATE_a_1433 , 1, 't', LTS_STATE_a_231 , LTS_STATE_a_1434 , 3, 'y', LTS_STATE_a_69 , LTS_STATE_a_1435 , 2, 'g', LTS_STATE_a_69 , LTS_STATE_a_1436 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_1437 , 6, 's', LTS_STATE_a_1439 , LTS_STATE_a_1438 , 3, 'g', LTS_STATE_a_28 , LTS_STATE_a_1440 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_1441 , 1, 'm', LTS_STATE_a_29 , LTS_STATE_a_1442 , 5, '#', LTS_STATE_a_28 , LTS_STATE_a_29 , 2, 'l', LTS_STATE_a_28 , LTS_STATE_a_1443 , 5, '#', LTS_STATE_a_29 , LTS_STATE_a_28 , 1, 't', LTS_STATE_a_29 , LTS_STATE_a_1444 , 1, 'a', LTS_STATE_a_28 , LTS_STATE_a_1445 , 6, 'e', LTS_STATE_a_1446 , LTS_STATE_a_29 , 5, 't', LTS_STATE_a_29 , LTS_STATE_a_1447 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_1448 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_29 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_1252 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_1449 , 3, 'b', LTS_STATE_a_1451 , LTS_STATE_a_1450 , 3, 'p', LTS_STATE_a_28 , LTS_STATE_a_1452 , 3, 'm', LTS_STATE_a_28 , LTS_STATE_a_26 , 3, 'h', LTS_STATE_a_28 , LTS_STATE_a_1453 , 3, 'b', LTS_STATE_a_1454 , LTS_STATE_a_29 , 3, 'b', LTS_STATE_a_1456 , LTS_STATE_a_1455 , 4, 't', LTS_STATE_a_1458 , LTS_STATE_a_1457 , 5, 'd', LTS_STATE_a_1460 , LTS_STATE_a_1459 , 5, 'd', LTS_STATE_a_69 , LTS_STATE_a_1461 , 5, 'd', LTS_STATE_a_1462 , LTS_STATE_a_69 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_83 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_1463 , 5, 'a', LTS_STATE_a_1465 , LTS_STATE_a_1464 , 5, 'd', LTS_STATE_a_29 , LTS_STATE_a_83 , 5, 'd', LTS_STATE_a_1467 , LTS_STATE_a_1466 , 6, 'i', LTS_STATE_a_1469 , LTS_STATE_a_1468 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1470 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_1471 , 3, 'l', LTS_STATE_a_1473 , LTS_STATE_a_1472 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_1474 , 6, 'u', LTS_STATE_a_101 , LTS_STATE_a_1475 , 2, 't', LTS_STATE_a_42 , LTS_STATE_a_73 , 5, 'a', LTS_STATE_a_1477 , LTS_STATE_a_1476 , 5, 'a', LTS_STATE_a_69 , LTS_STATE_a_29 , 6, 'i', LTS_STATE_a_1479 , LTS_STATE_a_1478 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1480 , 6, 'z', LTS_STATE_a_101 , LTS_STATE_a_1481 , 5, 'g', LTS_STATE_a_1483 , LTS_STATE_a_1482 , 6, 'i', LTS_STATE_a_1485 , LTS_STATE_a_1484 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_1486 , 3, 't', LTS_STATE_a_563 , LTS_STATE_a_1487 , 3, 'c', LTS_STATE_a_83 , LTS_STATE_a_1488 , 1, 'y', LTS_STATE_a_69 , LTS_STATE_a_29 , 3, 'd', LTS_STATE_a_69 , LTS_STATE_a_1489 , 3, 'r', LTS_STATE_a_83 , LTS_STATE_a_1490 , 3, 'r', LTS_STATE_a_1492 , LTS_STATE_a_1491 , 6, 'r', LTS_STATE_a_42 , LTS_STATE_a_231 , 2, 'c', LTS_STATE_a_28 , LTS_STATE_a_69 , 6, 'l', LTS_STATE_a_1494 , LTS_STATE_a_1493 , 6, 'm', LTS_STATE_a_69 , LTS_STATE_a_1071 , 2, 'o', LTS_STATE_a_1496 , LTS_STATE_a_1495 , 1, 't', LTS_STATE_a_1497 , LTS_STATE_a_42 , 2, 'u', LTS_STATE_a_1499 , LTS_STATE_a_1498 , 6, 'r', LTS_STATE_a_231 , LTS_STATE_a_1500 , 5, 'o', LTS_STATE_a_332 , LTS_STATE_a_1501 , 2, 'v', LTS_STATE_a_69 , LTS_STATE_a_1502 , 5, 'c', LTS_STATE_a_231 , LTS_STATE_a_29 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_1503 , 6, 'e', LTS_STATE_a_42 , LTS_STATE_a_101 , 6, 'p', LTS_STATE_a_563 , LTS_STATE_a_1504 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_1505 , 6, 'e', LTS_STATE_a_1507 , LTS_STATE_a_1506 , 6, 'i', LTS_STATE_a_1508 , LTS_STATE_a_231 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_1509 , 5, 'd', LTS_STATE_a_101 , LTS_STATE_a_1510 , 6, 'i', LTS_STATE_a_1512 , LTS_STATE_a_1511 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_1513 , 5, 'r', LTS_STATE_a_29 , LTS_STATE_a_1514 , 3, 'b', LTS_STATE_a_28 , LTS_STATE_a_1515 , 3, 'c', LTS_STATE_a_1517 , LTS_STATE_a_1516 , 3, 'l', LTS_STATE_a_1519 , LTS_STATE_a_1518 , 4, 'p', LTS_STATE_a_231 , LTS_STATE_a_1520 , 6, 'l', LTS_STATE_a_1522 , LTS_STATE_a_1521 , 3, 'n', LTS_STATE_a_231 , LTS_STATE_a_1523 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_1524 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_1525 , 3, 'b', LTS_STATE_a_42 , LTS_STATE_a_1526 , 3, 'm', LTS_STATE_a_1528 , LTS_STATE_a_1527 , 3, 'v', LTS_STATE_a_563 , LTS_STATE_a_1529 , 3, 'b', LTS_STATE_a_1531 , LTS_STATE_a_1530 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_1532 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_1533 , 3, 'b', LTS_STATE_a_231 , LTS_STATE_a_83 , 6, 'i', LTS_STATE_a_83 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1534 , 3, 'k', LTS_STATE_a_101 , LTS_STATE_a_1535 , 4, 'h', LTS_STATE_a_29 , LTS_STATE_a_1536 , 4, 'b', LTS_STATE_a_1538 , LTS_STATE_a_1537 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_1539 , 3, 't', LTS_STATE_a_1541 , LTS_STATE_a_1540 , 6, 'f', LTS_STATE_a_101 , LTS_STATE_a_1542 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1543 , 4, 'l', LTS_STATE_a_101 , LTS_STATE_a_1544 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_1545 , 1, '0', LTS_STATE_a_69 , LTS_STATE_a_1546 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_1547 , 1, '0', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_42 , LTS_STATE_a_1548 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_42 , 3, 'r', LTS_STATE_a_1550 , LTS_STATE_a_1549 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_1551 , 3, 'j', LTS_STATE_a_69 , LTS_STATE_a_1552 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_1553 , 2, 'c', LTS_STATE_a_1555 , LTS_STATE_a_1554 , 6, 'h', LTS_STATE_a_42 , LTS_STATE_a_1556 , 6, 'e', LTS_STATE_a_28 , LTS_STATE_a_42 , 6, 'r', LTS_STATE_a_1558 , LTS_STATE_a_1557 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_1559 , 6, 'x', LTS_STATE_a_69 , LTS_STATE_a_1560 , 6, 'l', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 't', LTS_STATE_a_101 , LTS_STATE_a_1561 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_29 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_1562 , 4, 'm', LTS_STATE_a_42 , LTS_STATE_a_1563 , 4, 'p', LTS_STATE_a_42 , LTS_STATE_a_1564 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_42 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'p', LTS_STATE_a_69 , LTS_STATE_a_1565 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_1566 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_1567 , 3, 'v', LTS_STATE_a_42 , LTS_STATE_a_1568 , 1, 'd', LTS_STATE_a_69 , LTS_STATE_a_1569 , 5, 't', LTS_STATE_a_1571 , LTS_STATE_a_1570 , 4, 'x', LTS_STATE_a_1573 , LTS_STATE_a_1572 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_1574 , 1, 'b', LTS_STATE_a_69 , LTS_STATE_a_1575 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_1576 , 2, 'a', LTS_STATE_a_1577 , LTS_STATE_a_69 , 3, 'y', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'z', LTS_STATE_a_28 , LTS_STATE_a_1578 , 3, 'y', LTS_STATE_a_29 , LTS_STATE_a_1579 , 2, 's', LTS_STATE_a_1581 , LTS_STATE_a_1580 , 5, 'z', LTS_STATE_a_231 , LTS_STATE_a_1582 , 3, 'c', LTS_STATE_a_28 , LTS_STATE_a_1583 , 5, 'd', LTS_STATE_a_29 , LTS_STATE_a_1584 , 1, 'c', LTS_STATE_a_29 , LTS_STATE_a_1585 , 3, 'p', LTS_STATE_a_26 , LTS_STATE_a_1586 , 5, 'm', LTS_STATE_a_1588 , LTS_STATE_a_1587 , 5, 'p', LTS_STATE_a_231 , LTS_STATE_a_1589 , 3, 'g', LTS_STATE_a_29 , LTS_STATE_a_1590 , 3, 'p', LTS_STATE_a_29 , LTS_STATE_a_1591 , 3, 'c', LTS_STATE_a_28 , LTS_STATE_a_26 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_28 , 6, 'o', LTS_STATE_a_231 , LTS_STATE_a_26 , 3, 'm', LTS_STATE_a_28 , LTS_STATE_a_1592 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_29 , 4, 'e', LTS_STATE_a_1594 , LTS_STATE_a_1593 , 5, 'h', LTS_STATE_a_1596 , LTS_STATE_a_1595 , 2, 'a', LTS_STATE_a_1598 , LTS_STATE_a_1597 , 6, '#', LTS_STATE_a_69 , LTS_STATE_a_1599 , 5, 'y', LTS_STATE_a_69 , LTS_STATE_a_1600 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_1601 , 5, 't', LTS_STATE_a_83 , LTS_STATE_a_1602 , 1, 'e', LTS_STATE_a_1604 , LTS_STATE_a_1603 , 2, 'd', LTS_STATE_a_83 , LTS_STATE_a_1605 , 5, 's', LTS_STATE_a_1607 , LTS_STATE_a_1606 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1608 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_1609 , 1, 'r', LTS_STATE_a_101 , LTS_STATE_a_1610 , 2, 'r', LTS_STATE_a_29 , LTS_STATE_a_1611 , 1, 'f', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 'f', LTS_STATE_a_101 , LTS_STATE_a_1612 , 5, 'y', LTS_STATE_a_1614 , LTS_STATE_a_1613 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1615 , 2, 'l', LTS_STATE_a_69 , LTS_STATE_a_1616 , 3, 'i', LTS_STATE_a_101 , LTS_STATE_a_1617 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 'u', LTS_STATE_a_1619 , LTS_STATE_a_1618 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_1620 , 6, 'e', LTS_STATE_a_1622 , LTS_STATE_a_1621 , 4, 'd', LTS_STATE_a_231 , LTS_STATE_a_101 , 5, 'm', LTS_STATE_a_101 , LTS_STATE_a_1623 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_1624 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1625 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_1626 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_1627 , 5, 'b', LTS_STATE_a_231 , LTS_STATE_a_1628 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_1629 , 6, 'i', LTS_STATE_a_29 , LTS_STATE_a_69 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_1630 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_1631 , 3, 'w', LTS_STATE_a_69 , LTS_STATE_a_83 , 4, 'n', LTS_STATE_a_1632 , LTS_STATE_a_69 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_1633 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_1634 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'r', LTS_STATE_a_1635 , LTS_STATE_a_1121 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_1290 , 3, 'g', LTS_STATE_a_42 , LTS_STATE_a_69 , 5, 'a', LTS_STATE_a_1637 , LTS_STATE_a_1636 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'd', LTS_STATE_a_29 , LTS_STATE_a_1638 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1639 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_1102 , 5, 'n', LTS_STATE_a_69 , LTS_STATE_a_29 , 6, 'f', LTS_STATE_a_563 , LTS_STATE_a_1640 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_1641 , 5, 'y', LTS_STATE_a_1643 , LTS_STATE_a_1642 , 5, 'l', LTS_STATE_a_1645 , LTS_STATE_a_1644 , 5, 'l', LTS_STATE_a_231 , LTS_STATE_a_73 , 5, 't', LTS_STATE_a_1647 , LTS_STATE_a_1646 , 6, 'l', LTS_STATE_a_101 , LTS_STATE_a_1648 , 6, 'a', LTS_STATE_a_1512 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_1649 , 6, 'i', LTS_STATE_a_29 , LTS_STATE_a_1650 , 6, 'e', LTS_STATE_a_28 , LTS_STATE_a_1651 , 3, 'i', LTS_STATE_a_29 , LTS_STATE_a_1652 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_1494 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1653 , 4, 'm', LTS_STATE_a_231 , LTS_STATE_a_1654 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_530 , 6, 'r', LTS_STATE_a_1656 , LTS_STATE_a_1655 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1657 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_231 , 3, 'f', LTS_STATE_a_69 , LTS_STATE_a_1658 , 3, 'n', LTS_STATE_a_231 , LTS_STATE_a_1512 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_1659 , 5, 't', LTS_STATE_a_1661 , LTS_STATE_a_1660 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_1662 , 6, 't', LTS_STATE_a_69 , LTS_STATE_a_101 , 5, 'l', LTS_STATE_a_1664 , LTS_STATE_a_1663 , 5, 'l', LTS_STATE_a_101 , LTS_STATE_a_42 , 3, 'g', LTS_STATE_a_101 , LTS_STATE_a_1186 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_231 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'd', LTS_STATE_a_101 , LTS_STATE_a_1665 , 5, 'l', LTS_STATE_a_29 , LTS_STATE_a_1666 , 2, 'q', LTS_STATE_a_29 , LTS_STATE_a_1667 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_69 , 3, 's', LTS_STATE_a_101 , LTS_STATE_a_1668 , 6, 'k', LTS_STATE_a_29 , LTS_STATE_a_1669 , 4, 'b', LTS_STATE_a_42 , LTS_STATE_a_1670 , 3, 'w', LTS_STATE_a_231 , LTS_STATE_a_1671 , 2, '#', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'n', LTS_STATE_a_29 , LTS_STATE_a_1672 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_1673 , 2, 'c', LTS_STATE_a_69 , LTS_STATE_a_101 , 1, 'd', LTS_STATE_a_101 , LTS_STATE_a_1674 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1675 , 2, 'o', LTS_STATE_a_1677 , LTS_STATE_a_1676 , 2, 'g', LTS_STATE_a_42 , LTS_STATE_a_1678 , 1, 'e', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'n', LTS_STATE_a_42 , LTS_STATE_a_1679 , 4, 'l', LTS_STATE_a_101 , LTS_STATE_a_231 , 2, 'g', LTS_STATE_a_69 , LTS_STATE_a_1680 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_101 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_1681 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_1682 , 4, 't', LTS_STATE_a_274 , LTS_STATE_a_1683 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_1684 , 4, 'v', LTS_STATE_a_1686 , LTS_STATE_a_1685 , 3, 'n', LTS_STATE_a_101 , LTS_STATE_a_1687 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_1688 , 2, 't', LTS_STATE_a_1689 , LTS_STATE_a_42 , 3, 'h', LTS_STATE_a_1691 , LTS_STATE_a_1690 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_1692 , 1, 'e', LTS_STATE_a_42 , LTS_STATE_a_1693 , 2, 'o', LTS_STATE_a_42 , LTS_STATE_a_1694 , 2, 'e', LTS_STATE_a_42 , LTS_STATE_a_1695 , 3, 'd', LTS_STATE_a_248 , LTS_STATE_a_1696 , 3, 't', LTS_STATE_a_64 , LTS_STATE_a_1697 , 6, 'z', LTS_STATE_a_83 , LTS_STATE_a_64 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_1698 , 3, 'n', LTS_STATE_a_563 , LTS_STATE_a_1699 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_1700 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_1701 , 3, 'u', LTS_STATE_a_231 , LTS_STATE_a_1702 , 1, 'r', LTS_STATE_a_563 , LTS_STATE_a_69 , 2, 'a', LTS_STATE_a_1704 , LTS_STATE_a_1703 , 3, 'z', LTS_STATE_a_28 , LTS_STATE_a_1705 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_1706 , 3, 's', LTS_STATE_a_28 , LTS_STATE_a_29 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_1707 , 2, 'a', LTS_STATE_a_28 , LTS_STATE_a_231 , 1, 'm', LTS_STATE_a_28 , LTS_STATE_a_29 , 3, 't', LTS_STATE_a_29 , LTS_STATE_a_1708 , 2, 's', LTS_STATE_a_26 , LTS_STATE_a_1709 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_1710 , 3, 'p', LTS_STATE_a_29 , LTS_STATE_a_1711 , 3, 's', LTS_STATE_a_29 , LTS_STATE_a_1712 , 3, 't', LTS_STATE_a_29 , LTS_STATE_a_1713 , 5, 'l', LTS_STATE_a_29 , LTS_STATE_a_1714 , 6, 'n', LTS_STATE_a_28 , LTS_STATE_a_1715 , 2, 'a', LTS_STATE_a_1717 , LTS_STATE_a_1716 , 6, '#', LTS_STATE_a_42 , LTS_STATE_a_28 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_1718 , 4, 'c', LTS_STATE_a_1720 , LTS_STATE_a_1719 , 4, 'c', LTS_STATE_a_1722 , LTS_STATE_a_1721 , 1, 'h', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_1723 , 5, 't', LTS_STATE_a_69 , LTS_STATE_a_1724 , 3, 'n', LTS_STATE_a_29 , LTS_STATE_a_1725 , 5, 'k', LTS_STATE_a_83 , LTS_STATE_a_101 , 2, 'e', LTS_STATE_a_155 , LTS_STATE_a_69 , 2, 'n', LTS_STATE_a_83 , LTS_STATE_a_155 , 2, 'a', LTS_STATE_a_1727 , LTS_STATE_a_1726 , 6, 'l', LTS_STATE_a_1729 , LTS_STATE_a_1728 , 6, 'k', LTS_STATE_a_101 , LTS_STATE_a_1730 , 6, 'r', LTS_STATE_a_231 , LTS_STATE_a_1731 , 5, 'n', LTS_STATE_a_69 , LTS_STATE_a_1732 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_1733 , 3, 'i', LTS_STATE_a_29 , LTS_STATE_a_1734 , 2, 'd', LTS_STATE_a_1736 , LTS_STATE_a_1735 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_1737 , 2, 'l', LTS_STATE_a_42 , LTS_STATE_a_69 , 3, 'r', LTS_STATE_a_1739 , LTS_STATE_a_1738 , 1, 'g', LTS_STATE_a_69 , LTS_STATE_a_1740 , 1, 'i', LTS_STATE_a_29 , LTS_STATE_a_101 , 5, 'h', LTS_STATE_a_1742 , LTS_STATE_a_1741 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_1743 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_1744 , 6, 'a', LTS_STATE_a_69 , LTS_STATE_a_1745 , 4, 'g', LTS_STATE_a_69 , LTS_STATE_a_29 , 5, 'b', LTS_STATE_a_1746 , LTS_STATE_a_101 , 6, 's', LTS_STATE_a_69 , LTS_STATE_a_1747 , 5, 'a', LTS_STATE_a_101 , LTS_STATE_a_1748 , 6, 'o', LTS_STATE_a_563 , LTS_STATE_a_101 , 6, 'e', LTS_STATE_a_1750 , LTS_STATE_a_1749 , 5, 'v', LTS_STATE_a_231 , LTS_STATE_a_101 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_1751 , 6, 'o', LTS_STATE_a_1753 , LTS_STATE_a_1752 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_1754 , 6, 'v', LTS_STATE_a_101 , LTS_STATE_a_1755 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_29 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_1756 , 2, 'e', LTS_STATE_a_42 , LTS_STATE_a_69 , 5, 'o', LTS_STATE_a_1758 , LTS_STATE_a_1757 , 6, '#', LTS_STATE_a_609 , LTS_STATE_a_1759 , 5, 't', LTS_STATE_a_29 , LTS_STATE_a_1760 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_1761 , 6, 'g', LTS_STATE_a_563 , LTS_STATE_a_1762 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_69 , 5, 'u', LTS_STATE_a_1764 , LTS_STATE_a_1763 , 6, '#', LTS_STATE_a_42 , LTS_STATE_a_1765 , 3, 'c', LTS_STATE_a_1767 , LTS_STATE_a_1766 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_1768 , 5, 'u', LTS_STATE_a_1770 , LTS_STATE_a_1769 , 3, 's', LTS_STATE_a_1771 , LTS_STATE_a_101 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_1772 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_626 , 5, 'u', LTS_STATE_a_101 , LTS_STATE_a_1773 , 3, 'k', LTS_STATE_a_28 , LTS_STATE_a_1774 , 3, 'z', LTS_STATE_a_69 , LTS_STATE_a_1775 , 4, 'g', LTS_STATE_a_231 , LTS_STATE_a_1776 , 4, 'f', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'c', LTS_STATE_a_1778 , LTS_STATE_a_1777 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_1779 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_1780 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_1781 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_1782 , 5, 'k', LTS_STATE_a_1784 , LTS_STATE_a_1783 , 3, 's', LTS_STATE_a_83 , LTS_STATE_a_1785 , 6, 'r', LTS_STATE_a_563 , LTS_STATE_a_1786 , 3, 'f', LTS_STATE_a_83 , LTS_STATE_a_1787 , 3, 'c', LTS_STATE_a_83 , LTS_STATE_a_1788 , 6, 'm', LTS_STATE_a_101 , LTS_STATE_a_1789 , 5, 'd', LTS_STATE_a_29 , LTS_STATE_a_1790 , 6, 'm', LTS_STATE_a_1792 , LTS_STATE_a_1791 , 4, 'k', LTS_STATE_a_29 , LTS_STATE_a_1793 , 6, 'l', LTS_STATE_a_1795 , LTS_STATE_a_1794 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'd', LTS_STATE_a_1797 , LTS_STATE_a_1796 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_1798 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1799 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_1800 , 4, 'p', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'd', LTS_STATE_a_513 , LTS_STATE_a_1801 , 3, 'm', LTS_STATE_a_231 , LTS_STATE_a_69 , 1, 'p', LTS_STATE_a_42 , LTS_STATE_a_1802 , 3, 'r', LTS_STATE_a_1804 , LTS_STATE_a_1803 , 2, 'h', LTS_STATE_a_69 , LTS_STATE_a_1805 , 5, 'g', LTS_STATE_a_1807 , LTS_STATE_a_1806 , 6, 'k', LTS_STATE_a_1809 , LTS_STATE_a_1808 , 4, 'p', LTS_STATE_a_42 , LTS_STATE_a_1810 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_1811 , 6, 't', LTS_STATE_a_69 , LTS_STATE_a_1812 , 6, 'n', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_1813 , 2, 'd', LTS_STATE_a_69 , LTS_STATE_a_1814 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_42 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_1815 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_1816 , 3, 'g', LTS_STATE_a_69 , LTS_STATE_a_1817 , 4, 'm', LTS_STATE_a_42 , LTS_STATE_a_1818 , 1, 'o', LTS_STATE_a_42 , LTS_STATE_a_1819 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_29 , 2, 'a', LTS_STATE_a_248 , LTS_STATE_a_1820 , 3, 'h', LTS_STATE_a_774 , LTS_STATE_a_1821 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_1822 , 3, 'r', LTS_STATE_a_563 , LTS_STATE_a_101 , 3, 'd', LTS_STATE_a_69 , LTS_STATE_a_1823 , 2, 's', LTS_STATE_a_69 , LTS_STATE_a_1824 , 2, 't', LTS_STATE_a_1826 , LTS_STATE_a_1825 , 6, 'l', LTS_STATE_a_28 , LTS_STATE_a_1827 , 6, 'a', LTS_STATE_a_29 , LTS_STATE_a_1828 , 1, 'r', LTS_STATE_a_29 , LTS_STATE_a_28 , 3, 'n', LTS_STATE_a_1830 , LTS_STATE_a_1829 , 5, 'd', LTS_STATE_a_1832 , LTS_STATE_a_1831 , 2, 'l', LTS_STATE_a_29 , LTS_STATE_a_1833 , 2, 'e', LTS_STATE_a_28 , LTS_STATE_a_1834 , 3, 'l', LTS_STATE_a_29 , LTS_STATE_a_1835 , 2, '#', LTS_STATE_a_1315 , LTS_STATE_a_231 , 3, 'd', LTS_STATE_a_29 , LTS_STATE_a_1836 , 3, 'p', LTS_STATE_a_29 , LTS_STATE_a_1837 , 3, 'v', LTS_STATE_a_231 , LTS_STATE_a_1838 , 3, 'g', LTS_STATE_a_28 , LTS_STATE_a_1839 , 5, 'y', LTS_STATE_a_1841 , LTS_STATE_a_1840 , 4, 'o', LTS_STATE_a_28 , LTS_STATE_a_1842 , 4, 'b', LTS_STATE_a_29 , LTS_STATE_a_1843 , 6, '#', LTS_STATE_a_69 , LTS_STATE_a_29 , 1, 'e', LTS_STATE_a_1845 , LTS_STATE_a_1844 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_1846 , 2, 'm', LTS_STATE_a_1847 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_29 , LTS_STATE_a_101 , 5, 'v', LTS_STATE_a_29 , LTS_STATE_a_1848 , 6, 'i', LTS_STATE_a_29 , LTS_STATE_a_1060 , 2, 'i', LTS_STATE_a_1850 , LTS_STATE_a_1849 , 6, 'n', LTS_STATE_a_1852 , LTS_STATE_a_1851 , 2, 'c', LTS_STATE_a_1854 , LTS_STATE_a_1853 , 5, 't', LTS_STATE_a_1855 , LTS_STATE_a_101 , 2, 'x', LTS_STATE_a_101 , LTS_STATE_a_1856 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_1857 , 1, 'a', LTS_STATE_a_101 , LTS_STATE_a_29 , 1, 'e', LTS_STATE_a_101 , LTS_STATE_a_1858 , 1, 'n', LTS_STATE_a_101 , LTS_STATE_a_1859 , 1, 'n', LTS_STATE_a_69 , LTS_STATE_a_1860 , 3, 'v', LTS_STATE_a_101 , LTS_STATE_a_69 , 5, 't', LTS_STATE_a_1862 , LTS_STATE_a_1861 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_1863 , 1, 'e', LTS_STATE_a_563 , LTS_STATE_a_1864 , 1, 'c', LTS_STATE_a_69 , LTS_STATE_a_1865 , 4, 's', LTS_STATE_a_1867 , LTS_STATE_a_1866 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_1868 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_1869 , 6, 'i', LTS_STATE_a_69 , LTS_STATE_a_1870 , 6, 'u', LTS_STATE_a_231 , LTS_STATE_a_69 , 6, 'i', LTS_STATE_a_563 , LTS_STATE_a_1206 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1871 , 5, 'c', LTS_STATE_a_1872 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_1874 , LTS_STATE_a_1873 , 5, 'v', LTS_STATE_a_231 , LTS_STATE_a_1875 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_1876 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_1877 , 2, 'e', LTS_STATE_a_29 , LTS_STATE_a_1878 , 3, 'h', LTS_STATE_a_1880 , LTS_STATE_a_1879 , 1, 'r', LTS_STATE_a_231 , LTS_STATE_a_69 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_1881 , 3, 'a', LTS_STATE_a_29 , LTS_STATE_a_1882 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_1883 , 4, 'h', LTS_STATE_a_28 , LTS_STATE_a_1884 , 2, 'q', LTS_STATE_a_101 , LTS_STATE_a_1885 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_1886 , 6, 'i', LTS_STATE_a_563 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_1888 , LTS_STATE_a_1887 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_1889 , 4, 't', LTS_STATE_a_29 , LTS_STATE_a_1890 , 5, 'u', LTS_STATE_a_1892 , LTS_STATE_a_1891 , 5, 't', LTS_STATE_a_231 , LTS_STATE_a_1893 , 4, 'b', LTS_STATE_a_42 , LTS_STATE_a_1894 , 5, 'y', LTS_STATE_a_101 , LTS_STATE_a_1895 , 6, 's', LTS_STATE_a_42 , LTS_STATE_a_1896 , 6, 'o', LTS_STATE_a_231 , LTS_STATE_a_1186 , 5, 'n', LTS_STATE_a_563 , LTS_STATE_a_1897 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_1898 , 6, '#', LTS_STATE_a_28 , LTS_STATE_a_42 , 6, 'b', LTS_STATE_a_101 , LTS_STATE_a_1899 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_1900 , 4, 'j', LTS_STATE_a_69 , LTS_STATE_a_1901 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_1902 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_1903 , 3, 'c', LTS_STATE_a_1905 , LTS_STATE_a_1904 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_1906 , 3, 'c', LTS_STATE_a_42 , LTS_STATE_a_1907 , 5, 'l', LTS_STATE_a_1909 , LTS_STATE_a_1908 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_1910 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_1911 , 6, 'u', LTS_STATE_a_563 , LTS_STATE_a_101 , 3, 's', LTS_STATE_a_42 , LTS_STATE_a_101 , 3, 'v', LTS_STATE_a_101 , LTS_STATE_a_1912 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_1686 , 5, 'a', LTS_STATE_a_29 , LTS_STATE_a_1913 , 6, 'l', LTS_STATE_a_1915 , LTS_STATE_a_1914 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_28 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_1916 , 2, 'd', LTS_STATE_a_69 , LTS_STATE_a_1917 , 3, 'r', LTS_STATE_a_1918 , LTS_STATE_a_69 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_1919 , 6, 'd', LTS_STATE_a_42 , LTS_STATE_a_69 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_1555 , 2, 'o', LTS_STATE_a_231 , LTS_STATE_a_1920 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_29 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_1921 , 4, 'f', LTS_STATE_a_231 , LTS_STATE_a_1922 , 3, 'k', LTS_STATE_a_1924 , LTS_STATE_a_1923 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_42 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_1925 , 6, 'e', LTS_STATE_a_42 , LTS_STATE_a_1926 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_28 , 6, 'l', LTS_STATE_a_1928 , LTS_STATE_a_1927 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_1929 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_1930 , 3, 'h', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_1931 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_1932 , 2, 'b', LTS_STATE_a_101 , LTS_STATE_a_29 , 4, 'c', LTS_STATE_a_1048 , LTS_STATE_a_1933 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_1282 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_1934 , 4, 's', LTS_STATE_a_69 , LTS_STATE_a_42 , 2, 'p', LTS_STATE_a_42 , LTS_STATE_a_1935 , 1, 'r', LTS_STATE_a_248 , LTS_STATE_a_1936 , 3, 'b', LTS_STATE_a_64 , LTS_STATE_a_1937 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_1938 , 2, 'l', LTS_STATE_a_69 , LTS_STATE_a_1939 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_1940 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_1941 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 't', LTS_STATE_a_1943 , LTS_STATE_a_1942 , 6, 'i', LTS_STATE_a_28 , LTS_STATE_a_29 , 2, 'l', LTS_STATE_a_1945 , LTS_STATE_a_1944 , 1, 'o', LTS_STATE_a_29 , LTS_STATE_a_28 , 5, 's', LTS_STATE_a_28 , LTS_STATE_a_29 , 3, 'i', LTS_STATE_a_28 , LTS_STATE_a_1946 , 6, 'e', LTS_STATE_a_29 , LTS_STATE_a_1947 , 3, 'h', LTS_STATE_a_28 , LTS_STATE_a_1948 , 3, 't', LTS_STATE_a_29 , LTS_STATE_a_1949 , 3, 'j', LTS_STATE_a_29 , LTS_STATE_a_1950 , 2, '#', LTS_STATE_a_1951 , LTS_STATE_a_29 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_1952 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'w', LTS_STATE_a_1954 , LTS_STATE_a_1953 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_1955 , 6, 'i', LTS_STATE_a_1957 , LTS_STATE_a_1956 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_1958 , 2, 'r', LTS_STATE_a_231 , LTS_STATE_a_1959 , 2, 'n', LTS_STATE_a_231 , LTS_STATE_a_1960 , 6, 'a', LTS_STATE_a_1962 , LTS_STATE_a_1961 , 6, '#', LTS_STATE_a_563 , LTS_STATE_a_101 , 1, 'd', LTS_STATE_a_101 , LTS_STATE_a_1963 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_1964 , 3, 'y', LTS_STATE_a_231 , LTS_STATE_a_69 , 6, 'k', LTS_STATE_a_231 , LTS_STATE_a_1965 , 3, 't', LTS_STATE_a_231 , LTS_STATE_a_69 , 1, 'r', LTS_STATE_a_101 , LTS_STATE_a_1966 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_101 , 1, 'i', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_1967 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_1968 , 3, 'r', LTS_STATE_a_29 , LTS_STATE_a_1969 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_1970 , 5, 's', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 'p', LTS_STATE_a_101 , LTS_STATE_a_1971 , 2, 'e', LTS_STATE_a_101 , LTS_STATE_a_1972 , 1, 's', LTS_STATE_a_69 , LTS_STATE_a_1973 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_1974 , 6, 'r', LTS_STATE_a_1976 , LTS_STATE_a_1975 , 5, 's', LTS_STATE_a_69 , LTS_STATE_a_1977 , 6, 'i', LTS_STATE_a_69 , LTS_STATE_a_1978 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_1979 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_1980 , 6, 'd', LTS_STATE_a_231 , LTS_STATE_a_101 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_1981 , 5, 'g', LTS_STATE_a_563 , LTS_STATE_a_101 , 5, 'v', LTS_STATE_a_101 , LTS_STATE_a_1982 , 5, 'g', LTS_STATE_a_101 , LTS_STATE_a_1983 , 4, 's', LTS_STATE_a_69 , LTS_STATE_a_1984 , 6, 'a', LTS_STATE_a_1986 , LTS_STATE_a_1985 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_1987 , 3, 'g', LTS_STATE_a_69 , LTS_STATE_a_1988 , 2, 's', LTS_STATE_a_69 , LTS_STATE_a_1989 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_1990 , 5, 'y', LTS_STATE_a_1992 , LTS_STATE_a_1991 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_1993 , 3, 'p', LTS_STATE_a_231 , LTS_STATE_a_1994 , 2, 'g', LTS_STATE_a_29 , LTS_STATE_a_1995 , 4, 's', LTS_STATE_a_1997 , LTS_STATE_a_1996 , 5, 'r', LTS_STATE_a_1999 , LTS_STATE_a_1998 , 4, 'j', LTS_STATE_a_2001 , LTS_STATE_a_2000 , 3, 'm', LTS_STATE_a_2003 , LTS_STATE_a_2002 , 3, 'b', LTS_STATE_a_42 , LTS_STATE_a_2004 , 5, 'h', LTS_STATE_a_2006 , LTS_STATE_a_2005 , 4, 'g', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'p', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_1675 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2007 , 6, 'e', LTS_STATE_a_231 , LTS_STATE_a_101 , 5, 'v', LTS_STATE_a_563 , LTS_STATE_a_2008 , 6, '#', LTS_STATE_a_101 , LTS_STATE_a_29 , 4, 'n', LTS_STATE_a_2010 , LTS_STATE_a_2009 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_2011 , 6, 't', LTS_STATE_a_2013 , LTS_STATE_a_2012 , 4, 's', LTS_STATE_a_1871 , LTS_STATE_a_69 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2014 , 4, 'b', LTS_STATE_a_231 , LTS_STATE_a_2015 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'k', LTS_STATE_a_101 , LTS_STATE_a_2016 , 3, 'h', LTS_STATE_a_42 , LTS_STATE_a_2017 , 5, 's', LTS_STATE_a_2019 , LTS_STATE_a_2018 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_2020 , 3, 't', LTS_STATE_a_83 , LTS_STATE_a_2021 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_2022 , 3, 'g', LTS_STATE_a_101 , LTS_STATE_a_2023 , 4, 'f', LTS_STATE_a_29 , LTS_STATE_a_2024 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_2025 , 3, 'f', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_2026 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_2027 , 4, 'z', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 's', LTS_STATE_a_2029 , LTS_STATE_a_2028 , 3, 'd', LTS_STATE_a_101 , LTS_STATE_a_2030 , 1, 'o', LTS_STATE_a_69 , LTS_STATE_a_2031 , 2, 'a', LTS_STATE_a_231 , LTS_STATE_a_69 , 4, 's', LTS_STATE_a_42 , LTS_STATE_a_2032 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 's', LTS_STATE_a_42 , LTS_STATE_a_2033 , 2, '#', LTS_STATE_a_2035 , LTS_STATE_a_2034 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_2036 , 4, 'n', LTS_STATE_a_2038 , LTS_STATE_a_2037 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_29 , 3, 's', LTS_STATE_a_42 , LTS_STATE_a_2039 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_2040 , 2, 'c', LTS_STATE_a_69 , LTS_STATE_a_2041 , 4, 'x', LTS_STATE_a_101 , LTS_STATE_a_2042 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_2043 , 3, 's', LTS_STATE_a_42 , LTS_STATE_a_2044 , 1, 'a', LTS_STATE_a_2046 , LTS_STATE_a_2045 , 5, 'b', LTS_STATE_a_64 , LTS_STATE_a_2047 , 3, 't', LTS_STATE_a_2049 , LTS_STATE_a_2048 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_2050 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_2051 , 3, 'b', LTS_STATE_a_69 , LTS_STATE_a_2052 , 2, 'c', LTS_STATE_a_29 , LTS_STATE_a_2053 , 3, 'h', LTS_STATE_a_2054 , LTS_STATE_a_29 , 2, 'h', LTS_STATE_a_28 , LTS_STATE_a_2055 , 1, 'a', LTS_STATE_a_231 , LTS_STATE_a_28 , 3, 'k', LTS_STATE_a_28 , LTS_STATE_a_2056 , 3, 'b', LTS_STATE_a_29 , LTS_STATE_a_2057 , 6, 'n', LTS_STATE_a_28 , LTS_STATE_a_2058 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_2059 , 3, 't', LTS_STATE_a_29 , LTS_STATE_a_2060 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_2061 , 5, 'b', LTS_STATE_a_29 , LTS_STATE_a_2062 , 5, 'u', LTS_STATE_a_2064 , LTS_STATE_a_2063 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_2065 , 6, '#', LTS_STATE_a_2066 , LTS_STATE_a_69 , 4, 's', LTS_STATE_a_2068 , LTS_STATE_a_2067 , 1, 'p', LTS_STATE_a_42 , LTS_STATE_a_2069 , 2, 'm', LTS_STATE_a_101 , LTS_STATE_a_2070 , 1, 'i', LTS_STATE_a_29 , LTS_STATE_a_2071 , 2, 'r', LTS_STATE_a_29 , LTS_STATE_a_231 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2072 , 1, 'd', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_2074 , LTS_STATE_a_2073 , 4, 'f', LTS_STATE_a_231 , LTS_STATE_a_2075 , 3, 'k', LTS_STATE_a_231 , LTS_STATE_a_2076 , 5, 'd', LTS_STATE_a_2078 , LTS_STATE_a_2077 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_2079 , LTS_STATE_a_101 , 3, 'd', LTS_STATE_a_69 , LTS_STATE_a_2080 , 2, 'u', LTS_STATE_a_69 , LTS_STATE_a_2081 , 1, 'o', LTS_STATE_a_69 , LTS_STATE_a_1987 , 2, 'b', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 's', LTS_STATE_a_101 , LTS_STATE_a_1855 , 4, 'h', LTS_STATE_a_29 , LTS_STATE_a_2082 , 4, 'g', LTS_STATE_a_69 , LTS_STATE_a_2083 , 5, 'y', LTS_STATE_a_42 , LTS_STATE_a_2084 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_2085 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_2086 , 6, 't', LTS_STATE_a_101 , LTS_STATE_a_2087 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_231 , 5, 'b', LTS_STATE_a_101 , LTS_STATE_a_2088 , 5, 'b', LTS_STATE_a_101 , LTS_STATE_a_563 , 4, 'f', LTS_STATE_a_69 , LTS_STATE_a_1286 , 6, 'e', LTS_STATE_a_2090 , LTS_STATE_a_2089 , 1, 'a', LTS_STATE_a_101 , LTS_STATE_a_1404 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'w', LTS_STATE_a_83 , LTS_STATE_a_2091 , 2, 'c', LTS_STATE_a_69 , LTS_STATE_a_83 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_2092 , 6, 'e', LTS_STATE_a_2094 , LTS_STATE_a_2093 , 6, '#', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'v', LTS_STATE_a_2096 , LTS_STATE_a_2095 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_2097 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_231 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_2098 , 3, 'n', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_2100 , LTS_STATE_a_2099 , 4, 't', LTS_STATE_a_2102 , LTS_STATE_a_2101 , 3, 'm', LTS_STATE_a_2104 , LTS_STATE_a_2103 , 255, 19, 0,0 , 0,0 , 4, 'k', LTS_STATE_a_69 , LTS_STATE_a_2105 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_1918 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_101 , 5, 'r', LTS_STATE_a_1787 , LTS_STATE_a_2106 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_2107 , 6, 'o', LTS_STATE_a_2109 , LTS_STATE_a_2108 , 5, 'c', LTS_STATE_a_101 , LTS_STATE_a_2110 , 3, 'n', LTS_STATE_a_2029 , LTS_STATE_a_2111 , 3, 'j', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'p', LTS_STATE_a_231 , LTS_STATE_a_2112 , 4, 'c', LTS_STATE_a_2114 , LTS_STATE_a_2113 , 4, 'b', LTS_STATE_a_29 , LTS_STATE_a_1839 , 4, 'h', LTS_STATE_a_29 , LTS_STATE_a_2115 , 4, 's', LTS_STATE_a_69 , LTS_STATE_a_231 , 3, 'b', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_2116 , 5, 'z', LTS_STATE_a_2118 , LTS_STATE_a_2117 , 3, 'f', LTS_STATE_a_83 , LTS_STATE_a_2021 , 6, 'u', LTS_STATE_a_2120 , LTS_STATE_a_2119 , 3, 'b', LTS_STATE_a_83 , LTS_STATE_a_101 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_83 , 3, 't', LTS_STATE_a_83 , LTS_STATE_a_101 , 5, 'h', LTS_STATE_a_29 , LTS_STATE_a_2121 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_2122 , 3, 't', LTS_STATE_a_1286 , LTS_STATE_a_2123 , 2, 's', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'f', LTS_STATE_a_69 , LTS_STATE_a_2124 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_69 , 2, '#', LTS_STATE_a_2126 , LTS_STATE_a_2125 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_2127 , 3, 's', LTS_STATE_a_2129 , LTS_STATE_a_2128 , 2, 'b', LTS_STATE_a_42 , LTS_STATE_a_2130 , 1, '#', LTS_STATE_a_42 , LTS_STATE_a_2131 , 6, 'l', LTS_STATE_a_42 , LTS_STATE_a_2132 , 6, 'm', LTS_STATE_a_42 , LTS_STATE_a_2133 , 2, 'n', LTS_STATE_a_69 , LTS_STATE_a_2134 , 2, 'm', LTS_STATE_a_101 , LTS_STATE_a_231 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_2135 , 6, 'r', LTS_STATE_a_29 , LTS_STATE_a_69 , 2, 'a', LTS_STATE_a_2137 , LTS_STATE_a_2136 , 3, 'c', LTS_STATE_a_2139 , LTS_STATE_a_2138 , 3, 'n', LTS_STATE_a_42 , LTS_STATE_a_2140 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_2141 , 2, 'i', LTS_STATE_a_248 , LTS_STATE_a_69 , 2, 'n', LTS_STATE_a_248 , LTS_STATE_a_2142 , 6, 'c', LTS_STATE_a_64 , LTS_STATE_a_2143 , 2, 'a', LTS_STATE_a_2145 , LTS_STATE_a_2144 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_2146 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_2147 , 1, 'h', LTS_STATE_a_69 , LTS_STATE_a_2148 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_2149 , 3, 'n', LTS_STATE_a_2151 , LTS_STATE_a_2150 , 1, 'e', LTS_STATE_a_231 , LTS_STATE_a_2152 , 3, 'y', LTS_STATE_a_29 , LTS_STATE_a_2153 , 1, 'r', LTS_STATE_a_2155 , LTS_STATE_a_2154 , 3, 'h', LTS_STATE_a_2157 , LTS_STATE_a_2156 , 3, 't', LTS_STATE_a_28 , LTS_STATE_a_29 , 3, 'm', LTS_STATE_a_2158 , LTS_STATE_a_29 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_2159 , 5, 'g', LTS_STATE_a_231 , LTS_STATE_a_29 , 2, '#', LTS_STATE_a_29 , LTS_STATE_a_2160 , 1, 's', LTS_STATE_a_2162 , LTS_STATE_a_2161 , 6, 'l', LTS_STATE_a_2164 , LTS_STATE_a_2163 , 5, 'h', LTS_STATE_a_29 , LTS_STATE_a_2165 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_69 , 6, 'e', LTS_STATE_a_69 , LTS_STATE_a_2166 , 6, '#', LTS_STATE_a_2168 , LTS_STATE_a_2167 , 4, 's', LTS_STATE_a_29 , LTS_STATE_a_2169 , 4, 's', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 'h', LTS_STATE_a_29 , LTS_STATE_a_2170 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_2171 , 5, 'u', LTS_STATE_a_1736 , LTS_STATE_a_2172 , 5, 'c', LTS_STATE_a_231 , LTS_STATE_a_101 , 1, 's', LTS_STATE_a_29 , LTS_STATE_a_2173 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_69 , 2, 'i', LTS_STATE_a_101 , LTS_STATE_a_2174 , 3, 'l', LTS_STATE_a_2176 , LTS_STATE_a_2175 , 6, 'h', LTS_STATE_a_69 , LTS_STATE_a_29 , 1, 'm', LTS_STATE_a_2177 , LTS_STATE_a_69 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_2178 , 4, 'p', LTS_STATE_a_2180 , LTS_STATE_a_2179 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_2181 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_2182 , 6, 'a', LTS_STATE_a_2184 , LTS_STATE_a_2183 , 6, 'a', LTS_STATE_a_29 , LTS_STATE_a_2185 , 6, 'p', LTS_STATE_a_69 , LTS_STATE_a_2186 , 5, 'c', LTS_STATE_a_101 , LTS_STATE_a_563 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2187 , 1, '0', LTS_STATE_a_101 , LTS_STATE_a_2188 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_2189 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_1494 , 5, 'r', LTS_STATE_a_2191 , LTS_STATE_a_2190 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_2192 , 6, 's', LTS_STATE_a_42 , LTS_STATE_a_2193 , 2, 'f', LTS_STATE_a_42 , LTS_STATE_a_69 , 2, 'g', LTS_STATE_a_2195 , LTS_STATE_a_2194 , 4, 'n', LTS_STATE_a_2196 , LTS_STATE_a_69 , 6, 'u', LTS_STATE_a_2198 , LTS_STATE_a_2197 , 4, 'c', LTS_STATE_a_2200 , LTS_STATE_a_2199 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_2201 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_2202 , 3, 'c', LTS_STATE_a_2204 , LTS_STATE_a_2203 , 4, 'c', LTS_STATE_a_2206 , LTS_STATE_a_2205 , 3, 'y', LTS_STATE_a_29 , LTS_STATE_a_2207 , 4, 's', LTS_STATE_a_2209 , LTS_STATE_a_2208 , 4, 'c', LTS_STATE_a_2211 , LTS_STATE_a_2210 , 3, 'm', LTS_STATE_a_2213 , LTS_STATE_a_2212 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_2214 , 5, 'm', LTS_STATE_a_563 , LTS_STATE_a_2215 , 6, 't', LTS_STATE_a_101 , LTS_STATE_a_2216 , 3, 'm', LTS_STATE_a_42 , LTS_STATE_a_2217 , 3, 'y', LTS_STATE_a_29 , LTS_STATE_a_2218 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_231 , 4, 'z', LTS_STATE_a_2220 , LTS_STATE_a_2219 , 4, 'g', LTS_STATE_a_42 , LTS_STATE_a_231 , 5, 'h', LTS_STATE_a_563 , LTS_STATE_a_101 , 3, 's', LTS_STATE_a_83 , LTS_STATE_a_231 , 3, 'b', LTS_STATE_a_2222 , LTS_STATE_a_2221 , 3, 'h', LTS_STATE_a_69 , LTS_STATE_a_2223 , 4, 'm', LTS_STATE_a_29 , LTS_STATE_a_2224 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_2225 , 1, 'e', LTS_STATE_a_69 , LTS_STATE_a_2226 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_2227 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2228 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_2229 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_2230 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_2231 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_69 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_194 , 6, 'i', LTS_STATE_a_28 , LTS_STATE_a_42 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_2232 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_2233 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_2234 , 1, 'r', LTS_STATE_a_29 , LTS_STATE_a_2235 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_2236 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_69 , 3, 't', LTS_STATE_a_2238 , LTS_STATE_a_2237 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_2239 , 3, 'f', LTS_STATE_a_42 , LTS_STATE_a_101 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_2240 , 2, 'c', LTS_STATE_a_248 , LTS_STATE_a_2241 , 3, 'k', LTS_STATE_a_83 , LTS_STATE_a_2242 , 1, 'a', LTS_STATE_a_2244 , LTS_STATE_a_2243 , 3, 'b', LTS_STATE_a_231 , LTS_STATE_a_1424 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2245 , 1, 'i', LTS_STATE_a_69 , LTS_STATE_a_2246 , 1, 'k', LTS_STATE_a_69 , LTS_STATE_a_2247 , 2, 'u', LTS_STATE_a_69 , LTS_STATE_a_2248 , 1, 'a', LTS_STATE_a_2250 , LTS_STATE_a_2249 , 5, 'd', LTS_STATE_a_910 , LTS_STATE_a_231 , 2, 'c', LTS_STATE_a_231 , LTS_STATE_a_2251 , 3, 'f', LTS_STATE_a_231 , LTS_STATE_a_2252 , 1, 'b', LTS_STATE_a_29 , LTS_STATE_a_2253 , 2, 'e', LTS_STATE_a_29 , LTS_STATE_a_28 , 2, 'c', LTS_STATE_a_29 , LTS_STATE_a_231 , 1, 'o', LTS_STATE_a_231 , LTS_STATE_a_2254 , 5, 's', LTS_STATE_a_231 , LTS_STATE_a_29 , 5, 's', LTS_STATE_a_29 , LTS_STATE_a_2255 , 5, 'n', LTS_STATE_a_231 , LTS_STATE_a_29 , 6, '#', LTS_STATE_a_2257 , LTS_STATE_a_2256 , 3, 'i', LTS_STATE_a_248 , LTS_STATE_a_2258 , 4, 't', LTS_STATE_a_2260 , LTS_STATE_a_2259 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_2261 , 4, 't', LTS_STATE_a_29 , LTS_STATE_a_155 , 4, 'g', LTS_STATE_a_2263 , LTS_STATE_a_2262 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_2264 , 5, 'h', LTS_STATE_a_248 , LTS_STATE_a_101 , 3, 'r', LTS_STATE_a_29 , LTS_STATE_a_101 , 6, '#', LTS_STATE_a_906 , LTS_STATE_a_29 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2265 , 2, 'n', LTS_STATE_a_101 , LTS_STATE_a_2266 , 4, 'd', LTS_STATE_a_2268 , LTS_STATE_a_2267 , 2, 'o', LTS_STATE_a_2270 , LTS_STATE_a_2269 , 2, 'g', LTS_STATE_a_563 , LTS_STATE_a_2271 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_2272 , 2, 'b', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_783 , 5, 't', LTS_STATE_a_2274 , LTS_STATE_a_2273 , 5, 'p', LTS_STATE_a_2275 , LTS_STATE_a_101 , 5, 'c', LTS_STATE_a_69 , LTS_STATE_a_2276 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_2277 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_2278 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'q', LTS_STATE_a_101 , LTS_STATE_a_1533 , 6, 'd', LTS_STATE_a_101 , LTS_STATE_a_2279 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_83 , 3, 'v', LTS_STATE_a_69 , LTS_STATE_a_2280 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_2281 , 3, 'h', LTS_STATE_a_2283 , LTS_STATE_a_2282 , 4, 'g', LTS_STATE_a_42 , LTS_STATE_a_2284 , 5, 'l', LTS_STATE_a_2286 , LTS_STATE_a_2285 , 4, 't', LTS_STATE_a_2288 , LTS_STATE_a_2287 , 4, 'n', LTS_STATE_a_2290 , LTS_STATE_a_2289 , 4, 'n', LTS_STATE_a_231 , LTS_STATE_a_101 , 5, 'd', LTS_STATE_a_69 , LTS_STATE_a_29 , 6, 'o', LTS_STATE_a_2292 , LTS_STATE_a_2291 , 5, 'q', LTS_STATE_a_2294 , LTS_STATE_a_2293 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_2295 , 5, 'h', LTS_STATE_a_2297 , LTS_STATE_a_2296 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_2298 , 3, 'p', LTS_STATE_a_1205 , LTS_STATE_a_101 , 5, 'k', LTS_STATE_a_2300 , LTS_STATE_a_2299 , 4, 'm', LTS_STATE_a_231 , LTS_STATE_a_2301 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_2302 , 5, 'c', LTS_STATE_a_101 , LTS_STATE_a_2303 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_2304 , 3, 'm', LTS_STATE_a_2305 , LTS_STATE_a_101 , 5, 's', LTS_STATE_a_101 , LTS_STATE_a_2306 , 4, 't', LTS_STATE_a_2307 , LTS_STATE_a_101 , 3, 'b', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_2308 , 5, 'c', LTS_STATE_a_2309 , LTS_STATE_a_101 , 3, 'p', LTS_STATE_a_231 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_2310 , 6, 'd', LTS_STATE_a_231 , LTS_STATE_a_2311 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_2312 , 3, 's', LTS_STATE_a_2314 , LTS_STATE_a_2313 , 3, 'n', LTS_STATE_a_231 , LTS_STATE_a_69 , 6, 's', LTS_STATE_a_83 , LTS_STATE_a_2315 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_2316 , 3, 'g', LTS_STATE_a_231 , LTS_STATE_a_101 , 6, 'o', LTS_STATE_a_83 , LTS_STATE_a_2317 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_2318 , 2, 'u', LTS_STATE_a_69 , LTS_STATE_a_2319 , 4, 'm', LTS_STATE_a_2321 , LTS_STATE_a_2320 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2322 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2323 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_597 , 4, 'l', LTS_STATE_a_101 , LTS_STATE_a_2324 , 5, 't', LTS_STATE_a_42 , LTS_STATE_a_2325 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_2326 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_2327 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_2328 , 3, 'l', LTS_STATE_a_2288 , LTS_STATE_a_29 , 3, 'l', LTS_STATE_a_2330 , LTS_STATE_a_2329 , 6, 'r', LTS_STATE_a_2331 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2332 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_2333 , 6, '#', LTS_STATE_a_248 , LTS_STATE_a_69 , 3, 'l', LTS_STATE_a_2335 , LTS_STATE_a_2334 , 4, 'f', LTS_STATE_a_69 , LTS_STATE_a_2336 , 4, 'd', LTS_STATE_a_29 , LTS_STATE_a_2337 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_563 , 2, 's', LTS_STATE_a_563 , LTS_STATE_a_2338 , 1, 'r', LTS_STATE_a_69 , LTS_STATE_a_2339 , 3, 'd', LTS_STATE_a_69 , LTS_STATE_a_2340 , 6, 'h', LTS_STATE_a_29 , LTS_STATE_a_2341 , 2, 'n', LTS_STATE_a_28 , LTS_STATE_a_29 , 1, 'r', LTS_STATE_a_231 , LTS_STATE_a_29 , 3, 'b', LTS_STATE_a_29 , LTS_STATE_a_2342 , 1, 'h', LTS_STATE_a_28 , LTS_STATE_a_2343 , 2, 'n', LTS_STATE_a_29 , LTS_STATE_a_2344 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_2345 , 4, 'p', LTS_STATE_a_2347 , LTS_STATE_a_2346 , 4, 'h', LTS_STATE_a_69 , LTS_STATE_a_2348 , 2, 'q', LTS_STATE_a_29 , LTS_STATE_a_2349 , 6, 'a', LTS_STATE_a_29 , LTS_STATE_a_2350 , 2, 'n', LTS_STATE_a_101 , LTS_STATE_a_2351 , 1, 'n', LTS_STATE_a_101 , LTS_STATE_a_231 , 4, 'z', LTS_STATE_a_29 , LTS_STATE_a_2352 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_2353 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_1723 , 2, 's', LTS_STATE_a_2355 , LTS_STATE_a_2354 , 3, 'v', LTS_STATE_a_69 , LTS_STATE_a_2356 , 1, 'm', LTS_STATE_a_2358 , LTS_STATE_a_2357 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_231 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_2359 , 1, 'i', LTS_STATE_a_29 , LTS_STATE_a_2360 , 6, 't', LTS_STATE_a_69 , LTS_STATE_a_2361 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2362 , 6, 'e', LTS_STATE_a_2364 , LTS_STATE_a_2363 , 4, 't', LTS_STATE_a_2365 , LTS_STATE_a_101 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_2366 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_2367 , 5, 'c', LTS_STATE_a_2366 , LTS_STATE_a_2368 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_2369 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_2370 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_83 , 3, 't', LTS_STATE_a_69 , LTS_STATE_a_83 , 3, 'y', LTS_STATE_a_2372 , LTS_STATE_a_2371 , 5, 'u', LTS_STATE_a_29 , LTS_STATE_a_2373 , 4, 'h', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 'h', LTS_STATE_a_2375 , LTS_STATE_a_2374 , 4, 'b', LTS_STATE_a_42 , LTS_STATE_a_2376 , 3, 'r', LTS_STATE_a_2378 , LTS_STATE_a_2377 , 2, 'p', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'c', LTS_STATE_a_42 , LTS_STATE_a_2379 , 2, 'b', LTS_STATE_a_101 , LTS_STATE_a_2380 , 6, 'i', LTS_STATE_a_2382 , LTS_STATE_a_2381 , 5, 'k', LTS_STATE_a_2300 , LTS_STATE_a_2383 , 5, 's', LTS_STATE_a_101 , LTS_STATE_a_2384 , 3, 'p', LTS_STATE_a_231 , LTS_STATE_a_2385 , 4, 'z', LTS_STATE_a_231 , LTS_STATE_a_2386 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 'i', LTS_STATE_a_248 , LTS_STATE_a_69 , 3, 'g', LTS_STATE_a_231 , LTS_STATE_a_2387 , 5, 'h', LTS_STATE_a_2389 , LTS_STATE_a_2388 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 'c', LTS_STATE_a_563 , LTS_STATE_a_2390 , 4, 'm', LTS_STATE_a_29 , LTS_STATE_a_2391 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'n', LTS_STATE_a_101 , LTS_STATE_a_2392 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_2393 , 3, 'h', LTS_STATE_a_42 , LTS_STATE_a_2394 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_2395 , 3, 'c', LTS_STATE_a_2397 , LTS_STATE_a_2396 , 6, 'i', LTS_STATE_a_231 , LTS_STATE_a_101 , 6, 'e', LTS_STATE_a_563 , LTS_STATE_a_2398 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_2399 , 6, 'd', LTS_STATE_a_101 , LTS_STATE_a_2400 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_2401 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_231 , 6, 'm', LTS_STATE_a_83 , LTS_STATE_a_2402 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_83 , 6, 'e', LTS_STATE_a_83 , LTS_STATE_a_29 , 1, 'm', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_29 , LTS_STATE_a_2403 , 4, 'l', LTS_STATE_a_2405 , LTS_STATE_a_2404 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_2406 , 2, 'g', LTS_STATE_a_101 , LTS_STATE_a_2407 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_274 , 3, 'l', LTS_STATE_a_2409 , LTS_STATE_a_2408 , 6, 'i', LTS_STATE_a_42 , LTS_STATE_a_2410 , 6, 'a', LTS_STATE_a_2412 , LTS_STATE_a_2411 , 4, 'b', LTS_STATE_a_231 , LTS_STATE_a_69 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_2413 , 4, 'f', LTS_STATE_a_42 , LTS_STATE_a_2414 , 6, 'r', LTS_STATE_a_2331 , LTS_STATE_a_2415 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_42 , 6, 'b', LTS_STATE_a_42 , LTS_STATE_a_2416 , 1, 'h', LTS_STATE_a_42 , LTS_STATE_a_2417 , 5, 's', LTS_STATE_a_83 , LTS_STATE_a_2418 , 5, 'd', LTS_STATE_a_83 , LTS_STATE_a_64 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_2419 , 4, 't', LTS_STATE_a_563 , LTS_STATE_a_2420 , 1, 'a', LTS_STATE_a_563 , LTS_STATE_a_69 , 2, 'o', LTS_STATE_a_563 , LTS_STATE_a_69 , 1, 'l', LTS_STATE_a_69 , LTS_STATE_a_2421 , 3, 'i', LTS_STATE_a_29 , LTS_STATE_a_2422 , 3, 'm', LTS_STATE_a_2424 , LTS_STATE_a_2423 , 2, 'r', LTS_STATE_a_2426 , LTS_STATE_a_2425 , 1, 'i', LTS_STATE_a_231 , LTS_STATE_a_2427 , 3, 'b', LTS_STATE_a_2428 , LTS_STATE_a_29 , 5, 'r', LTS_STATE_a_2430 , LTS_STATE_a_2429 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2431 , 5, 'z', LTS_STATE_a_1670 , LTS_STATE_a_2432 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_2433 , 6, '#', LTS_STATE_a_29 , LTS_STATE_a_559 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_2434 , 1, 'p', LTS_STATE_a_69 , LTS_STATE_a_2435 , 6, 'a', LTS_STATE_a_29 , LTS_STATE_a_231 , 2, 'd', LTS_STATE_a_101 , LTS_STATE_a_2436 , 3, 't', LTS_STATE_a_563 , LTS_STATE_a_101 , 6, 'u', LTS_STATE_a_101 , LTS_STATE_a_2437 , 4, 'z', LTS_STATE_a_101 , LTS_STATE_a_69 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_897 , 3, 'l', LTS_STATE_a_2439 , LTS_STATE_a_2438 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_2440 , 1, 'a', LTS_STATE_a_101 , LTS_STATE_a_2441 , 6, 'e', LTS_STATE_a_1855 , LTS_STATE_a_29 , 4, 'c', LTS_STATE_a_2443 , LTS_STATE_a_2442 , 5, 'c', LTS_STATE_a_563 , LTS_STATE_a_2444 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2445 , 6, 'e', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 't', LTS_STATE_a_69 , LTS_STATE_a_2446 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_2447 , 6, 'l', LTS_STATE_a_563 , LTS_STATE_a_101 , 4, 'h', LTS_STATE_a_69 , LTS_STATE_a_2448 , 2, 'o', LTS_STATE_a_1826 , LTS_STATE_a_2449 , 5, 't', LTS_STATE_a_69 , LTS_STATE_a_101 , 2, 'b', LTS_STATE_a_29 , LTS_STATE_a_2450 , 5, 'c', LTS_STATE_a_2452 , LTS_STATE_a_2451 , 5, 'g', LTS_STATE_a_42 , LTS_STATE_a_2453 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2454 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_2455 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_2456 , 6, 'n', LTS_STATE_a_42 , LTS_STATE_a_2457 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_274 , 6, 'r', LTS_STATE_a_2459 , LTS_STATE_a_2458 , 5, 't', LTS_STATE_a_2461 , LTS_STATE_a_2460 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_2462 , 3, 't', LTS_STATE_a_231 , LTS_STATE_a_2463 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_563 , 6, 'r', LTS_STATE_a_563 , LTS_STATE_a_2464 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_2465 , 5, 'r', LTS_STATE_a_2467 , LTS_STATE_a_2466 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_2468 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_2469 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2470 , 6, 'n', LTS_STATE_a_69 , LTS_STATE_a_2471 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2472 , 3, 't', LTS_STATE_a_42 , LTS_STATE_a_101 , 3, 'g', LTS_STATE_a_101 , LTS_STATE_a_757 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_2473 , 5, 'c', LTS_STATE_a_1981 , LTS_STATE_a_101 , 6, 'o', LTS_STATE_a_2474 , LTS_STATE_a_101 , 6, 'v', LTS_STATE_a_231 , LTS_STATE_a_2475 , 4, 'p', LTS_STATE_a_69 , LTS_STATE_a_2476 , 3, 'b', LTS_STATE_a_69 , LTS_STATE_a_2477 , 3, 'h', LTS_STATE_a_2478 , LTS_STATE_a_101 , 4, 'n', LTS_STATE_a_2479 , LTS_STATE_a_1426 , 6, 'g', LTS_STATE_a_101 , LTS_STATE_a_2480 , 6, 'g', LTS_STATE_a_69 , LTS_STATE_a_2481 , 2, '#', LTS_STATE_a_69 , LTS_STATE_a_2482 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_257 , 3, 'f', LTS_STATE_a_42 , LTS_STATE_a_2483 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 'o', LTS_STATE_a_42 , LTS_STATE_a_28 , 6, 'y', LTS_STATE_a_2485 , LTS_STATE_a_2484 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_69 , 2, 's', LTS_STATE_a_69 , LTS_STATE_a_2486 , 6, 'n', LTS_STATE_a_2488 , LTS_STATE_a_2487 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_2489 , 1, 'c', LTS_STATE_a_42 , LTS_STATE_a_2490 , 3, 'm', LTS_STATE_a_83 , LTS_STATE_a_2491 , 2, 'i', LTS_STATE_a_563 , LTS_STATE_a_2492 , 3, 'i', LTS_STATE_a_101 , LTS_STATE_a_2493 , 2, 'e', LTS_STATE_a_69 , LTS_STATE_a_2494 , 1, 'r', LTS_STATE_a_29 , LTS_STATE_a_2495 , 1, 'l', LTS_STATE_a_28 , LTS_STATE_a_2496 , 1, 'a', LTS_STATE_a_29 , LTS_STATE_a_2497 , 1, 'o', LTS_STATE_a_28 , LTS_STATE_a_2498 , 3, 'g', LTS_STATE_a_28 , LTS_STATE_a_29 , 2, 'r', LTS_STATE_a_231 , LTS_STATE_a_29 , 5, 'b', LTS_STATE_a_231 , LTS_STATE_a_29 , 5, 'h', LTS_STATE_a_2500 , LTS_STATE_a_2499 , 3, 'p', LTS_STATE_a_42 , LTS_STATE_a_2501 , 5, 's', LTS_STATE_a_101 , LTS_STATE_a_2502 , 4, 's', LTS_STATE_a_2504 , LTS_STATE_a_2503 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2505 , 3, 'l', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'k', LTS_STATE_a_563 , LTS_STATE_a_2506 , 1, 'e', LTS_STATE_a_101 , LTS_STATE_a_2507 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2508 , 5, 'n', LTS_STATE_a_1208 , LTS_STATE_a_2509 , 6, 'e', LTS_STATE_a_2510 , LTS_STATE_a_101 , 5, 'n', LTS_STATE_a_101 , LTS_STATE_a_29 , 3, 's', LTS_STATE_a_29 , LTS_STATE_a_2511 , 4, 'z', LTS_STATE_a_231 , LTS_STATE_a_2512 , 5, 'k', LTS_STATE_a_2514 , LTS_STATE_a_2513 , 5, 'v', LTS_STATE_a_101 , LTS_STATE_a_2515 , 6, 'e', LTS_STATE_a_69 , LTS_STATE_a_2516 , 4, 'd', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_2517 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_2518 , 4, 'h', LTS_STATE_a_2520 , LTS_STATE_a_2519 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2521 , 2, 'o', LTS_STATE_a_69 , LTS_STATE_a_2522 , 2, 'f', LTS_STATE_a_231 , LTS_STATE_a_101 , 5, 'b', LTS_STATE_a_42 , LTS_STATE_a_2070 , 2, 'b', LTS_STATE_a_101 , LTS_STATE_a_2523 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_2524 , 2, 'g', LTS_STATE_a_42 , LTS_STATE_a_29 , 6, 's', LTS_STATE_a_29 , LTS_STATE_a_2525 , 5, 'z', LTS_STATE_a_2527 , LTS_STATE_a_2526 , 5, 't', LTS_STATE_a_101 , LTS_STATE_a_2528 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_2529 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_2530 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_2531 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2214 , 6, 'u', LTS_STATE_a_2533 , LTS_STATE_a_2532 , 3, 'f', LTS_STATE_a_101 , LTS_STATE_a_2534 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_2535 , 4, 'g', LTS_STATE_a_42 , LTS_STATE_a_2536 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2537 , 5, 't', LTS_STATE_a_2539 , LTS_STATE_a_2538 , 5, 'n', LTS_STATE_a_101 , LTS_STATE_a_2540 , 4, 'b', LTS_STATE_a_1417 , LTS_STATE_a_2541 , 5, 'z', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_2542 , 5, 'h', LTS_STATE_a_101 , LTS_STATE_a_563 , 4, 'g', LTS_STATE_a_231 , LTS_STATE_a_2543 , 3, 'j', LTS_STATE_a_69 , LTS_STATE_a_2544 , 4, 'v', LTS_STATE_a_2546 , LTS_STATE_a_2545 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_2316 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_2547 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_2548 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_2549 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'v', LTS_STATE_a_101 , LTS_STATE_a_2550 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_2551 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_42 , 3, 'h', LTS_STATE_a_42 , LTS_STATE_a_2552 , 4, 'b', LTS_STATE_a_42 , LTS_STATE_a_2553 , 3, 'g', LTS_STATE_a_42 , LTS_STATE_a_2554 , 4, 's', LTS_STATE_a_42 , LTS_STATE_a_2555 , 2, 'l', LTS_STATE_a_69 , LTS_STATE_a_2556 , 5, 'p', LTS_STATE_a_83 , LTS_STATE_a_64 , 3, 'u', LTS_STATE_a_563 , LTS_STATE_a_2557 , 4, 'c', LTS_STATE_a_563 , LTS_STATE_a_101 , 3, 'k', LTS_STATE_a_69 , LTS_STATE_a_2558 , 1, 'b', LTS_STATE_a_231 , LTS_STATE_a_2559 , 1, 'u', LTS_STATE_a_29 , LTS_STATE_a_2560 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_2561 , 3, 'u', LTS_STATE_a_29 , LTS_STATE_a_2562 , 6, 'e', LTS_STATE_a_2564 , LTS_STATE_a_2563 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_2565 , 6, 'e', LTS_STATE_a_2567 , LTS_STATE_a_2566 , 6, 's', LTS_STATE_a_101 , LTS_STATE_a_2568 , 5, 'p', LTS_STATE_a_2570 , LTS_STATE_a_2569 , 5, 's', LTS_STATE_a_2571 , LTS_STATE_a_101 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_29 , 4, 'd', LTS_STATE_a_29 , LTS_STATE_a_2572 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_2573 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_2574 , 3, 's', LTS_STATE_a_29 , LTS_STATE_a_2575 , 2, 'p', LTS_STATE_a_101 , LTS_STATE_a_29 , 1, 'd', LTS_STATE_a_101 , LTS_STATE_a_2576 , 5, 'j', LTS_STATE_a_69 , LTS_STATE_a_2577 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2578 , 6, 'n', LTS_STATE_a_563 , LTS_STATE_a_101 , 4, 'f', LTS_STATE_a_69 , LTS_STATE_a_2579 , 6, 'a', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'i', LTS_STATE_a_2580 , LTS_STATE_a_101 , 6, 'n', LTS_STATE_a_231 , LTS_STATE_a_2581 , 2, 'i', LTS_STATE_a_2583 , LTS_STATE_a_2582 , 5, 'l', LTS_STATE_a_29 , LTS_STATE_a_101 , 5, 'p', LTS_STATE_a_1626 , LTS_STATE_a_2584 , 5, 'g', LTS_STATE_a_2586 , LTS_STATE_a_2585 , 2, 's', LTS_STATE_a_1675 , LTS_STATE_a_2587 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_2588 , 4, 'v', LTS_STATE_a_69 , LTS_STATE_a_101 , 5, 'h', LTS_STATE_a_2589 , LTS_STATE_a_101 , 4, 'c', LTS_STATE_a_69 , LTS_STATE_a_101 , 5, 'b', LTS_STATE_a_101 , LTS_STATE_a_2590 , 5, 's', LTS_STATE_a_2592 , LTS_STATE_a_2591 , 4, 't', LTS_STATE_a_2593 , LTS_STATE_a_101 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_2594 , 6, 'o', LTS_STATE_a_2074 , LTS_STATE_a_101 , 5, 's', LTS_STATE_a_231 , LTS_STATE_a_101 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_2595 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2596 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_101 , 4, 'p', LTS_STATE_a_563 , LTS_STATE_a_101 , 5, 's', LTS_STATE_a_101 , LTS_STATE_a_2597 , 4, 's', LTS_STATE_a_231 , LTS_STATE_a_101 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'r', LTS_STATE_a_231 , LTS_STATE_a_2598 , 6, 'u', LTS_STATE_a_101 , LTS_STATE_a_2599 , 4, 'f', LTS_STATE_a_29 , LTS_STATE_a_2600 , 3, 'r', LTS_STATE_a_29 , LTS_STATE_a_2601 , 4, 'b', LTS_STATE_a_231 , LTS_STATE_a_2602 , 3, 'n', LTS_STATE_a_101 , LTS_STATE_a_231 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_29 , 4, 'c', LTS_STATE_a_1417 , LTS_STATE_a_2603 , 6, 'p', LTS_STATE_a_101 , LTS_STATE_a_2604 , 4, 'm', LTS_STATE_a_42 , LTS_STATE_a_2605 , 6, 'n', LTS_STATE_a_2606 , LTS_STATE_a_69 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_42 , 6, 'c', LTS_STATE_a_101 , LTS_STATE_a_2607 , 4, 'd', LTS_STATE_a_42 , LTS_STATE_a_2608 , 6, 'n', LTS_STATE_a_101 , LTS_STATE_a_1354 , 2, 'r', LTS_STATE_a_69 , LTS_STATE_a_2609 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2610 , 2, 'h', LTS_STATE_a_69 , LTS_STATE_a_2611 , 2, 'n', LTS_STATE_a_231 , LTS_STATE_a_2612 , 1, 'k', LTS_STATE_a_28 , LTS_STATE_a_2613 , 1, 'd', LTS_STATE_a_29 , LTS_STATE_a_231 , 3, 't', LTS_STATE_a_28 , LTS_STATE_a_2614 , 6, 'o', LTS_STATE_a_2616 , LTS_STATE_a_2615 , 4, 'g', LTS_STATE_a_2618 , LTS_STATE_a_2617 , 3, 'f', LTS_STATE_a_29 , LTS_STATE_a_2619 , 6, 'i', LTS_STATE_a_2621 , LTS_STATE_a_2620 , 2, 'i', LTS_STATE_a_69 , LTS_STATE_a_2622 , 5, 'h', LTS_STATE_a_69 , LTS_STATE_a_2623 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_2624 , 3, 'k', LTS_STATE_a_2625 , LTS_STATE_a_101 , 2, 'g', LTS_STATE_a_101 , LTS_STATE_a_2626 , 5, 'u', LTS_STATE_a_69 , LTS_STATE_a_2627 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_2628 , 6, 'o', LTS_STATE_a_2318 , LTS_STATE_a_69 , 1, 'u', LTS_STATE_a_69 , LTS_STATE_a_2629 , 1, 'm', LTS_STATE_a_101 , LTS_STATE_a_2630 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2631 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_2632 , 5, 'n', LTS_STATE_a_101 , LTS_STATE_a_2633 , 5, 'p', LTS_STATE_a_101 , LTS_STATE_a_69 , 6, 'r', LTS_STATE_a_101 , LTS_STATE_a_2217 , 6, 'i', LTS_STATE_a_2635 , LTS_STATE_a_2634 , 5, 'c', LTS_STATE_a_101 , LTS_STATE_a_2636 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_2637 , 5, 'u', LTS_STATE_a_1892 , LTS_STATE_a_101 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2638 , 2, 'c', LTS_STATE_a_42 , LTS_STATE_a_101 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_69 , 4, 'c', LTS_STATE_a_2639 , LTS_STATE_a_101 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2640 , 5, 'l', LTS_STATE_a_101 , LTS_STATE_a_2641 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_563 , 3, 'b', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'k', LTS_STATE_a_29 , LTS_STATE_a_2642 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2643 , 5, 'z', LTS_STATE_a_231 , LTS_STATE_a_2644 , 5, 'r', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_231 , LTS_STATE_a_2645 , 6, 'i', LTS_STATE_a_1997 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_2646 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2647 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'p', LTS_STATE_a_69 , LTS_STATE_a_2648 , 3, 'v', LTS_STATE_a_101 , LTS_STATE_a_2649 , 4, 'p', LTS_STATE_a_231 , LTS_STATE_a_42 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2650 , 3, 'p', LTS_STATE_a_2652 , LTS_STATE_a_2651 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_1826 , 1, 'e', LTS_STATE_a_42 , LTS_STATE_a_2653 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_2654 , 1, 'e', LTS_STATE_a_69 , LTS_STATE_a_2655 , 5, 's', LTS_STATE_a_29 , LTS_STATE_a_2656 , 3, 't', LTS_STATE_a_28 , LTS_STATE_a_2657 , 1, 'a', LTS_STATE_a_28 , LTS_STATE_a_2658 , 6, 'h', LTS_STATE_a_101 , LTS_STATE_a_2659 , 5, 'n', LTS_STATE_a_231 , LTS_STATE_a_2660 , 3, 'm', LTS_STATE_a_69 , LTS_STATE_a_2661 , 1, 'r', LTS_STATE_a_101 , LTS_STATE_a_42 , 4, 't', LTS_STATE_a_2663 , LTS_STATE_a_2662 , 3, 'l', LTS_STATE_a_29 , LTS_STATE_a_2664 , 3, 'i', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_42 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'v', LTS_STATE_a_563 , LTS_STATE_a_2665 , 2, 'n', LTS_STATE_a_563 , LTS_STATE_a_101 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_101 , 5, 'h', LTS_STATE_a_69 , LTS_STATE_a_2666 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_2667 , 6, 'e', LTS_STATE_a_2669 , LTS_STATE_a_2668 , 6, 'r', LTS_STATE_a_2671 , LTS_STATE_a_2670 , 5, 'f', LTS_STATE_a_2673 , LTS_STATE_a_2672 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'd', LTS_STATE_a_2674 , LTS_STATE_a_101 , 6, 'o', LTS_STATE_a_2676 , LTS_STATE_a_2675 , 3, 'r', LTS_STATE_a_2677 , LTS_STATE_a_101 , 3, 'n', LTS_STATE_a_1424 , LTS_STATE_a_2678 , 5, 't', LTS_STATE_a_2679 , LTS_STATE_a_101 , 3, 'r', LTS_STATE_a_42 , LTS_STATE_a_101 , 3, 'b', LTS_STATE_a_29 , LTS_STATE_a_2680 , 4, 'f', LTS_STATE_a_101 , LTS_STATE_a_2681 , 3, 'c', LTS_STATE_a_2074 , LTS_STATE_a_2682 , 5, 'b', LTS_STATE_a_2684 , LTS_STATE_a_2683 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2685 , 5, 'l', LTS_STATE_a_101 , LTS_STATE_a_2686 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_2687 , 6, 'm', LTS_STATE_a_69 , LTS_STATE_a_2688 , 6, 'y', LTS_STATE_a_2690 , LTS_STATE_a_2689 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2691 , 6, 'b', LTS_STATE_a_101 , LTS_STATE_a_231 , 2, 't', LTS_STATE_a_69 , LTS_STATE_a_2692 , 3, 'n', LTS_STATE_a_2694 , LTS_STATE_a_2693 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_2695 , 2, 'n', LTS_STATE_a_69 , LTS_STATE_a_42 , 1, 'd', LTS_STATE_a_69 , LTS_STATE_a_2696 , 1, 'm', LTS_STATE_a_101 , LTS_STATE_a_2697 , 6, 'o', LTS_STATE_a_29 , LTS_STATE_a_2698 , 1, 'o', LTS_STATE_a_29 , LTS_STATE_a_2699 , 1, 'i', LTS_STATE_a_28 , LTS_STATE_a_2700 , 5, 'k', LTS_STATE_a_2702 , LTS_STATE_a_2701 , 5, 'z', LTS_STATE_a_29 , LTS_STATE_a_2703 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_2704 , 2, 'h', LTS_STATE_a_101 , LTS_STATE_a_2705 , 2, 'm', LTS_STATE_a_69 , LTS_STATE_a_2706 , 3, 'r', LTS_STATE_a_28 , LTS_STATE_a_69 , 2, 't', LTS_STATE_a_101 , LTS_STATE_a_2707 , 6, '#', LTS_STATE_a_69 , LTS_STATE_a_2708 , 6, '#', LTS_STATE_a_101 , LTS_STATE_a_69 , 5, 't', LTS_STATE_a_2710 , LTS_STATE_a_2709 , 5, 't', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 'h', LTS_STATE_a_101 , LTS_STATE_a_2711 , 3, 'x', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 's', LTS_STATE_a_2713 , LTS_STATE_a_2712 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_2714 , 5, 'd', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'a', LTS_STATE_a_2716 , LTS_STATE_a_2715 , 3, 'l', LTS_STATE_a_2718 , LTS_STATE_a_2717 , 4, 'n', LTS_STATE_a_2720 , LTS_STATE_a_2719 , 4, 'n', LTS_STATE_a_29 , LTS_STATE_a_231 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_563 , 6, 't', LTS_STATE_a_29 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2300 , 3, 'z', LTS_STATE_a_231 , LTS_STATE_a_2721 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2722 , 3, 'r', LTS_STATE_a_69 , LTS_STATE_a_101 , 3, 'm', LTS_STATE_a_101 , LTS_STATE_a_2723 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2724 , 6, 'l', LTS_STATE_a_231 , LTS_STATE_a_2725 , 6, 'u', LTS_STATE_a_69 , LTS_STATE_a_2726 , 3, 't', LTS_STATE_a_101 , LTS_STATE_a_2727 , 3, 'm', LTS_STATE_a_29 , LTS_STATE_a_101 , 3, 'c', LTS_STATE_a_231 , LTS_STATE_a_2728 , 3, 'v', LTS_STATE_a_69 , LTS_STATE_a_2729 , 4, 't', LTS_STATE_a_42 , LTS_STATE_a_2730 , 6, 'r', LTS_STATE_a_42 , LTS_STATE_a_69 , 4, 'l', LTS_STATE_a_42 , LTS_STATE_a_231 , 3, 'v', LTS_STATE_a_69 , LTS_STATE_a_2731 , 3, 'c', LTS_STATE_a_69 , LTS_STATE_a_2732 , 3, 'c', LTS_STATE_a_29 , LTS_STATE_a_2733 , 1, 'a', LTS_STATE_a_29 , LTS_STATE_a_2734 , 3, 'r', LTS_STATE_a_29 , LTS_STATE_a_2735 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_2736 , 6, 's', LTS_STATE_a_101 , LTS_STATE_a_2737 , 4, 's', LTS_STATE_a_29 , LTS_STATE_a_1861 , 3, 'n', LTS_STATE_a_563 , LTS_STATE_a_2738 , 6, 'i', LTS_STATE_a_2740 , LTS_STATE_a_2739 , 3, 'n', LTS_STATE_a_69 , LTS_STATE_a_2741 , 5, 'h', LTS_STATE_a_2743 , LTS_STATE_a_2742 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_1723 , 5, 'z', LTS_STATE_a_29 , LTS_STATE_a_2744 , 1, 'n', LTS_STATE_a_69 , LTS_STATE_a_2745 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_2746 , 6, 'u', LTS_STATE_a_563 , LTS_STATE_a_2747 , 4, 'b', LTS_STATE_a_2748 , LTS_STATE_a_101 , 6, 'i', LTS_STATE_a_69 , LTS_STATE_a_2749 , 3, 'v', LTS_STATE_a_69 , LTS_STATE_a_2750 , 5, 'c', LTS_STATE_a_2195 , LTS_STATE_a_2751 , 5, 'k', LTS_STATE_a_101 , LTS_STATE_a_2752 , 5, 'b', LTS_STATE_a_563 , LTS_STATE_a_101 , 2, 'g', LTS_STATE_a_101 , LTS_STATE_a_2753 , 5, 'c', LTS_STATE_a_563 , LTS_STATE_a_101 , 3, 'v', LTS_STATE_a_101 , LTS_STATE_a_2754 , 3, 't', LTS_STATE_a_2755 , LTS_STATE_a_101 , 6, 'o', LTS_STATE_a_69 , LTS_STATE_a_29 , 5, 'm', LTS_STATE_a_101 , LTS_STATE_a_2756 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2757 , 4, 's', LTS_STATE_a_101 , LTS_STATE_a_2758 , 6, 'h', LTS_STATE_a_29 , LTS_STATE_a_2759 , 4, 'k', LTS_STATE_a_69 , LTS_STATE_a_2760 , 4, 'l', LTS_STATE_a_69 , LTS_STATE_a_2761 , 4, 's', LTS_STATE_a_42 , LTS_STATE_a_2762 , 2, 'r', LTS_STATE_a_2764 , LTS_STATE_a_2763 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_2765 , 2, 'e', LTS_STATE_a_231 , LTS_STATE_a_29 , 3, 'i', LTS_STATE_a_28 , LTS_STATE_a_2766 , 2, 't', LTS_STATE_a_28 , LTS_STATE_a_2767 , 4, 'c', LTS_STATE_a_29 , LTS_STATE_a_2768 , 2, 'e', LTS_STATE_a_101 , LTS_STATE_a_2769 , 2, 'o', LTS_STATE_a_2217 , LTS_STATE_a_2770 , 4, 'c', LTS_STATE_a_2772 , LTS_STATE_a_2771 , 3, 'h', LTS_STATE_a_29 , LTS_STATE_a_69 , 2, 'o', LTS_STATE_a_101 , LTS_STATE_a_2773 , 2, 'l', LTS_STATE_a_2775 , LTS_STATE_a_2774 , 4, 't', LTS_STATE_a_1288 , LTS_STATE_a_69 , 5, 'j', LTS_STATE_a_29 , LTS_STATE_a_2296 , 1, 'o', LTS_STATE_a_231 , LTS_STATE_a_2776 , 1, 's', LTS_STATE_a_101 , LTS_STATE_a_2777 , 5, 'd', LTS_STATE_a_2779 , LTS_STATE_a_2778 , 6, 't', LTS_STATE_a_69 , LTS_STATE_a_1205 , 6, 'l', LTS_STATE_a_69 , LTS_STATE_a_101 , 5, 'u', LTS_STATE_a_2780 , LTS_STATE_a_101 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2781 , 5, 'n', LTS_STATE_a_231 , LTS_STATE_a_2782 , 5, 'h', LTS_STATE_a_42 , LTS_STATE_a_101 , 5, 'c', LTS_STATE_a_2783 , LTS_STATE_a_101 , 5, 'p', LTS_STATE_a_101 , LTS_STATE_a_563 , 3, 'z', LTS_STATE_a_231 , LTS_STATE_a_2784 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2785 , 6, 'w', LTS_STATE_a_69 , LTS_STATE_a_2786 , 4, 'v', LTS_STATE_a_29 , LTS_STATE_a_2787 , 2, '#', LTS_STATE_a_2789 , LTS_STATE_a_2788 , 4, 'c', LTS_STATE_a_42 , LTS_STATE_a_2790 , 4, 'v', LTS_STATE_a_42 , LTS_STATE_a_2791 , 2, 'u', LTS_STATE_a_563 , LTS_STATE_a_2792 , 1, 'e', LTS_STATE_a_101 , LTS_STATE_a_1426 , 3, 't', LTS_STATE_a_69 , LTS_STATE_a_2793 , 1, 'm', LTS_STATE_a_28 , LTS_STATE_a_2794 , 2, 'i', LTS_STATE_a_28 , LTS_STATE_a_2795 , 1, 'i', LTS_STATE_a_101 , LTS_STATE_a_2796 , 2, 'u', LTS_STATE_a_29 , LTS_STATE_a_2797 , 3, 'h', LTS_STATE_a_2799 , LTS_STATE_a_2798 , 6, 'e', LTS_STATE_a_101 , LTS_STATE_a_69 , 2, 'e', LTS_STATE_a_29 , LTS_STATE_a_2800 , 2, 'e', LTS_STATE_a_101 , LTS_STATE_a_69 , 5, 'k', LTS_STATE_a_2802 , LTS_STATE_a_2801 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_2803 , 2, 'r', LTS_STATE_a_101 , LTS_STATE_a_2804 , 6, 'o', LTS_STATE_a_101 , LTS_STATE_a_2805 , 6, 'a', LTS_STATE_a_2807 , LTS_STATE_a_2806 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_2808 , 2, 's', LTS_STATE_a_2602 , LTS_STATE_a_101 , 4, 'm', LTS_STATE_a_101 , LTS_STATE_a_2809 , 2, 'f', LTS_STATE_a_101 , LTS_STATE_a_2810 , 3, 'f', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'p', LTS_STATE_a_2812 , LTS_STATE_a_2811 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2813 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_2814 , 6, 'k', LTS_STATE_a_29 , LTS_STATE_a_2815 , 4, 'v', LTS_STATE_a_231 , LTS_STATE_a_2816 , 6, 'r', LTS_STATE_a_69 , LTS_STATE_a_2817 , 4, 'v', LTS_STATE_a_69 , LTS_STATE_a_231 , 3, 'd', LTS_STATE_a_42 , LTS_STATE_a_2818 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_2819 , 2, 'a', LTS_STATE_a_69 , LTS_STATE_a_2820 , 2, 'o', LTS_STATE_a_29 , LTS_STATE_a_2821 , 3, 'b', LTS_STATE_a_28 , LTS_STATE_a_2822 , 5, 'p', LTS_STATE_a_101 , LTS_STATE_a_2823 , 4, 's', LTS_STATE_a_29 , LTS_STATE_a_2824 , 4, 's', LTS_STATE_a_2825 , LTS_STATE_a_101 , 5, 'm', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 't', LTS_STATE_a_29 , LTS_STATE_a_69 , 1, 'o', LTS_STATE_a_101 , LTS_STATE_a_2826 , 1, 'o', LTS_STATE_a_69 , LTS_STATE_a_2827 , 5, 's', LTS_STATE_a_563 , LTS_STATE_a_69 , 2, 'n', LTS_STATE_a_101 , LTS_STATE_a_2828 , 1, 'l', LTS_STATE_a_101 , LTS_STATE_a_2829 , 5, 'k', LTS_STATE_a_563 , LTS_STATE_a_2830 , 5, 'v', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'i', LTS_STATE_a_69 , LTS_STATE_a_101 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_2831 , 5, 'h', LTS_STATE_a_29 , LTS_STATE_a_101 , 5, 't', LTS_STATE_a_2833 , LTS_STATE_a_2832 , 5, 's', LTS_STATE_a_231 , LTS_STATE_a_2539 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 's', LTS_STATE_a_101 , LTS_STATE_a_2749 , 4, 'z', LTS_STATE_a_69 , LTS_STATE_a_2834 , 4, 'b', LTS_STATE_a_69 , LTS_STATE_a_2835 , 4, 'n', LTS_STATE_a_69 , LTS_STATE_a_1800 , 6, 'a', LTS_STATE_a_42 , LTS_STATE_a_2836 , 3, 'b', LTS_STATE_a_101 , LTS_STATE_a_2837 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_2838 , 2, 'a', LTS_STATE_a_29 , LTS_STATE_a_2839 , 3, 'n', LTS_STATE_a_28 , LTS_STATE_a_2840 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_2841 , 1, 'a', LTS_STATE_a_101 , LTS_STATE_a_2842 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_2626 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_2843 , 3, 's', LTS_STATE_a_69 , LTS_STATE_a_2844 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_2845 , 3, 'm', LTS_STATE_a_2771 , LTS_STATE_a_101 , 6, 'i', LTS_STATE_a_563 , LTS_STATE_a_2846 , 2, 'f', LTS_STATE_a_101 , LTS_STATE_a_2847 , 3, 'k', LTS_STATE_a_101 , LTS_STATE_a_2848 , 4, 't', LTS_STATE_a_231 , LTS_STATE_a_101 , 3, 'l', LTS_STATE_a_69 , LTS_STATE_a_2849 , 4, 'g', LTS_STATE_a_69 , LTS_STATE_a_101 , 6, 'r', LTS_STATE_a_2851 , LTS_STATE_a_2850 , 3, 'p', LTS_STATE_a_101 , LTS_STATE_a_2852 , 2, 'o', LTS_STATE_a_2853 , LTS_STATE_a_69 , 2, 'i', LTS_STATE_a_29 , LTS_STATE_a_28 , 2, 's', LTS_STATE_a_28 , LTS_STATE_a_2854 , 1, 'm', LTS_STATE_a_101 , LTS_STATE_a_2855 , 2, 'c', LTS_STATE_a_101 , LTS_STATE_a_29 , 3, 'c', LTS_STATE_a_101 , LTS_STATE_a_2856 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_1854 , 2, 's', LTS_STATE_a_101 , LTS_STATE_a_2857 , 5, 'v', LTS_STATE_a_101 , LTS_STATE_a_2858 , 5, 'u', LTS_STATE_a_101 , LTS_STATE_a_2859 , 5, 'g', LTS_STATE_a_101 , LTS_STATE_a_2860 , 4, 'h', LTS_STATE_a_69 , LTS_STATE_a_2861 , 4, 'n', LTS_STATE_a_101 , LTS_STATE_a_1553 , 4, 'm', LTS_STATE_a_42 , LTS_STATE_a_2862 , 2, 'g', LTS_STATE_a_101 , LTS_STATE_a_2863 , 1, 'd', LTS_STATE_a_29 , LTS_STATE_a_69 , 3, 'g', LTS_STATE_a_28 , LTS_STATE_a_2864 , 5, 'm', LTS_STATE_a_2866 , LTS_STATE_a_2865 , 2, 'g', LTS_STATE_a_69 , LTS_STATE_a_2867 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_2868 , 5, 'n', LTS_STATE_a_101 , LTS_STATE_a_2869 , 3, 'l', LTS_STATE_a_101 , LTS_STATE_a_1228 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_2870 , 6, 'm', LTS_STATE_a_231 , LTS_STATE_a_101 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_2871 , 2, 'e', LTS_STATE_a_2184 , LTS_STATE_a_2872 , 2, 'c', LTS_STATE_a_28 , LTS_STATE_a_241 , 5, 'b', LTS_STATE_a_101 , LTS_STATE_a_2873 , 6, 'a', LTS_STATE_a_101 , LTS_STATE_a_563 , 4, 'm', LTS_STATE_a_69 , LTS_STATE_a_2874 , 2, 'a', LTS_STATE_a_101 , LTS_STATE_a_2875 , 4, 'b', LTS_STATE_a_101 , LTS_STATE_a_2876 , 5, 'c', LTS_STATE_a_2877 , LTS_STATE_a_101 , 3, 'g', LTS_STATE_a_101 , LTS_STATE_a_42 , 4, 'p', LTS_STATE_a_101 , LTS_STATE_a_2878 , 2, 'l', LTS_STATE_a_2880 , LTS_STATE_a_2879 , 3, 'r', LTS_STATE_a_101 , LTS_STATE_a_2881 , 6, 'i', LTS_STATE_a_101 , LTS_STATE_a_29 , 5, 'm', LTS_STATE_a_563 , LTS_STATE_a_69 , 4, 'c', LTS_STATE_a_101 , LTS_STATE_a_231 , 3, 'i', LTS_STATE_a_101 , LTS_STATE_a_2882 , 5, 's', LTS_STATE_a_2884 , LTS_STATE_a_2883 , 1, 'a', LTS_STATE_a_231 , LTS_STATE_a_69 , 5, 's', LTS_STATE_a_101 , LTS_STATE_a_69 , 1, 'c', LTS_STATE_a_69 , LTS_STATE_a_2885 , 3, 'p', LTS_STATE_a_231 , LTS_STATE_a_2886 , 1, 'a', LTS_STATE_a_69 , LTS_STATE_a_2887 , 3, 'r', LTS_STATE_a_2184 , LTS_STATE_a_2888 , 4, 'g', LTS_STATE_a_101 , LTS_STATE_a_2889 , 4, 's', LTS_STATE_a_2890 , LTS_STATE_a_29 , 4, 'd', LTS_STATE_a_563 , LTS_STATE_a_2891 , 4, 'd', LTS_STATE_a_101 , LTS_STATE_a_2892 , 2, 'o', LTS_STATE_a_29 , LTS_STATE_a_101 , 4, 't', LTS_STATE_a_101 , LTS_STATE_a_2893 , 5, 'c', LTS_STATE_a_101 , LTS_STATE_a_69 , 3, 'm', LTS_STATE_a_563 , LTS_STATE_a_2894 , 2, 's', LTS_STATE_a_563 , LTS_STATE_a_101 , /** letter b **/ 4, 'b', LTS_STATE_b_2 , LTS_STATE_b_1 , 3, 'm', LTS_STATE_b_4 , LTS_STATE_b_3 , 1, 'c', LTS_STATE_b_6 , LTS_STATE_b_5 , 4, 't', LTS_STATE_b_8 , LTS_STATE_b_7 , 4, '#', LTS_STATE_b_5 , LTS_STATE_b_9 , 255, 0, 0,0 , 0,0 , 2, 'r', LTS_STATE_b_11 , LTS_STATE_b_5 , 255, 20, 0,0 , 0,0 , 1, 'd', LTS_STATE_b_5 , LTS_STATE_b_12 , 4, 's', LTS_STATE_b_5 , LTS_STATE_b_13 , 3, 'a', LTS_STATE_b_5 , LTS_STATE_b_7 , 2, 'd', LTS_STATE_b_5 , LTS_STATE_b_7 , 2, 'o', LTS_STATE_b_15 , LTS_STATE_b_14 , 1, 'l', LTS_STATE_b_17 , LTS_STATE_b_16 , 4, 'a', LTS_STATE_b_7 , LTS_STATE_b_18 , 2, 'u', LTS_STATE_b_19 , LTS_STATE_b_7 , 2, 'i', LTS_STATE_b_20 , LTS_STATE_b_7 , 1, 'b', LTS_STATE_b_5 , LTS_STATE_b_21 , 1, 'd', LTS_STATE_b_5 , LTS_STATE_b_7 , 4, 'e', LTS_STATE_b_5 , LTS_STATE_b_7 , 1, 'c', LTS_STATE_b_20 , LTS_STATE_b_7 , /** letter c **/ 4, 'k', LTS_STATE_c_2 , LTS_STATE_c_1 , 4, 'h', LTS_STATE_c_4 , LTS_STATE_c_3 , 5, 'i', LTS_STATE_c_6 , LTS_STATE_c_5 , 4, 'e', LTS_STATE_c_8 , LTS_STATE_c_7 , 3, 's', LTS_STATE_c_10 , LTS_STATE_c_9 , 255, 0, 0,0 , 0,0 , 6, '#', LTS_STATE_c_12 , LTS_STATE_c_5 , 4, 'i', LTS_STATE_c_14 , LTS_STATE_c_13 , 3, 's', LTS_STATE_c_5 , LTS_STATE_c_15 , 3, 't', LTS_STATE_c_17 , LTS_STATE_c_16 , 2, 't', LTS_STATE_c_17 , LTS_STATE_c_18 , 1, '#', LTS_STATE_c_5 , LTS_STATE_c_19 , 4, 'c', LTS_STATE_c_21 , LTS_STATE_c_20 , 3, 's', LTS_STATE_c_23 , LTS_STATE_c_22 , 3, 'm', LTS_STATE_c_25 , LTS_STATE_c_24 , 2, '0', LTS_STATE_c_27 , LTS_STATE_c_26 , 255, 21, 0,0 , 0,0 , 5, 'o', LTS_STATE_c_29 , LTS_STATE_c_28 , 1, 'o', LTS_STATE_c_31 , LTS_STATE_c_30 , 4, 'y', LTS_STATE_c_33 , LTS_STATE_c_32 , 5, 'e', LTS_STATE_c_35 , LTS_STATE_c_34 , 5, 'a', LTS_STATE_c_37 , LTS_STATE_c_36 , 5, 'a', LTS_STATE_c_39 , LTS_STATE_c_38 , 3, 'x', LTS_STATE_c_5 , LTS_STATE_c_40 , 255, 22, 0,0 , 0,0 , 3, 'n', LTS_STATE_c_42 , LTS_STATE_c_41 , 5, 'r', LTS_STATE_c_25 , LTS_STATE_c_43 , 5, 'i', LTS_STATE_c_45 , LTS_STATE_c_44 , 6, 'o', LTS_STATE_c_25 , LTS_STATE_c_5 , 1, 'a', LTS_STATE_c_47 , LTS_STATE_c_46 , 255, 23, 0,0 , 0,0 , 4, 'z', LTS_STATE_c_49 , LTS_STATE_c_48 , 5, 'r', LTS_STATE_c_25 , LTS_STATE_c_50 , 5, 'i', LTS_STATE_c_51 , LTS_STATE_c_5 , 3, 'a', LTS_STATE_c_25 , LTS_STATE_c_52 , 3, 'c', LTS_STATE_c_54 , LTS_STATE_c_53 , 6, 'l', LTS_STATE_c_56 , LTS_STATE_c_55 , 1, 'p', LTS_STATE_c_17 , LTS_STATE_c_5 , 1, '0', LTS_STATE_c_5 , LTS_STATE_c_17 , 5, 'k', LTS_STATE_c_58 , LTS_STATE_c_57 , 2, 'v', LTS_STATE_c_17 , LTS_STATE_c_59 , 5, 'o', LTS_STATE_c_61 , LTS_STATE_c_60 , 5, 'l', LTS_STATE_c_25 , LTS_STATE_c_62 , 6, 'd', LTS_STATE_c_64 , LTS_STATE_c_63 , 1, '0', LTS_STATE_c_5 , LTS_STATE_c_25 , 3, 'i', LTS_STATE_c_31 , LTS_STATE_c_65 , 2, 'l', LTS_STATE_c_5 , LTS_STATE_c_31 , 4, 'g', LTS_STATE_c_5 , LTS_STATE_c_66 , 2, 's', LTS_STATE_c_5 , LTS_STATE_c_17 , 255, 24, 0,0 , 0,0 , 6, '#', LTS_STATE_c_5 , LTS_STATE_c_67 , 2, 's', LTS_STATE_c_25 , LTS_STATE_c_5 , 6, 'u', LTS_STATE_c_69 , LTS_STATE_c_68 , 5, '#', LTS_STATE_c_17 , LTS_STATE_c_70 , 3, 'i', LTS_STATE_c_56 , LTS_STATE_c_71 , 255, 25, 0,0 , 0,0 , 6, 'n', LTS_STATE_c_73 , LTS_STATE_c_72 , 3, 'i', LTS_STATE_c_17 , LTS_STATE_c_74 , 2, 'e', LTS_STATE_c_76 , LTS_STATE_c_75 , 6, 'l', LTS_STATE_c_78 , LTS_STATE_c_77 , 6, 'r', LTS_STATE_c_25 , LTS_STATE_c_79 , 5, 'a', LTS_STATE_c_81 , LTS_STATE_c_80 , 1, '0', LTS_STATE_c_83 , LTS_STATE_c_82 , 5, 'a', LTS_STATE_c_5 , LTS_STATE_c_25 , 1, 'r', LTS_STATE_c_31 , LTS_STATE_c_84 , 4, 'q', LTS_STATE_c_5 , LTS_STATE_c_85 , 6, 'd', LTS_STATE_c_25 , LTS_STATE_c_86 , 3, 'x', LTS_STATE_c_5 , LTS_STATE_c_87 , 5, 'o', LTS_STATE_c_56 , LTS_STATE_c_50 , 5, 'o', LTS_STATE_c_17 , LTS_STATE_c_88 , 6, 't', LTS_STATE_c_90 , LTS_STATE_c_89 , 2, '0', LTS_STATE_c_92 , LTS_STATE_c_91 , 5, 'a', LTS_STATE_c_56 , LTS_STATE_c_50 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_93 , 5, 'e', LTS_STATE_c_95 , LTS_STATE_c_94 , 3, 'i', LTS_STATE_c_25 , LTS_STATE_c_96 , 5, 'e', LTS_STATE_c_17 , LTS_STATE_c_97 , 2, 'i', LTS_STATE_c_17 , LTS_STATE_c_56 , 6, '#', LTS_STATE_c_17 , LTS_STATE_c_25 , 6, 'v', LTS_STATE_c_17 , LTS_STATE_c_98 , 6, 'r', LTS_STATE_c_17 , LTS_STATE_c_99 , 5, 'a', LTS_STATE_c_100 , LTS_STATE_c_5 , 6, 'm', LTS_STATE_c_101 , LTS_STATE_c_5 , 2, 'r', LTS_STATE_c_31 , LTS_STATE_c_102 , 3, 'k', LTS_STATE_c_5 , LTS_STATE_c_103 , 6, 'a', LTS_STATE_c_5 , LTS_STATE_c_104 , 6, 'n', LTS_STATE_c_106 , LTS_STATE_c_105 , 1, '#', LTS_STATE_c_50 , LTS_STATE_c_107 , 3, 'c', LTS_STATE_c_17 , LTS_STATE_c_108 , 1, 'p', LTS_STATE_c_56 , LTS_STATE_c_50 , 5, 'o', LTS_STATE_c_56 , LTS_STATE_c_109 , 5, 'n', LTS_STATE_c_50 , LTS_STATE_c_110 , 1, 'o', LTS_STATE_c_17 , LTS_STATE_c_111 , 3, 'e', LTS_STATE_c_113 , LTS_STATE_c_112 , 6, 'r', LTS_STATE_c_115 , LTS_STATE_c_114 , 3, 'c', LTS_STATE_c_25 , LTS_STATE_c_116 , 1, 's', LTS_STATE_c_25 , LTS_STATE_c_117 , 6, 'r', LTS_STATE_c_119 , LTS_STATE_c_118 , 6, 'u', LTS_STATE_c_56 , LTS_STATE_c_17 , 6, 'r', LTS_STATE_c_120 , LTS_STATE_c_5 , 5, 'e', LTS_STATE_c_25 , LTS_STATE_c_5 , 3, 'a', LTS_STATE_c_31 , LTS_STATE_c_121 , 3, 'n', LTS_STATE_c_123 , LTS_STATE_c_122 , 3, 'a', LTS_STATE_c_124 , LTS_STATE_c_5 , 3, 'm', LTS_STATE_c_25 , LTS_STATE_c_125 , 2, 'f', LTS_STATE_c_56 , LTS_STATE_c_126 , 1, 'v', LTS_STATE_c_50 , LTS_STATE_c_17 , 1, '0', LTS_STATE_c_17 , LTS_STATE_c_127 , 6, 'c', LTS_STATE_c_129 , LTS_STATE_c_128 , 6, 's', LTS_STATE_c_50 , LTS_STATE_c_130 , 1, 'a', LTS_STATE_c_17 , LTS_STATE_c_131 , 2, 'b', LTS_STATE_c_133 , LTS_STATE_c_132 , 2, 'i', LTS_STATE_c_135 , LTS_STATE_c_134 , 6, 'n', LTS_STATE_c_137 , LTS_STATE_c_136 , 3, 'a', LTS_STATE_c_25 , LTS_STATE_c_138 , 3, 'u', LTS_STATE_c_25 , LTS_STATE_c_139 , 5, '#', LTS_STATE_c_17 , LTS_STATE_c_140 , 6, 'a', LTS_STATE_c_142 , LTS_STATE_c_141 , 5, 'o', LTS_STATE_c_25 , LTS_STATE_c_17 , 1, 'd', LTS_STATE_c_17 , LTS_STATE_c_25 , 3, 'o', LTS_STATE_c_31 , LTS_STATE_c_5 , 2, 'u', LTS_STATE_c_144 , LTS_STATE_c_143 , 1, 'r', LTS_STATE_c_145 , LTS_STATE_c_25 , 1, '#', LTS_STATE_c_25 , LTS_STATE_c_5 , 5, 'e', LTS_STATE_c_147 , LTS_STATE_c_146 , 5, 'n', LTS_STATE_c_50 , LTS_STATE_c_148 , 3, 'n', LTS_STATE_c_17 , LTS_STATE_c_149 , 3, 'n', LTS_STATE_c_151 , LTS_STATE_c_150 , 2, 'a', LTS_STATE_c_17 , LTS_STATE_c_50 , 5, 'm', LTS_STATE_c_50 , LTS_STATE_c_152 , 3, 'a', LTS_STATE_c_50 , LTS_STATE_c_17 , 3, 'c', LTS_STATE_c_25 , LTS_STATE_c_153 , 5, '#', LTS_STATE_c_25 , LTS_STATE_c_154 , 5, 'a', LTS_STATE_c_156 , LTS_STATE_c_155 , 5, '#', LTS_STATE_c_17 , LTS_STATE_c_25 , 6, 'l', LTS_STATE_c_158 , LTS_STATE_c_157 , 3, 'r', LTS_STATE_c_17 , LTS_STATE_c_25 , 1, 'r', LTS_STATE_c_17 , LTS_STATE_c_159 , 3, 'r', LTS_STATE_c_160 , LTS_STATE_c_17 , 6, 's', LTS_STATE_c_17 , LTS_STATE_c_161 , 6, 'm', LTS_STATE_c_162 , LTS_STATE_c_17 , 5, 'i', LTS_STATE_c_25 , LTS_STATE_c_17 , 4, '#', LTS_STATE_c_25 , LTS_STATE_c_163 , 4, 'l', LTS_STATE_c_5 , LTS_STATE_c_25 , 5, 'i', LTS_STATE_c_50 , LTS_STATE_c_25 , 5, '#', LTS_STATE_c_165 , LTS_STATE_c_164 , 6, '#', LTS_STATE_c_25 , LTS_STATE_c_166 , 3, 'n', LTS_STATE_c_17 , LTS_STATE_c_50 , 6, 'n', LTS_STATE_c_56 , LTS_STATE_c_167 , 5, 'l', LTS_STATE_c_169 , LTS_STATE_c_168 , 5, 'n', LTS_STATE_c_170 , LTS_STATE_c_50 , 6, 'u', LTS_STATE_c_17 , LTS_STATE_c_171 , 2, 'o', LTS_STATE_c_173 , LTS_STATE_c_172 , 1, '#', LTS_STATE_c_174 , LTS_STATE_c_17 , 5, 'i', LTS_STATE_c_176 , LTS_STATE_c_175 , 2, 'm', LTS_STATE_c_25 , LTS_STATE_c_17 , 6, 't', LTS_STATE_c_178 , LTS_STATE_c_177 , 2, 'r', LTS_STATE_c_56 , LTS_STATE_c_179 , 3, 'e', LTS_STATE_c_25 , LTS_STATE_c_180 , 5, 'a', LTS_STATE_c_17 , LTS_STATE_c_181 , 1, 'r', LTS_STATE_c_17 , LTS_STATE_c_182 , 5, 'e', LTS_STATE_c_25 , LTS_STATE_c_17 , 1, 'n', LTS_STATE_c_183 , LTS_STATE_c_25 , 6, 'g', LTS_STATE_c_50 , LTS_STATE_c_184 , 3, 'i', LTS_STATE_c_17 , LTS_STATE_c_185 , 3, 'n', LTS_STATE_c_50 , LTS_STATE_c_186 , 3, 'r', LTS_STATE_c_50 , LTS_STATE_c_187 , 1, 'a', LTS_STATE_c_189 , LTS_STATE_c_188 , 6, 'e', LTS_STATE_c_50 , LTS_STATE_c_190 , 1, 'v', LTS_STATE_c_17 , LTS_STATE_c_50 , 5, 'p', LTS_STATE_c_50 , LTS_STATE_c_191 , 2, 'u', LTS_STATE_c_193 , LTS_STATE_c_192 , 3, 'r', LTS_STATE_c_194 , LTS_STATE_c_17 , 6, 'e', LTS_STATE_c_25 , LTS_STATE_c_195 , 1, 'c', LTS_STATE_c_196 , LTS_STATE_c_25 , 6, 'n', LTS_STATE_c_17 , LTS_STATE_c_25 , 6, 'm', LTS_STATE_c_198 , LTS_STATE_c_197 , 2, 'a', LTS_STATE_c_25 , LTS_STATE_c_199 , 3, 'a', LTS_STATE_c_17 , LTS_STATE_c_25 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_200 , 1, 'k', LTS_STATE_c_17 , LTS_STATE_c_201 , 6, 'n', LTS_STATE_c_17 , LTS_STATE_c_202 , 4, 't', LTS_STATE_c_203 , LTS_STATE_c_25 , 5, 'n', LTS_STATE_c_205 , LTS_STATE_c_204 , 3, 'a', LTS_STATE_c_17 , LTS_STATE_c_50 , 3, 'r', LTS_STATE_c_25 , LTS_STATE_c_206 , 3, 'a', LTS_STATE_c_17 , LTS_STATE_c_56 , 5, 's', LTS_STATE_c_208 , LTS_STATE_c_207 , 3, 'i', LTS_STATE_c_50 , LTS_STATE_c_185 , 3, 'a', LTS_STATE_c_50 , LTS_STATE_c_209 , 6, 't', LTS_STATE_c_50 , LTS_STATE_c_210 , 5, 'i', LTS_STATE_c_212 , LTS_STATE_c_211 , 5, 'a', LTS_STATE_c_213 , LTS_STATE_c_17 , 5, 'a', LTS_STATE_c_17 , LTS_STATE_c_142 , 6, 'n', LTS_STATE_c_25 , LTS_STATE_c_214 , 2, 'h', LTS_STATE_c_17 , LTS_STATE_c_25 , 2, 's', LTS_STATE_c_25 , LTS_STATE_c_215 , 3, 'o', LTS_STATE_c_25 , LTS_STATE_c_216 , 1, '#', LTS_STATE_c_56 , LTS_STATE_c_217 , 3, 'r', LTS_STATE_c_219 , LTS_STATE_c_218 , 5, 'e', LTS_STATE_c_17 , LTS_STATE_c_25 , 2, 'i', LTS_STATE_c_17 , LTS_STATE_c_220 , 3, 'i', LTS_STATE_c_221 , LTS_STATE_c_25 , 3, 'i', LTS_STATE_c_50 , LTS_STATE_c_222 , 2, 'm', LTS_STATE_c_25 , LTS_STATE_c_223 , 2, '0', LTS_STATE_c_17 , LTS_STATE_c_224 , 6, '#', LTS_STATE_c_50 , LTS_STATE_c_225 , 6, 't', LTS_STATE_c_5 , LTS_STATE_c_50 , 6, 'y', LTS_STATE_c_50 , LTS_STATE_c_226 , 5, 'r', LTS_STATE_c_227 , LTS_STATE_c_50 , 5, 'a', LTS_STATE_c_229 , LTS_STATE_c_228 , 3, 'a', LTS_STATE_c_231 , LTS_STATE_c_230 , 1, 'p', LTS_STATE_c_17 , LTS_STATE_c_56 , 6, 'a', LTS_STATE_c_25 , LTS_STATE_c_232 , 6, 'd', LTS_STATE_c_17 , LTS_STATE_c_233 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_25 , 3, 'o', LTS_STATE_c_56 , LTS_STATE_c_17 , 2, 'o', LTS_STATE_c_17 , LTS_STATE_c_25 , 2, 'a', LTS_STATE_c_17 , LTS_STATE_c_25 , 5, 'a', LTS_STATE_c_234 , LTS_STATE_c_17 , 2, 'd', LTS_STATE_c_5 , LTS_STATE_c_25 , 5, 'c', LTS_STATE_c_236 , LTS_STATE_c_235 , 6, 's', LTS_STATE_c_17 , LTS_STATE_c_237 , 6, 's', LTS_STATE_c_50 , LTS_STATE_c_238 , 6, 'o', LTS_STATE_c_50 , LTS_STATE_c_239 , 1, 'm', LTS_STATE_c_241 , LTS_STATE_c_240 , 6, 'e', LTS_STATE_c_50 , LTS_STATE_c_242 , 6, 'w', LTS_STATE_c_244 , LTS_STATE_c_243 , 6, 'e', LTS_STATE_c_25 , LTS_STATE_c_245 , 3, 'r', LTS_STATE_c_25 , LTS_STATE_c_246 , 6, 'e', LTS_STATE_c_17 , LTS_STATE_c_247 , 3, 'u', LTS_STATE_c_25 , LTS_STATE_c_17 , 6, 'v', LTS_STATE_c_17 , LTS_STATE_c_248 , 6, 'r', LTS_STATE_c_17 , LTS_STATE_c_25 , 5, 'o', LTS_STATE_c_250 , LTS_STATE_c_249 , 1, '0', LTS_STATE_c_50 , LTS_STATE_c_17 , 1, 'm', LTS_STATE_c_17 , LTS_STATE_c_251 , 3, 'a', LTS_STATE_c_56 , LTS_STATE_c_50 , 3, 'i', LTS_STATE_c_50 , LTS_STATE_c_252 , 2, 'a', LTS_STATE_c_50 , LTS_STATE_c_253 , 6, 'l', LTS_STATE_c_50 , LTS_STATE_c_17 , 6, 'a', LTS_STATE_c_50 , LTS_STATE_c_254 , 3, 'o', LTS_STATE_c_256 , LTS_STATE_c_255 , 3, 'a', LTS_STATE_c_5 , LTS_STATE_c_17 , 1, '0', LTS_STATE_c_25 , LTS_STATE_c_257 , 2, 's', LTS_STATE_c_25 , LTS_STATE_c_258 , 2, 'm', LTS_STATE_c_56 , LTS_STATE_c_259 , 1, 'l', LTS_STATE_c_17 , LTS_STATE_c_260 , 5, 'u', LTS_STATE_c_50 , LTS_STATE_c_261 , 3, 'o', LTS_STATE_c_50 , LTS_STATE_c_262 , 6, 'o', LTS_STATE_c_17 , LTS_STATE_c_263 , 2, 'e', LTS_STATE_c_50 , LTS_STATE_c_264 , 6, 'l', LTS_STATE_c_265 , LTS_STATE_c_50 , 6, 'v', LTS_STATE_c_50 , LTS_STATE_c_17 , 2, 'r', LTS_STATE_c_267 , LTS_STATE_c_266 , 5, 'u', LTS_STATE_c_17 , LTS_STATE_c_25 , 3, 'r', LTS_STATE_c_269 , LTS_STATE_c_268 , 2, 'a', LTS_STATE_c_17 , LTS_STATE_c_270 , 1, 's', LTS_STATE_c_56 , LTS_STATE_c_79 , 6, 'c', LTS_STATE_c_17 , LTS_STATE_c_271 , 5, 'k', LTS_STATE_c_17 , LTS_STATE_c_272 , 6, '#', LTS_STATE_c_273 , LTS_STATE_c_17 , 3, 'l', LTS_STATE_c_17 , LTS_STATE_c_274 , 2, 'd', LTS_STATE_c_50 , LTS_STATE_c_275 , 3, 'i', LTS_STATE_c_50 , LTS_STATE_c_276 , 2, 'l', LTS_STATE_c_278 , LTS_STATE_c_277 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_279 , 6, 'u', LTS_STATE_c_56 , LTS_STATE_c_280 , 1, '#', LTS_STATE_c_56 , LTS_STATE_c_25 , 2, 'm', LTS_STATE_c_17 , LTS_STATE_c_281 , 3, 'u', LTS_STATE_c_283 , LTS_STATE_c_282 , 5, 'm', LTS_STATE_c_285 , LTS_STATE_c_284 , 3, 'a', LTS_STATE_c_50 , LTS_STATE_c_286 , 6, 'a', LTS_STATE_c_287 , LTS_STATE_c_50 , 5, 'r', LTS_STATE_c_289 , LTS_STATE_c_288 , 1, 'p', LTS_STATE_c_50 , LTS_STATE_c_17 , 2, 'y', LTS_STATE_c_5 , LTS_STATE_c_290 , 5, '#', LTS_STATE_c_25 , LTS_STATE_c_291 , 3, 'a', LTS_STATE_c_135 , LTS_STATE_c_25 , 3, 'u', LTS_STATE_c_293 , LTS_STATE_c_292 , 3, 'o', LTS_STATE_c_294 , LTS_STATE_c_17 , 2, 'o', LTS_STATE_c_296 , LTS_STATE_c_295 , 6, '#', LTS_STATE_c_56 , LTS_STATE_c_17 , 3, 'e', LTS_STATE_c_50 , LTS_STATE_c_297 , 1, '0', LTS_STATE_c_17 , LTS_STATE_c_50 , 1, 'c', LTS_STATE_c_17 , LTS_STATE_c_50 , 1, 'l', LTS_STATE_c_50 , LTS_STATE_c_17 , 3, 'e', LTS_STATE_c_50 , LTS_STATE_c_298 , 2, 'r', LTS_STATE_c_50 , LTS_STATE_c_299 , 5, '#', LTS_STATE_c_301 , LTS_STATE_c_300 , 5, 'l', LTS_STATE_c_25 , LTS_STATE_c_302 , 3, 'a', LTS_STATE_c_304 , LTS_STATE_c_303 , 6, 'r', LTS_STATE_c_25 , LTS_STATE_c_17 , 2, 'r', LTS_STATE_c_25 , LTS_STATE_c_17 , 1, 'c', LTS_STATE_c_25 , LTS_STATE_c_305 , 1, '#', LTS_STATE_c_25 , LTS_STATE_c_17 , 1, '#', LTS_STATE_c_306 , LTS_STATE_c_50 , 2, 'l', LTS_STATE_c_50 , LTS_STATE_c_307 , 1, '#', LTS_STATE_c_131 , LTS_STATE_c_50 , 3, 'y', LTS_STATE_c_25 , LTS_STATE_c_308 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_309 , 6, 'e', LTS_STATE_c_25 , LTS_STATE_c_310 , 3, 'i', LTS_STATE_c_17 , LTS_STATE_c_311 , 1, '#', LTS_STATE_c_293 , LTS_STATE_c_17 , 2, 'r', LTS_STATE_c_313 , LTS_STATE_c_312 , 6, 'a', LTS_STATE_c_17 , LTS_STATE_c_50 , 1, 's', LTS_STATE_c_50 , LTS_STATE_c_314 , 6, 'l', LTS_STATE_c_25 , LTS_STATE_c_315 , 1, 't', LTS_STATE_c_17 , LTS_STATE_c_316 , 5, 't', LTS_STATE_c_17 , LTS_STATE_c_25 , 3, 'o', LTS_STATE_c_25 , LTS_STATE_c_17 , 1, 'a', LTS_STATE_c_17 , LTS_STATE_c_317 , 3, 'i', LTS_STATE_c_17 , LTS_STATE_c_318 , 1, 'f', LTS_STATE_c_50 , LTS_STATE_c_319 , 5, 'u', LTS_STATE_c_17 , LTS_STATE_c_320 , 1, 'a', LTS_STATE_c_5 , LTS_STATE_c_321 , 2, 'a', LTS_STATE_c_17 , LTS_STATE_c_322 , 3, 'o', LTS_STATE_c_17 , LTS_STATE_c_25 , 6, 'e', LTS_STATE_c_50 , LTS_STATE_c_323 , 5, 'o', LTS_STATE_c_325 , LTS_STATE_c_324 , 1, 'o', LTS_STATE_c_25 , LTS_STATE_c_326 , 1, '#', LTS_STATE_c_17 , LTS_STATE_c_283 , 1, 't', LTS_STATE_c_50 , LTS_STATE_c_327 , 6, 'i', LTS_STATE_c_137 , LTS_STATE_c_328 , 6, '#', LTS_STATE_c_17 , LTS_STATE_c_329 , 1, 'u', LTS_STATE_c_25 , LTS_STATE_c_330 , 3, 'a', LTS_STATE_c_331 , LTS_STATE_c_50 , 2, 'n', LTS_STATE_c_25 , LTS_STATE_c_332 , 1, '0', LTS_STATE_c_25 , LTS_STATE_c_17 , 3, 'a', LTS_STATE_c_25 , LTS_STATE_c_333 , 2, 'f', LTS_STATE_c_50 , LTS_STATE_c_334 , 1, '#', LTS_STATE_c_336 , LTS_STATE_c_335 , 1, 'r', LTS_STATE_c_25 , LTS_STATE_c_337 , 5, 't', LTS_STATE_c_50 , LTS_STATE_c_338 , 5, 'm', LTS_STATE_c_17 , LTS_STATE_c_25 , 5, 'y', LTS_STATE_c_17 , LTS_STATE_c_339 , 3, 'i', LTS_STATE_c_17 , LTS_STATE_c_340 , 1, '#', LTS_STATE_c_50 , LTS_STATE_c_341 , 2, 'm', LTS_STATE_c_17 , LTS_STATE_c_342 , 2, 'a', LTS_STATE_c_17 , LTS_STATE_c_343 , 1, 'g', LTS_STATE_c_50 , LTS_STATE_c_344 , 6, 'a', LTS_STATE_c_17 , LTS_STATE_c_25 , 2, 'i', LTS_STATE_c_17 , LTS_STATE_c_25 , 1, 'r', LTS_STATE_c_50 , LTS_STATE_c_345 , 5, '#', LTS_STATE_c_50 , LTS_STATE_c_17 , /** letter d **/ 4, '#', LTS_STATE_d_2 , LTS_STATE_d_1 , 4, 'd', LTS_STATE_d_4 , LTS_STATE_d_3 , 3, 'e', LTS_STATE_d_6 , LTS_STATE_d_5 , 4, 'g', LTS_STATE_d_8 , LTS_STATE_d_7 , 2, 'g', LTS_STATE_d_10 , LTS_STATE_d_9 , 255, 26, 0,0 , 0,0 , 2, 'k', LTS_STATE_d_13 , LTS_STATE_d_12 , 4, 't', LTS_STATE_d_15 , LTS_STATE_d_14 , 5, 'e', LTS_STATE_d_17 , LTS_STATE_d_16 , 3, 'o', LTS_STATE_d_17 , LTS_STATE_d_18 , 3, 'o', LTS_STATE_d_5 , LTS_STATE_d_17 , 2, 'h', LTS_STATE_d_20 , LTS_STATE_d_19 , 255, 27, 0,0 , 0,0 , 4, 'j', LTS_STATE_d_17 , LTS_STATE_d_21 , 5, '#', LTS_STATE_d_23 , LTS_STATE_d_22 , 5, 'r', LTS_STATE_d_5 , LTS_STATE_d_24 , 255, 0, 0,0 , 0,0 , 2, 'b', LTS_STATE_d_17 , LTS_STATE_d_25 , 2, 'p', LTS_STATE_d_13 , LTS_STATE_d_26 , 1, 't', LTS_STATE_d_5 , LTS_STATE_d_27 , 3, 'd', LTS_STATE_d_29 , LTS_STATE_d_28 , 1, '#', LTS_STATE_d_5 , LTS_STATE_d_30 , 3, 'u', LTS_STATE_d_5 , LTS_STATE_d_10 , 5, 'a', LTS_STATE_d_5 , LTS_STATE_d_31 , 3, 'e', LTS_STATE_d_33 , LTS_STATE_d_32 , 2, 'c', LTS_STATE_d_13 , LTS_STATE_d_34 , 1, 'g', LTS_STATE_d_5 , LTS_STATE_d_13 , 4, 'u', LTS_STATE_d_36 , LTS_STATE_d_35 , 2, 'e', LTS_STATE_d_38 , LTS_STATE_d_37 , 5, 'h', LTS_STATE_d_5 , LTS_STATE_d_39 , 5, 'o', LTS_STATE_d_5 , LTS_STATE_d_17 , 5, 'y', LTS_STATE_d_17 , LTS_STATE_d_40 , 5, 'y', LTS_STATE_d_5 , LTS_STATE_d_41 , 2, 's', LTS_STATE_d_43 , LTS_STATE_d_42 , 4, 'z', LTS_STATE_d_44 , LTS_STATE_d_5 , 2, '0', LTS_STATE_d_5 , LTS_STATE_d_45 , 4, 'e', LTS_STATE_d_47 , LTS_STATE_d_46 , 4, 'y', LTS_STATE_d_17 , LTS_STATE_d_48 , 1, 'o', LTS_STATE_d_5 , LTS_STATE_d_49 , 5, 'i', LTS_STATE_d_17 , LTS_STATE_d_50 , 6, 'r', LTS_STATE_d_17 , LTS_STATE_d_51 , 2, 'f', LTS_STATE_d_13 , LTS_STATE_d_52 , 1, 's', LTS_STATE_d_13 , LTS_STATE_d_53 , 6, '#', LTS_STATE_d_5 , LTS_STATE_d_54 , 5, 'a', LTS_STATE_d_56 , LTS_STATE_d_55 , 1, '#', LTS_STATE_d_5 , LTS_STATE_d_57 , 1, 'b', LTS_STATE_d_5 , LTS_STATE_d_58 , 6, '#', LTS_STATE_d_5 , LTS_STATE_d_59 , 5, 'k', LTS_STATE_d_5 , LTS_STATE_d_17 , 2, 'm', LTS_STATE_d_17 , LTS_STATE_d_60 , 2, 'p', LTS_STATE_d_5 , LTS_STATE_d_17 , 2, 'x', LTS_STATE_d_13 , LTS_STATE_d_5 , 1, 'r', LTS_STATE_d_13 , LTS_STATE_d_61 , 6, 'k', LTS_STATE_d_5 , LTS_STATE_d_62 , 5, 'l', LTS_STATE_d_64 , LTS_STATE_d_63 , 1, 'g', LTS_STATE_d_62 , LTS_STATE_d_65 , 1, 'w', LTS_STATE_d_5 , LTS_STATE_d_66 , 1, 'l', LTS_STATE_d_5 , LTS_STATE_d_67 , 1, 'p', LTS_STATE_d_17 , LTS_STATE_d_68 , 6, 'd', LTS_STATE_d_17 , LTS_STATE_d_69 , 1, 'a', LTS_STATE_d_13 , LTS_STATE_d_70 , 255, 28, 0,0 , 0,0 , 3, 'e', LTS_STATE_d_71 , LTS_STATE_d_5 , 3, 'o', LTS_STATE_d_62 , LTS_STATE_d_72 , 3, 'i', LTS_STATE_d_62 , LTS_STATE_d_5 , 6, 'd', LTS_STATE_d_5 , LTS_STATE_d_73 , 5, 'd', LTS_STATE_d_5 , LTS_STATE_d_74 , 5, 'r', LTS_STATE_d_5 , LTS_STATE_d_75 , 2, 'w', LTS_STATE_d_5 , LTS_STATE_d_76 , 1, 'n', LTS_STATE_d_13 , LTS_STATE_d_77 , 1, '#', LTS_STATE_d_5 , LTS_STATE_d_78 , 2, 'h', LTS_STATE_d_62 , LTS_STATE_d_79 , 2, 'a', LTS_STATE_d_81 , LTS_STATE_d_80 , 1, 'm', LTS_STATE_d_5 , LTS_STATE_d_82 , 4, 'i', LTS_STATE_d_5 , LTS_STATE_d_83 , 1, 's', LTS_STATE_d_85 , LTS_STATE_d_84 , 1, 'i', LTS_STATE_d_5 , LTS_STATE_d_86 , 1, '0', LTS_STATE_d_62 , LTS_STATE_d_87 , 6, 't', LTS_STATE_d_5 , LTS_STATE_d_88 , 1, 'r', LTS_STATE_d_89 , LTS_STATE_d_5 , 6, '#', LTS_STATE_d_5 , LTS_STATE_d_90 , 1, 's', LTS_STATE_d_5 , LTS_STATE_d_91 , 5, '#', LTS_STATE_d_17 , LTS_STATE_d_5 , 2, 'p', LTS_STATE_d_17 , LTS_STATE_d_92 , 2, 'h', LTS_STATE_d_5 , LTS_STATE_d_17 , 1, 'o', LTS_STATE_d_5 , LTS_STATE_d_93 , 5, 'c', LTS_STATE_d_5 , LTS_STATE_d_62 , 2, 'i', LTS_STATE_d_5 , LTS_STATE_d_94 , 2, 'i', LTS_STATE_d_17 , LTS_STATE_d_5 , 1, 'h', LTS_STATE_d_17 , LTS_STATE_d_5 , 6, '#', LTS_STATE_d_5 , LTS_STATE_d_95 , 1, 'c', LTS_STATE_d_17 , LTS_STATE_d_96 , 1, 'u', LTS_STATE_d_5 , LTS_STATE_d_13 , 3, 'n', LTS_STATE_d_62 , LTS_STATE_d_5 , 2, 'a', LTS_STATE_d_17 , LTS_STATE_d_97 , 2, 'l', LTS_STATE_d_17 , LTS_STATE_d_98 , 5, 'r', LTS_STATE_d_17 , LTS_STATE_d_5 , 2, 'f', LTS_STATE_d_17 , LTS_STATE_d_99 , 3, 'i', LTS_STATE_d_101 , LTS_STATE_d_100 , 2, 'r', LTS_STATE_d_17 , LTS_STATE_d_102 , 2, 'r', LTS_STATE_d_5 , LTS_STATE_d_17 , 5, 'e', LTS_STATE_d_103 , LTS_STATE_d_17 , 1, '#', LTS_STATE_d_17 , LTS_STATE_d_5 , /** letter e **/ 6, '0', LTS_STATE_e_2 , LTS_STATE_e_1 , 4, 'r', LTS_STATE_e_4 , LTS_STATE_e_3 , 4, '#', LTS_STATE_e_6 , LTS_STATE_e_5 , 4, 'a', LTS_STATE_e_8 , LTS_STATE_e_7 , 5, 'r', LTS_STATE_e_10 , LTS_STATE_e_9 , 4, 'r', LTS_STATE_e_12 , LTS_STATE_e_11 , 3, 'e', LTS_STATE_e_14 , LTS_STATE_e_13 , 3, 'e', LTS_STATE_e_16 , LTS_STATE_e_15 , 5, 'r', LTS_STATE_e_18 , LTS_STATE_e_17 , 5, 'i', LTS_STATE_e_20 , LTS_STATE_e_19 , 3, 'b', LTS_STATE_e_22 , LTS_STATE_e_21 , 4, 'n', LTS_STATE_e_24 , LTS_STATE_e_23 , 3, 'e', LTS_STATE_e_26 , LTS_STATE_e_25 , 3, 'n', LTS_STATE_e_28 , LTS_STATE_e_27 , 2, 'r', LTS_STATE_e_30 , LTS_STATE_e_29 , 4, 'e', LTS_STATE_e_32 , LTS_STATE_e_31 , 2, 'r', LTS_STATE_e_34 , LTS_STATE_e_33 , 5, 'u', LTS_STATE_e_36 , LTS_STATE_e_35 , 3, 'w', LTS_STATE_e_22 , LTS_STATE_e_37 , 3, 'e', LTS_STATE_e_26 , LTS_STATE_e_38 , 6, 'n', LTS_STATE_e_40 , LTS_STATE_e_39 , 1, '0', LTS_STATE_e_42 , LTS_STATE_e_41 , 255, 1, 0,0 , 0,0 , 3, 'e', LTS_STATE_e_45 , LTS_STATE_e_44 , 3, 'e', LTS_STATE_e_30 , LTS_STATE_e_46 , 2, 'e', LTS_STATE_e_47 , LTS_STATE_e_36 , 255, 12, 0,0 , 0,0 , 3, 'r', LTS_STATE_e_49 , LTS_STATE_e_48 , 2, 'o', LTS_STATE_e_51 , LTS_STATE_e_50 , 2, 'p', LTS_STATE_e_30 , LTS_STATE_e_52 , 255, 29, 0,0 , 0,0 , 4, 'i', LTS_STATE_e_54 , LTS_STATE_e_53 , 3, 'r', LTS_STATE_e_55 , LTS_STATE_e_36 , 2, 'f', LTS_STATE_e_56 , LTS_STATE_e_30 , 1, '#', LTS_STATE_e_58 , LTS_STATE_e_57 , 5, 'd', LTS_STATE_e_60 , LTS_STATE_e_59 , 255, 0, 0,0 , 0,0 , 3, 'b', LTS_STATE_e_62 , LTS_STATE_e_61 , 5, 'o', LTS_STATE_e_64 , LTS_STATE_e_63 , 6, 'a', LTS_STATE_e_66 , LTS_STATE_e_65 , 3, 'e', LTS_STATE_e_26 , LTS_STATE_e_36 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_67 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_68 , 4, 'l', LTS_STATE_e_70 , LTS_STATE_e_69 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_71 , 3, 'm', LTS_STATE_e_73 , LTS_STATE_e_72 , 3, 'w', LTS_STATE_e_75 , LTS_STATE_e_74 , 3, 'k', LTS_STATE_e_77 , LTS_STATE_e_76 , 2, 'd', LTS_STATE_e_79 , LTS_STATE_e_78 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_80 , 1, 'i', LTS_STATE_e_82 , LTS_STATE_e_81 , 2, 'n', LTS_STATE_e_30 , LTS_STATE_e_83 , 1, '0', LTS_STATE_e_85 , LTS_STATE_e_84 , 5, 'r', LTS_STATE_e_87 , LTS_STATE_e_86 , 1, '0', LTS_STATE_e_89 , LTS_STATE_e_88 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_90 , 1, 'p', LTS_STATE_e_91 , LTS_STATE_e_30 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_92 , 6, 'h', LTS_STATE_e_95 , LTS_STATE_e_94 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_96 , 1, 'u', LTS_STATE_e_82 , LTS_STATE_e_97 , 6, 'd', LTS_STATE_e_36 , LTS_STATE_e_22 , 5, 'e', LTS_STATE_e_99 , LTS_STATE_e_98 , 1, '0', LTS_STATE_e_101 , LTS_STATE_e_100 , 6, 'o', LTS_STATE_e_103 , LTS_STATE_e_102 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_104 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_105 , 6, 'a', LTS_STATE_e_106 , LTS_STATE_e_22 , 4, 'k', LTS_STATE_e_108 , LTS_STATE_e_107 , 3, 'i', LTS_STATE_e_110 , LTS_STATE_e_109 , 2, 'r', LTS_STATE_e_30 , LTS_STATE_e_111 , 2, 'g', LTS_STATE_e_113 , LTS_STATE_e_112 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_114 , 3, 'y', LTS_STATE_e_115 , LTS_STATE_e_36 , 255, 30, 0,0 , 0,0 , 2, 'n', LTS_STATE_e_117 , LTS_STATE_e_116 , 2, 't', LTS_STATE_e_82 , LTS_STATE_e_118 , 2, 'b', LTS_STATE_e_36 , LTS_STATE_e_119 , 1, 'n', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 'a', LTS_STATE_e_36 , LTS_STATE_e_120 , 1, 't', LTS_STATE_e_36 , LTS_STATE_e_121 , 255, 31, 0,0 , 0,0 , 1, 'd', LTS_STATE_e_30 , LTS_STATE_e_122 , 3, 'i', LTS_STATE_e_124 , LTS_STATE_e_123 , 3, 'r', LTS_STATE_e_126 , LTS_STATE_e_125 , 5, 'g', LTS_STATE_e_128 , LTS_STATE_e_127 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_129 , 2, 'p', LTS_STATE_e_130 , LTS_STATE_e_36 , 6, 'a', LTS_STATE_e_82 , LTS_STATE_e_131 , 4, 'd', LTS_STATE_e_82 , LTS_STATE_e_30 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_132 , 4, 'n', LTS_STATE_e_26 , LTS_STATE_e_133 , 255, 5, 0,0 , 0,0 , 1, '0', LTS_STATE_e_135 , LTS_STATE_e_134 , 5, 't', LTS_STATE_e_136 , LTS_STATE_e_30 , 3, 't', LTS_STATE_e_138 , LTS_STATE_e_137 , 6, 'r', LTS_STATE_e_30 , LTS_STATE_e_36 , 5, 'a', LTS_STATE_e_140 , LTS_STATE_e_139 , 6, 'd', LTS_STATE_e_36 , LTS_STATE_e_141 , 6, '#', LTS_STATE_e_143 , LTS_STATE_e_142 , 3, 'a', LTS_STATE_e_22 , LTS_STATE_e_144 , 6, 'e', LTS_STATE_e_146 , LTS_STATE_e_145 , 3, 't', LTS_STATE_e_26 , LTS_STATE_e_147 , 2, 'a', LTS_STATE_e_26 , LTS_STATE_e_148 , 6, 'y', LTS_STATE_e_22 , LTS_STATE_e_149 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_150 , 3, 't', LTS_STATE_e_152 , LTS_STATE_e_151 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_153 , 3, 't', LTS_STATE_e_155 , LTS_STATE_e_154 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_156 , 4, 'd', LTS_STATE_e_30 , LTS_STATE_e_157 , 3, 'i', LTS_STATE_e_159 , LTS_STATE_e_158 , 3, 'r', LTS_STATE_e_160 , LTS_STATE_e_93 , 2, 'l', LTS_STATE_e_160 , LTS_STATE_e_161 , 1, 'm', LTS_STATE_e_36 , LTS_STATE_e_162 , 3, 'h', LTS_STATE_e_36 , LTS_STATE_e_163 , 3, 't', LTS_STATE_e_164 , LTS_STATE_e_36 , 2, 'z', LTS_STATE_e_82 , LTS_STATE_e_165 , 1, 'i', LTS_STATE_e_167 , LTS_STATE_e_166 , 2, 'e', LTS_STATE_e_36 , LTS_STATE_e_168 , 1, 'h', LTS_STATE_e_36 , LTS_STATE_e_169 , 2, 's', LTS_STATE_e_171 , LTS_STATE_e_170 , 5, 't', LTS_STATE_e_173 , LTS_STATE_e_172 , 5, 't', LTS_STATE_e_175 , LTS_STATE_e_174 , 4, 'w', LTS_STATE_e_177 , LTS_STATE_e_176 , 4, 'v', LTS_STATE_e_179 , LTS_STATE_e_178 , 3, 'r', LTS_STATE_e_181 , LTS_STATE_e_180 , 6, 'h', LTS_STATE_e_183 , LTS_STATE_e_182 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_184 , 5, 'm', LTS_STATE_e_82 , LTS_STATE_e_36 , 6, 't', LTS_STATE_e_82 , LTS_STATE_e_36 , 255, 16, 0,0 , 0,0 , 6, '#', LTS_STATE_e_30 , LTS_STATE_e_185 , 5, 's', LTS_STATE_e_187 , LTS_STATE_e_186 , 3, 'r', LTS_STATE_e_189 , LTS_STATE_e_188 , 2, '#', LTS_STATE_e_22 , LTS_STATE_e_190 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_191 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_192 , 5, 'u', LTS_STATE_e_194 , LTS_STATE_e_193 , 6, '#', LTS_STATE_e_196 , LTS_STATE_e_195 , 1, '0', LTS_STATE_e_198 , LTS_STATE_e_197 , 1, '#', LTS_STATE_e_184 , LTS_STATE_e_36 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_22 , 6, 'u', LTS_STATE_e_36 , LTS_STATE_e_199 , 3, 'd', LTS_STATE_e_201 , LTS_STATE_e_200 , 1, '0', LTS_STATE_e_22 , LTS_STATE_e_202 , 1, 'i', LTS_STATE_e_22 , LTS_STATE_e_203 , 2, 'i', LTS_STATE_e_26 , LTS_STATE_e_204 , 1, 'm', LTS_STATE_e_22 , LTS_STATE_e_205 , 3, 't', LTS_STATE_e_36 , LTS_STATE_e_206 , 4, 't', LTS_STATE_e_208 , LTS_STATE_e_207 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_209 , 3, 't', LTS_STATE_e_211 , LTS_STATE_e_210 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_212 , 2, 's', LTS_STATE_e_93 , LTS_STATE_e_213 , 1, 'a', LTS_STATE_e_214 , LTS_STATE_e_36 , 1, 's', LTS_STATE_e_30 , LTS_STATE_e_215 , 1, '#', LTS_STATE_e_216 , LTS_STATE_e_93 , 2, 't', LTS_STATE_e_36 , LTS_STATE_e_217 , 255, 32, 0,0 , 0,0 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_218 , 255, 3, 0,0 , 0,0 , 2, 'e', LTS_STATE_e_220 , LTS_STATE_e_219 , 1, 'a', LTS_STATE_e_82 , LTS_STATE_e_221 , 2, 'd', LTS_STATE_e_82 , LTS_STATE_e_222 , 1, 'd', LTS_STATE_e_36 , LTS_STATE_e_223 , 2, 'o', LTS_STATE_e_82 , LTS_STATE_e_36 , 2, 'y', LTS_STATE_e_36 , LTS_STATE_e_224 , 1, 'b', LTS_STATE_e_36 , LTS_STATE_e_225 , 1, 'e', LTS_STATE_e_82 , LTS_STATE_e_226 , 1, 's', LTS_STATE_e_82 , LTS_STATE_e_30 , 5, 's', LTS_STATE_e_228 , LTS_STATE_e_227 , 6, '#', LTS_STATE_e_230 , LTS_STATE_e_229 , 4, 'n', LTS_STATE_e_232 , LTS_STATE_e_231 , 4, 's', LTS_STATE_e_234 , LTS_STATE_e_233 , 4, 'u', LTS_STATE_e_236 , LTS_STATE_e_235 , 3, 'n', LTS_STATE_e_238 , LTS_STATE_e_237 , 4, 'u', LTS_STATE_e_240 , LTS_STATE_e_239 , 5, 'i', LTS_STATE_e_242 , LTS_STATE_e_241 , 3, 'v', LTS_STATE_e_244 , LTS_STATE_e_243 , 5, 'n', LTS_STATE_e_246 , LTS_STATE_e_245 , 6, 'n', LTS_STATE_e_247 , LTS_STATE_e_36 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_248 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_36 , 5, 'e', LTS_STATE_e_249 , LTS_STATE_e_30 , 5, 'b', LTS_STATE_e_251 , LTS_STATE_e_250 , 6, 'u', LTS_STATE_e_22 , LTS_STATE_e_252 , 3, 'h', LTS_STATE_e_254 , LTS_STATE_e_253 , 5, 'g', LTS_STATE_e_256 , LTS_STATE_e_255 , 3, 'h', LTS_STATE_e_30 , LTS_STATE_e_22 , 3, 'r', LTS_STATE_e_258 , LTS_STATE_e_257 , 1, 'm', LTS_STATE_e_22 , LTS_STATE_e_259 , 2, 'e', LTS_STATE_e_261 , LTS_STATE_e_260 , 1, '0', LTS_STATE_e_262 , LTS_STATE_e_36 , 1, '0', LTS_STATE_e_264 , LTS_STATE_e_263 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_265 , 6, '#', LTS_STATE_e_267 , LTS_STATE_e_266 , 6, 'g', LTS_STATE_e_269 , LTS_STATE_e_268 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_270 , 6, 'z', LTS_STATE_e_36 , LTS_STATE_e_271 , 1, '0', LTS_STATE_e_272 , LTS_STATE_e_36 , 2, 'x', LTS_STATE_e_26 , LTS_STATE_e_36 , 3, 'p', LTS_STATE_e_26 , LTS_STATE_e_22 , 2, 'm', LTS_STATE_e_26 , LTS_STATE_e_273 , 6, 'o', LTS_STATE_e_275 , LTS_STATE_e_274 , 3, 'f', LTS_STATE_e_36 , LTS_STATE_e_22 , 4, 'w', LTS_STATE_e_277 , LTS_STATE_e_276 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_278 , 4, 's', LTS_STATE_e_280 , LTS_STATE_e_279 , 3, 'c', LTS_STATE_e_282 , LTS_STATE_e_281 , 2, 'a', LTS_STATE_e_160 , LTS_STATE_e_283 , 3, 'u', LTS_STATE_e_285 , LTS_STATE_e_284 , 2, 't', LTS_STATE_e_93 , LTS_STATE_e_286 , 2, 'n', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 's', LTS_STATE_e_30 , LTS_STATE_e_287 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_288 , 2, 'r', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 'r', LTS_STATE_e_160 , LTS_STATE_e_289 , 3, 'b', LTS_STATE_e_36 , LTS_STATE_e_290 , 3, 's', LTS_STATE_e_36 , LTS_STATE_e_291 , 1, 'o', LTS_STATE_e_82 , LTS_STATE_e_292 , 2, 'm', LTS_STATE_e_82 , LTS_STATE_e_36 , 2, 'u', LTS_STATE_e_36 , LTS_STATE_e_293 , 1, 'e', LTS_STATE_e_36 , LTS_STATE_e_294 , 1, 'd', LTS_STATE_e_36 , LTS_STATE_e_295 , 1, 'u', LTS_STATE_e_82 , LTS_STATE_e_296 , 4, 'n', LTS_STATE_e_298 , LTS_STATE_e_297 , 6, '#', LTS_STATE_e_300 , LTS_STATE_e_299 , 4, 'n', LTS_STATE_e_302 , LTS_STATE_e_301 , 4, 'n', LTS_STATE_e_304 , LTS_STATE_e_303 , 4, 't', LTS_STATE_e_306 , LTS_STATE_e_305 , 5, 'c', LTS_STATE_e_308 , LTS_STATE_e_307 , 1, 'o', LTS_STATE_e_310 , LTS_STATE_e_309 , 6, '#', LTS_STATE_e_93 , LTS_STATE_e_36 , 3, 'd', LTS_STATE_e_312 , LTS_STATE_e_311 , 3, 'd', LTS_STATE_e_314 , LTS_STATE_e_313 , 5, 'e', LTS_STATE_e_316 , LTS_STATE_e_315 , 255, 33, 0,0 , 0,0 , 4, 'n', LTS_STATE_e_318 , LTS_STATE_e_317 , 6, 'i', LTS_STATE_e_82 , LTS_STATE_e_319 , 5, 'a', LTS_STATE_e_82 , LTS_STATE_e_320 , 6, 'e', LTS_STATE_e_82 , LTS_STATE_e_321 , 2, 't', LTS_STATE_e_131 , LTS_STATE_e_322 , 5, 't', LTS_STATE_e_36 , LTS_STATE_e_323 , 5, 'm', LTS_STATE_e_324 , LTS_STATE_e_36 , 1, '0', LTS_STATE_e_325 , LTS_STATE_e_36 , 2, '#', LTS_STATE_e_162 , LTS_STATE_e_36 , 3, 'h', LTS_STATE_e_36 , LTS_STATE_e_326 , 4, 'l', LTS_STATE_e_93 , LTS_STATE_e_30 , 2, 'b', LTS_STATE_e_328 , LTS_STATE_e_327 , 2, 'a', LTS_STATE_e_36 , LTS_STATE_e_329 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_330 , 5, 'n', LTS_STATE_e_332 , LTS_STATE_e_331 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_333 , 5, 'c', LTS_STATE_e_82 , LTS_STATE_e_334 , 6, 'a', LTS_STATE_e_36 , LTS_STATE_e_30 , 1, '0', LTS_STATE_e_335 , LTS_STATE_e_30 , 1, '0', LTS_STATE_e_337 , LTS_STATE_e_336 , 6, '#', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, '#', LTS_STATE_e_36 , LTS_STATE_e_338 , 3, 'w', LTS_STATE_e_238 , LTS_STATE_e_339 , 6, 'p', LTS_STATE_e_132 , LTS_STATE_e_340 , 3, 'h', LTS_STATE_e_341 , LTS_STATE_e_36 , 2, '#', LTS_STATE_e_343 , LTS_STATE_e_342 , 3, 'h', LTS_STATE_e_36 , LTS_STATE_e_344 , 3, 'h', LTS_STATE_e_346 , LTS_STATE_e_345 , 3, 'i', LTS_STATE_e_348 , LTS_STATE_e_347 , 6, 'c', LTS_STATE_e_132 , LTS_STATE_e_349 , 3, 'd', LTS_STATE_e_82 , LTS_STATE_e_36 , 3, 's', LTS_STATE_e_160 , LTS_STATE_e_350 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_351 , 6, 'v', LTS_STATE_e_36 , LTS_STATE_e_352 , 1, '0', LTS_STATE_e_22 , LTS_STATE_e_26 , 1, 'a', LTS_STATE_e_36 , LTS_STATE_e_353 , 2, 'n', LTS_STATE_e_22 , LTS_STATE_e_36 , 4, 's', LTS_STATE_e_355 , LTS_STATE_e_354 , 2, 'v', LTS_STATE_e_75 , LTS_STATE_e_356 , 3, 'u', LTS_STATE_e_358 , LTS_STATE_e_357 , 4, 'e', LTS_STATE_e_36 , LTS_STATE_e_359 , 2, 'n', LTS_STATE_e_360 , LTS_STATE_e_36 , 3, 'z', LTS_STATE_e_160 , LTS_STATE_e_361 , 2, 'i', LTS_STATE_e_160 , LTS_STATE_e_362 , 1, 'o', LTS_STATE_e_160 , LTS_STATE_e_363 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_364 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 'r', LTS_STATE_e_366 , LTS_STATE_e_365 , 2, 'l', LTS_STATE_e_30 , LTS_STATE_e_367 , 2, 'o', LTS_STATE_e_93 , LTS_STATE_e_368 , 1, 'e', LTS_STATE_e_160 , LTS_STATE_e_369 , 2, 'b', LTS_STATE_e_36 , LTS_STATE_e_370 , 3, 'w', LTS_STATE_e_238 , LTS_STATE_e_36 , 1, 'e', LTS_STATE_e_82 , LTS_STATE_e_36 , 1, 't', LTS_STATE_e_36 , LTS_STATE_e_371 , 1, 'y', LTS_STATE_e_36 , LTS_STATE_e_372 , 1, 'e', LTS_STATE_e_36 , LTS_STATE_e_373 , 2, 'f', LTS_STATE_e_82 , LTS_STATE_e_374 , 4, 'l', LTS_STATE_e_376 , LTS_STATE_e_375 , 5, 'e', LTS_STATE_e_378 , LTS_STATE_e_377 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_379 , 4, 'y', LTS_STATE_e_36 , LTS_STATE_e_380 , 4, 's', LTS_STATE_e_382 , LTS_STATE_e_381 , 6, 's', LTS_STATE_e_384 , LTS_STATE_e_383 , 4, 't', LTS_STATE_e_386 , LTS_STATE_e_385 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_387 , 5, 'l', LTS_STATE_e_389 , LTS_STATE_e_388 , 1, '#', LTS_STATE_e_391 , LTS_STATE_e_390 , 1, 'f', LTS_STATE_e_22 , LTS_STATE_e_392 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_393 , 4, 'n', LTS_STATE_e_395 , LTS_STATE_e_394 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'x', LTS_STATE_e_397 , LTS_STATE_e_396 , 4, 'm', LTS_STATE_e_399 , LTS_STATE_e_398 , 3, 't', LTS_STATE_e_400 , LTS_STATE_e_36 , 5, 't', LTS_STATE_e_400 , LTS_STATE_e_36 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_401 , 6, 'l', LTS_STATE_e_402 , LTS_STATE_e_36 , 4, 'y', LTS_STATE_e_162 , LTS_STATE_e_403 , 6, 'w', LTS_STATE_e_93 , LTS_STATE_e_404 , 5, 's', LTS_STATE_e_36 , LTS_STATE_e_400 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_405 , 6, 'v', LTS_STATE_e_132 , LTS_STATE_e_82 , 3, 'd', LTS_STATE_e_36 , LTS_STATE_e_406 , 6, 'l', LTS_STATE_e_36 , LTS_STATE_e_162 , 6, 'b', LTS_STATE_e_30 , LTS_STATE_e_36 , 6, 't', LTS_STATE_e_82 , LTS_STATE_e_407 , 2, '0', LTS_STATE_e_162 , LTS_STATE_e_408 , 5, 'm', LTS_STATE_e_30 , LTS_STATE_e_409 , 3, 'r', LTS_STATE_e_36 , LTS_STATE_e_30 , 3, 'g', LTS_STATE_e_36 , LTS_STATE_e_410 , 2, 'b', LTS_STATE_e_22 , LTS_STATE_e_411 , 5, 't', LTS_STATE_e_30 , LTS_STATE_e_412 , 6, 'd', LTS_STATE_e_82 , LTS_STATE_e_30 , 5, 'v', LTS_STATE_e_22 , LTS_STATE_e_30 , 5, 'l', LTS_STATE_e_414 , LTS_STATE_e_413 , 3, 'b', LTS_STATE_e_30 , LTS_STATE_e_415 , 2, 'b', LTS_STATE_e_22 , LTS_STATE_e_416 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'z', LTS_STATE_e_418 , LTS_STATE_e_417 , 3, 'u', LTS_STATE_e_400 , LTS_STATE_e_36 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_22 , 6, 'p', LTS_STATE_e_22 , LTS_STATE_e_419 , 6, 's', LTS_STATE_e_132 , LTS_STATE_e_160 , 3, 'd', LTS_STATE_e_132 , LTS_STATE_e_420 , 2, 'e', LTS_STATE_e_36 , LTS_STATE_e_22 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_421 , 1, '#', LTS_STATE_e_423 , LTS_STATE_e_422 , 2, 'w', LTS_STATE_e_22 , LTS_STATE_e_424 , 2, 'r', LTS_STATE_e_36 , LTS_STATE_e_160 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_425 , 3, 'v', LTS_STATE_e_36 , LTS_STATE_e_426 , 1, 'a', LTS_STATE_e_428 , LTS_STATE_e_427 , 6, 's', LTS_STATE_e_36 , LTS_STATE_e_22 , 1, '#', LTS_STATE_e_430 , LTS_STATE_e_429 , 3, 'd', LTS_STATE_e_432 , LTS_STATE_e_431 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_433 , 1, '#', LTS_STATE_e_238 , LTS_STATE_e_434 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_435 , 2, 'q', LTS_STATE_e_162 , LTS_STATE_e_36 , 4, 'y', LTS_STATE_e_36 , LTS_STATE_e_436 , 1, 'e', LTS_STATE_e_160 , LTS_STATE_e_437 , 3, 's', LTS_STATE_e_160 , LTS_STATE_e_438 , 2, 'e', LTS_STATE_e_160 , LTS_STATE_e_439 , 2, 'i', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 'i', LTS_STATE_e_93 , LTS_STATE_e_440 , 2, 'h', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_441 , LTS_STATE_e_30 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 's', LTS_STATE_e_160 , LTS_STATE_e_442 , 3, 'j', LTS_STATE_e_36 , LTS_STATE_e_443 , 1, 's', LTS_STATE_e_444 , LTS_STATE_e_36 , 2, 'u', LTS_STATE_e_36 , LTS_STATE_e_445 , 1, 'm', LTS_STATE_e_36 , LTS_STATE_e_446 , 1, 'n', LTS_STATE_e_82 , LTS_STATE_e_447 , 4, 'w', LTS_STATE_e_449 , LTS_STATE_e_448 , 5, 'y', LTS_STATE_e_451 , LTS_STATE_e_450 , 5, 'd', LTS_STATE_e_453 , LTS_STATE_e_452 , 6, '#', LTS_STATE_e_455 , LTS_STATE_e_454 , 1, '#', LTS_STATE_e_457 , LTS_STATE_e_456 , 4, 'w', LTS_STATE_e_238 , LTS_STATE_e_458 , 4, 'u', LTS_STATE_e_460 , LTS_STATE_e_459 , 6, 'o', LTS_STATE_e_462 , LTS_STATE_e_461 , 6, 'l', LTS_STATE_e_93 , LTS_STATE_e_463 , 3, 'm', LTS_STATE_e_93 , LTS_STATE_e_464 , 4, 's', LTS_STATE_e_466 , LTS_STATE_e_465 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_467 , 3, 'm', LTS_STATE_e_93 , LTS_STATE_e_468 , 4, 'w', LTS_STATE_e_470 , LTS_STATE_e_469 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_471 , 2, 'p', LTS_STATE_e_36 , LTS_STATE_e_472 , 2, 'd', LTS_STATE_e_473 , LTS_STATE_e_36 , 5, 'n', LTS_STATE_e_22 , LTS_STATE_e_474 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_36 , 4, 't', LTS_STATE_e_475 , LTS_STATE_e_36 , 6, 'i', LTS_STATE_e_93 , LTS_STATE_e_476 , 4, 'y', LTS_STATE_e_478 , LTS_STATE_e_477 , 2, '#', LTS_STATE_e_22 , LTS_STATE_e_479 , 4, 'l', LTS_STATE_e_481 , LTS_STATE_e_480 , 6, 'g', LTS_STATE_e_22 , LTS_STATE_e_482 , 255, 34, 0,0 , 0,0 , 3, 'd', LTS_STATE_e_238 , LTS_STATE_e_483 , 3, 'j', LTS_STATE_e_238 , LTS_STATE_e_22 , 5, 'a', LTS_STATE_e_485 , LTS_STATE_e_484 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_486 , 5, 'e', LTS_STATE_e_132 , LTS_STATE_e_487 , 5, 'j', LTS_STATE_e_162 , LTS_STATE_e_488 , 6, 'v', LTS_STATE_e_30 , LTS_STATE_e_489 , 3, 'r', LTS_STATE_e_490 , LTS_STATE_e_162 , 3, 'w', LTS_STATE_e_492 , LTS_STATE_e_491 , 3, 'c', LTS_STATE_e_36 , LTS_STATE_e_493 , 6, '#', LTS_STATE_e_494 , LTS_STATE_e_30 , 6, 'u', LTS_STATE_e_496 , LTS_STATE_e_495 , 6, 'a', LTS_STATE_e_82 , LTS_STATE_e_30 , 6, 'i', LTS_STATE_e_30 , LTS_STATE_e_497 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_498 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_499 , 3, 'a', LTS_STATE_e_22 , LTS_STATE_e_500 , 1, '0', LTS_STATE_e_26 , LTS_STATE_e_36 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_501 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_502 , 2, 't', LTS_STATE_e_36 , LTS_STATE_e_26 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_160 , 1, 'l', LTS_STATE_e_36 , LTS_STATE_e_26 , 6, '#', LTS_STATE_e_26 , LTS_STATE_e_503 , 3, 'z', LTS_STATE_e_26 , LTS_STATE_e_504 , 6, 'd', LTS_STATE_e_36 , LTS_STATE_e_505 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 'n', LTS_STATE_e_36 , LTS_STATE_e_506 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_36 , 4, 'd', LTS_STATE_e_508 , LTS_STATE_e_507 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_509 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_510 , 3, 'h', LTS_STATE_e_512 , LTS_STATE_e_511 , 3, 'i', LTS_STATE_e_514 , LTS_STATE_e_513 , 4, 'm', LTS_STATE_e_93 , LTS_STATE_e_515 , 1, 'a', LTS_STATE_e_36 , LTS_STATE_e_160 , 3, 'l', LTS_STATE_e_517 , LTS_STATE_e_516 , 2, 'a', LTS_STATE_e_160 , LTS_STATE_e_518 , 2, 'p', LTS_STATE_e_93 , LTS_STATE_e_519 , 2, 'n', LTS_STATE_e_30 , LTS_STATE_e_520 , 2, 'h', LTS_STATE_e_160 , LTS_STATE_e_521 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_522 , 2, 'a', LTS_STATE_e_82 , LTS_STATE_e_36 , 2, 'r', LTS_STATE_e_36 , LTS_STATE_e_523 , 1, 'o', LTS_STATE_e_36 , LTS_STATE_e_524 , 1, 'a', LTS_STATE_e_82 , LTS_STATE_e_525 , 4, 'o', LTS_STATE_e_527 , LTS_STATE_e_526 , 1, '#', LTS_STATE_e_529 , LTS_STATE_e_528 , 5, 'l', LTS_STATE_e_531 , LTS_STATE_e_530 , 6, '#', LTS_STATE_e_36 , LTS_STATE_e_93 , 5, 'b', LTS_STATE_e_93 , LTS_STATE_e_532 , 6, 'o', LTS_STATE_e_534 , LTS_STATE_e_533 , 6, 's', LTS_STATE_e_36 , LTS_STATE_e_535 , 2, 'y', LTS_STATE_e_30 , LTS_STATE_e_536 , 4, 'w', LTS_STATE_e_538 , LTS_STATE_e_537 , 4, 's', LTS_STATE_e_540 , LTS_STATE_e_539 , 1, '#', LTS_STATE_e_542 , LTS_STATE_e_541 , 4, 'o', LTS_STATE_e_82 , LTS_STATE_e_543 , 3, 'r', LTS_STATE_e_400 , LTS_STATE_e_36 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_544 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_545 , 6, 'h', LTS_STATE_e_368 , LTS_STATE_e_546 , 1, 'r', LTS_STATE_e_22 , LTS_STATE_e_547 , 4, 'c', LTS_STATE_e_22 , LTS_STATE_e_548 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_549 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_550 , 3, 's', LTS_STATE_e_552 , LTS_STATE_e_551 , 1, 'a', LTS_STATE_e_214 , LTS_STATE_e_553 , 5, 's', LTS_STATE_e_555 , LTS_STATE_e_554 , 4, 'l', LTS_STATE_e_428 , LTS_STATE_e_36 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_556 , 5, 'z', LTS_STATE_e_36 , LTS_STATE_e_557 , 1, 'a', LTS_STATE_e_558 , LTS_STATE_e_36 , 6, '#', LTS_STATE_e_36 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_559 , 2, '#', LTS_STATE_e_561 , LTS_STATE_e_560 , 5, 'e', LTS_STATE_e_36 , LTS_STATE_e_562 , 5, 'a', LTS_STATE_e_132 , LTS_STATE_e_563 , 4, 'v', LTS_STATE_e_565 , LTS_STATE_e_564 , 5, 'i', LTS_STATE_e_567 , LTS_STATE_e_566 , 5, 'i', LTS_STATE_e_569 , LTS_STATE_e_568 , 3, 'l', LTS_STATE_e_571 , LTS_STATE_e_570 , 4, 'j', LTS_STATE_e_132 , LTS_STATE_e_572 , 6, 'l', LTS_STATE_e_574 , LTS_STATE_e_573 , 5, 'e', LTS_STATE_e_30 , LTS_STATE_e_575 , 5, 'o', LTS_STATE_e_132 , LTS_STATE_e_22 , 6, 'o', LTS_STATE_e_36 , LTS_STATE_e_576 , 6, 'f', LTS_STATE_e_30 , LTS_STATE_e_577 , 2, 'f', LTS_STATE_e_162 , LTS_STATE_e_36 , 6, 'i', LTS_STATE_e_579 , LTS_STATE_e_578 , 5, 't', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'l', LTS_STATE_e_30 , LTS_STATE_e_36 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_82 , 6, 'o', LTS_STATE_e_581 , LTS_STATE_e_580 , 5, 's', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'l', LTS_STATE_e_82 , LTS_STATE_e_30 , 3, 'l', LTS_STATE_e_582 , LTS_STATE_e_30 , 1, 's', LTS_STATE_e_22 , LTS_STATE_e_583 , 1, 'l', LTS_STATE_e_585 , LTS_STATE_e_584 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_586 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_587 , 3, 'j', LTS_STATE_e_22 , LTS_STATE_e_588 , 2, '#', LTS_STATE_e_206 , LTS_STATE_e_132 , 6, 's', LTS_STATE_e_590 , LTS_STATE_e_589 , 1, 'd', LTS_STATE_e_36 , LTS_STATE_e_591 , 4, 'y', LTS_STATE_e_593 , LTS_STATE_e_592 , 3, 'w', LTS_STATE_e_595 , LTS_STATE_e_594 , 4, 'z', LTS_STATE_e_160 , LTS_STATE_e_596 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_597 , 3, 'r', LTS_STATE_e_599 , LTS_STATE_e_598 , 255, 35, 0,0 , 0,0 , 2, 'o', LTS_STATE_e_601 , LTS_STATE_e_600 , 2, 'l', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 't', LTS_STATE_e_36 , LTS_STATE_e_602 , 1, 'z', LTS_STATE_e_160 , LTS_STATE_e_603 , 2, 'a', LTS_STATE_e_160 , LTS_STATE_e_604 , 2, 'u', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'p', LTS_STATE_e_606 , LTS_STATE_e_605 , 2, 't', LTS_STATE_e_30 , LTS_STATE_e_82 , 1, 'w', LTS_STATE_e_160 , LTS_STATE_e_607 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_608 , 2, 'n', LTS_STATE_e_36 , LTS_STATE_e_609 , 1, 'r', LTS_STATE_e_36 , LTS_STATE_e_610 , 2, 'b', LTS_STATE_e_171 , LTS_STATE_e_611 , 6, '#', LTS_STATE_e_613 , LTS_STATE_e_612 , 3, 'g', LTS_STATE_e_36 , LTS_STATE_e_614 , 6, '#', LTS_STATE_e_238 , LTS_STATE_e_615 , 5, 'e', LTS_STATE_e_617 , LTS_STATE_e_616 , 5, 'd', LTS_STATE_e_619 , LTS_STATE_e_618 , 6, '#', LTS_STATE_e_621 , LTS_STATE_e_620 , 6, '#', LTS_STATE_e_623 , LTS_STATE_e_622 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_624 , 3, 'u', LTS_STATE_e_22 , LTS_STATE_e_625 , 6, 'd', LTS_STATE_e_93 , LTS_STATE_e_626 , 2, 'l', LTS_STATE_e_30 , LTS_STATE_e_627 , 4, 's', LTS_STATE_e_629 , LTS_STATE_e_628 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_630 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_631 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_632 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_633 , 4, 'n', LTS_STATE_e_93 , LTS_STATE_e_634 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_635 , 2, 'n', LTS_STATE_e_22 , LTS_STATE_e_636 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_637 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_638 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_639 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_640 , 3, 'u', LTS_STATE_e_22 , LTS_STATE_e_641 , 3, 'g', LTS_STATE_e_643 , LTS_STATE_e_642 , 3, 'v', LTS_STATE_e_22 , LTS_STATE_e_644 , 1, 'r', LTS_STATE_e_22 , LTS_STATE_e_93 , 5, 'c', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 'v', LTS_STATE_e_645 , LTS_STATE_e_36 , 2, 'n', LTS_STATE_e_22 , LTS_STATE_e_75 , 2, 't', LTS_STATE_e_93 , LTS_STATE_e_646 , 5, 'e', LTS_STATE_e_36 , LTS_STATE_e_93 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 't', LTS_STATE_e_36 , LTS_STATE_e_647 , 4, 'n', LTS_STATE_e_649 , LTS_STATE_e_648 , 4, 'o', LTS_STATE_e_651 , LTS_STATE_e_650 , 3, 'k', LTS_STATE_e_653 , LTS_STATE_e_652 , 5, 'i', LTS_STATE_e_655 , LTS_STATE_e_654 , 4, 'c', LTS_STATE_e_657 , LTS_STATE_e_656 , 6, 'a', LTS_STATE_e_30 , LTS_STATE_e_658 , 5, 'u', LTS_STATE_e_660 , LTS_STATE_e_659 , 6, 'c', LTS_STATE_e_22 , LTS_STATE_e_661 , 6, 'r', LTS_STATE_e_663 , LTS_STATE_e_662 , 6, 'l', LTS_STATE_e_82 , LTS_STATE_e_22 , 3, 's', LTS_STATE_e_238 , LTS_STATE_e_664 , 5, 'a', LTS_STATE_e_665 , LTS_STATE_e_238 , 5, 'e', LTS_STATE_e_667 , LTS_STATE_e_666 , 6, 'i', LTS_STATE_e_93 , LTS_STATE_e_668 , 4, 'c', LTS_STATE_e_132 , LTS_STATE_e_669 , 6, 'i', LTS_STATE_e_160 , LTS_STATE_e_670 , 6, 'u', LTS_STATE_e_36 , LTS_STATE_e_671 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_672 , 6, 't', LTS_STATE_e_674 , LTS_STATE_e_673 , 2, 'c', LTS_STATE_e_82 , LTS_STATE_e_675 , 5, 'f', LTS_STATE_e_677 , LTS_STATE_e_676 , 5, 'l', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'e', LTS_STATE_e_30 , LTS_STATE_e_22 , 2, 'd', LTS_STATE_e_22 , LTS_STATE_e_678 , 5, 'y', LTS_STATE_e_680 , LTS_STATE_e_679 , 5, 't', LTS_STATE_e_681 , LTS_STATE_e_36 , 6, 'l', LTS_STATE_e_683 , LTS_STATE_e_682 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_684 , 6, 'a', LTS_STATE_e_36 , LTS_STATE_e_685 , 2, 'p', LTS_STATE_e_22 , LTS_STATE_e_686 , 1, '0', LTS_STATE_e_22 , LTS_STATE_e_36 , 3, 'f', LTS_STATE_e_36 , LTS_STATE_e_687 , 4, 'e', LTS_STATE_e_36 , LTS_STATE_e_688 , 3, 'k', LTS_STATE_e_690 , LTS_STATE_e_689 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_691 , 2, 'e', LTS_STATE_e_238 , LTS_STATE_e_36 , 4, 'a', LTS_STATE_e_82 , LTS_STATE_e_692 , 3, 'h', LTS_STATE_e_694 , LTS_STATE_e_693 , 1, 'e', LTS_STATE_e_238 , LTS_STATE_e_665 , 2, 'b', LTS_STATE_e_665 , LTS_STATE_e_238 , 2, 'c', LTS_STATE_e_696 , LTS_STATE_e_695 , 3, 'n', LTS_STATE_e_160 , LTS_STATE_e_93 , 2, 's', LTS_STATE_e_698 , LTS_STATE_e_697 , 1, 'p', LTS_STATE_e_132 , LTS_STATE_e_699 , 2, 'o', LTS_STATE_e_160 , LTS_STATE_e_132 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_700 , 2, 'a', LTS_STATE_e_93 , LTS_STATE_e_701 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_702 , 1, 'a', LTS_STATE_e_36 , LTS_STATE_e_703 , 1, 'o', LTS_STATE_e_36 , LTS_STATE_e_704 , 1, 'c', LTS_STATE_e_82 , LTS_STATE_e_705 , 1, 'i', LTS_STATE_e_82 , LTS_STATE_e_706 , 1, '#', LTS_STATE_e_708 , LTS_STATE_e_707 , 5, 'e', LTS_STATE_e_710 , LTS_STATE_e_709 , 1, '#', LTS_STATE_e_712 , LTS_STATE_e_711 , 2, 'c', LTS_STATE_e_238 , LTS_STATE_e_713 , 3, 'r', LTS_STATE_e_238 , LTS_STATE_e_714 , 6, 'l', LTS_STATE_e_238 , LTS_STATE_e_36 , 6, '#', LTS_STATE_e_716 , LTS_STATE_e_715 , 3, 'f', LTS_STATE_e_718 , LTS_STATE_e_717 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_719 , 3, 'w', LTS_STATE_e_721 , LTS_STATE_e_720 , 1, '#', LTS_STATE_e_723 , LTS_STATE_e_722 , 5, 'y', LTS_STATE_e_93 , LTS_STATE_e_724 , 2, 'l', LTS_STATE_e_726 , LTS_STATE_e_725 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'g', LTS_STATE_e_728 , LTS_STATE_e_727 , 2, 'i', LTS_STATE_e_30 , LTS_STATE_e_729 , 6, 'k', LTS_STATE_e_22 , LTS_STATE_e_730 , 6, 'l', LTS_STATE_e_732 , LTS_STATE_e_731 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_733 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_734 , 6, 'a', LTS_STATE_e_160 , LTS_STATE_e_735 , 4, 'n', LTS_STATE_e_93 , LTS_STATE_e_736 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_737 , 3, 'u', LTS_STATE_e_739 , LTS_STATE_e_738 , 1, '#', LTS_STATE_e_741 , LTS_STATE_e_740 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_742 , 2, 'i', LTS_STATE_e_22 , LTS_STATE_e_743 , 1, 'i', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'd', LTS_STATE_e_160 , LTS_STATE_e_744 , 1, 'd', LTS_STATE_e_22 , LTS_STATE_e_745 , 3, 'k', LTS_STATE_e_747 , LTS_STATE_e_746 , 2, 'd', LTS_STATE_e_93 , LTS_STATE_e_748 , 3, 'r', LTS_STATE_e_93 , LTS_STATE_e_749 , 5, 'e', LTS_STATE_e_36 , LTS_STATE_e_75 , 1, 'q', LTS_STATE_e_93 , LTS_STATE_e_750 , 2, 'c', LTS_STATE_e_751 , LTS_STATE_e_234 , 6, 'c', LTS_STATE_e_753 , LTS_STATE_e_752 , 5, 'g', LTS_STATE_e_755 , LTS_STATE_e_754 , 5, 't', LTS_STATE_e_757 , LTS_STATE_e_756 , 5, 'r', LTS_STATE_e_36 , LTS_STATE_e_758 , 5, 'r', LTS_STATE_e_22 , LTS_STATE_e_162 , 6, 'e', LTS_STATE_e_162 , LTS_STATE_e_30 , 6, 'c', LTS_STATE_e_22 , LTS_STATE_e_759 , 6, 's', LTS_STATE_e_132 , LTS_STATE_e_22 , 4, 'g', LTS_STATE_e_761 , LTS_STATE_e_760 , 5, 'e', LTS_STATE_e_93 , LTS_STATE_e_762 , 6, 'r', LTS_STATE_e_22 , LTS_STATE_e_763 , 6, 'o', LTS_STATE_e_765 , LTS_STATE_e_764 , 6, 'c', LTS_STATE_e_160 , LTS_STATE_e_93 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_93 , 5, 'e', LTS_STATE_e_26 , LTS_STATE_e_766 , 5, 'e', LTS_STATE_e_82 , LTS_STATE_e_767 , 3, 'j', LTS_STATE_e_238 , LTS_STATE_e_75 , 255, 36, 0,0 , 0,0 , 4, 'c', LTS_STATE_e_769 , LTS_STATE_e_768 , 6, 'r', LTS_STATE_e_771 , LTS_STATE_e_770 , 6, 'r', LTS_STATE_e_773 , LTS_STATE_e_772 , 4, 'g', LTS_STATE_e_132 , LTS_STATE_e_93 , 6, 'u', LTS_STATE_e_26 , LTS_STATE_e_22 , 3, 's', LTS_STATE_e_774 , LTS_STATE_e_36 , 6, 'c', LTS_STATE_e_82 , LTS_STATE_e_36 , 1, 't', LTS_STATE_e_22 , LTS_STATE_e_775 , 3, 'r', LTS_STATE_e_82 , LTS_STATE_e_776 , 3, 'd', LTS_STATE_e_30 , LTS_STATE_e_777 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_778 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_22 , 1, 't', LTS_STATE_e_22 , LTS_STATE_e_30 , 1, '0', LTS_STATE_e_780 , LTS_STATE_e_779 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, 'y', LTS_STATE_e_36 , LTS_STATE_e_781 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_782 , 3, 'g', LTS_STATE_e_160 , LTS_STATE_e_22 , 2, 'r', LTS_STATE_e_26 , LTS_STATE_e_36 , 6, 's', LTS_STATE_e_784 , LTS_STATE_e_783 , 6, '#', LTS_STATE_e_22 , LTS_STATE_e_785 , 6, 'e', LTS_STATE_e_36 , LTS_STATE_e_22 , 4, 'a', LTS_STATE_e_787 , LTS_STATE_e_786 , 3, 'v', LTS_STATE_e_789 , LTS_STATE_e_788 , 2, 'c', LTS_STATE_e_36 , LTS_STATE_e_790 , 3, 'm', LTS_STATE_e_36 , LTS_STATE_e_791 , 4, 'o', LTS_STATE_e_82 , LTS_STATE_e_792 , 3, 'z', LTS_STATE_e_93 , LTS_STATE_e_793 , 2, 't', LTS_STATE_e_36 , LTS_STATE_e_93 , 3, 'p', LTS_STATE_e_93 , LTS_STATE_e_794 , 1, 'o', LTS_STATE_e_162 , LTS_STATE_e_93 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_795 , 4, 'p', LTS_STATE_e_22 , LTS_STATE_e_160 , 3, 'r', LTS_STATE_e_797 , LTS_STATE_e_796 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_798 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'i', LTS_STATE_e_160 , LTS_STATE_e_93 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_799 , 2, 'g', LTS_STATE_e_36 , LTS_STATE_e_82 , 1, 'z', LTS_STATE_e_82 , LTS_STATE_e_800 , 1, 'r', LTS_STATE_e_520 , LTS_STATE_e_801 , 5, 'i', LTS_STATE_e_803 , LTS_STATE_e_802 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_804 , 4, 'u', LTS_STATE_e_806 , LTS_STATE_e_805 , 4, 'k', LTS_STATE_e_132 , LTS_STATE_e_807 , 6, 'l', LTS_STATE_e_30 , LTS_STATE_e_808 , 3, 'd', LTS_STATE_e_82 , LTS_STATE_e_809 , 6, 'c', LTS_STATE_e_36 , LTS_STATE_e_810 , 2, 's', LTS_STATE_e_238 , LTS_STATE_e_811 , 2, 'n', LTS_STATE_e_813 , LTS_STATE_e_812 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_814 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_815 , 6, 't', LTS_STATE_e_160 , LTS_STATE_e_816 , 3, 'u', LTS_STATE_e_687 , LTS_STATE_e_817 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_818 , 2, 'o', LTS_STATE_e_160 , LTS_STATE_e_819 , 5, 'c', LTS_STATE_e_821 , LTS_STATE_e_820 , 3, 'u', LTS_STATE_e_823 , LTS_STATE_e_822 , 5, 'a', LTS_STATE_e_825 , LTS_STATE_e_824 , 1, 'l', LTS_STATE_e_93 , LTS_STATE_e_826 , 1, 'a', LTS_STATE_e_22 , LTS_STATE_e_160 , 1, '#', LTS_STATE_e_828 , LTS_STATE_e_827 , 6, 'r', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'c', LTS_STATE_e_30 , LTS_STATE_e_829 , 6, 'e', LTS_STATE_e_831 , LTS_STATE_e_830 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_832 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_36 , 3, 'j', LTS_STATE_e_22 , LTS_STATE_e_833 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_834 , 6, 'n', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_835 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_836 , 4, 'l', LTS_STATE_e_838 , LTS_STATE_e_837 , 2, 'q', LTS_STATE_e_22 , LTS_STATE_e_839 , 6, 'a', LTS_STATE_e_841 , LTS_STATE_e_840 , 2, 'p', LTS_STATE_e_22 , LTS_STATE_e_842 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_843 , 1, 'd', LTS_STATE_e_22 , LTS_STATE_e_844 , 1, 'o', LTS_STATE_e_160 , LTS_STATE_e_845 , 3, 'w', LTS_STATE_e_22 , LTS_STATE_e_846 , 3, 'v', LTS_STATE_e_93 , LTS_STATE_e_847 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_160 , 2, 'g', LTS_STATE_e_160 , LTS_STATE_e_93 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_848 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_849 , 1, 's', LTS_STATE_e_93 , LTS_STATE_e_36 , 4, 'm', LTS_STATE_e_851 , LTS_STATE_e_850 , 4, 'l', LTS_STATE_e_93 , LTS_STATE_e_852 , 6, 'e', LTS_STATE_e_854 , LTS_STATE_e_853 , 6, 'l', LTS_STATE_e_26 , LTS_STATE_e_855 , 6, '#', LTS_STATE_e_857 , LTS_STATE_e_856 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_858 , 3, 'l', LTS_STATE_e_860 , LTS_STATE_e_859 , 6, 'm', LTS_STATE_e_132 , LTS_STATE_e_861 , 5, 'p', LTS_STATE_e_863 , LTS_STATE_e_862 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_132 , 5, 'i', LTS_STATE_e_865 , LTS_STATE_e_864 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_866 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_867 , 5, 'm', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'a', LTS_STATE_e_26 , LTS_STATE_e_868 , 5, 'a', LTS_STATE_e_22 , LTS_STATE_e_26 , 4, 'g', LTS_STATE_e_870 , LTS_STATE_e_869 , 5, 'u', LTS_STATE_e_132 , LTS_STATE_e_871 , 4, 's', LTS_STATE_e_873 , LTS_STATE_e_872 , 4, 'f', LTS_STATE_e_22 , LTS_STATE_e_874 , 4, 'm', LTS_STATE_e_30 , LTS_STATE_e_875 , 4, 'm', LTS_STATE_e_82 , LTS_STATE_e_93 , 5, 'n', LTS_STATE_e_162 , LTS_STATE_e_36 , 1, 'l', LTS_STATE_e_877 , LTS_STATE_e_876 , 5, 'n', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 'p', LTS_STATE_e_30 , LTS_STATE_e_878 , 6, 'a', LTS_STATE_e_30 , LTS_STATE_e_879 , 5, 't', LTS_STATE_e_881 , LTS_STATE_e_880 , 5, 'd', LTS_STATE_e_883 , LTS_STATE_e_882 , 6, 'i', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 's', LTS_STATE_e_36 , LTS_STATE_e_884 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_885 , 3, 't', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 't', LTS_STATE_e_430 , LTS_STATE_e_886 , 4, 'o', LTS_STATE_e_82 , LTS_STATE_e_887 , 3, 'y', LTS_STATE_e_36 , LTS_STATE_e_888 , 1, '#', LTS_STATE_e_889 , LTS_STATE_e_36 , 1, 'u', LTS_STATE_e_162 , LTS_STATE_e_36 , 1, 'a', LTS_STATE_e_890 , LTS_STATE_e_36 , 3, 'y', LTS_STATE_e_36 , LTS_STATE_e_891 , 4, 'e', LTS_STATE_e_36 , LTS_STATE_e_892 , 3, 'x', LTS_STATE_e_93 , LTS_STATE_e_893 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_894 , 4, 'c', LTS_STATE_e_22 , LTS_STATE_e_895 , 1, 'b', LTS_STATE_e_160 , LTS_STATE_e_896 , 2, 'o', LTS_STATE_e_132 , LTS_STATE_e_160 , 1, 'u', LTS_STATE_e_93 , LTS_STATE_e_897 , 3, 'l', LTS_STATE_e_898 , LTS_STATE_e_36 , 1, 's', LTS_STATE_e_82 , LTS_STATE_e_899 , 1, 't', LTS_STATE_e_30 , LTS_STATE_e_900 , 4, 'y', LTS_STATE_e_36 , LTS_STATE_e_901 , 6, 'a', LTS_STATE_e_903 , LTS_STATE_e_902 , 2, 'p', LTS_STATE_e_905 , LTS_STATE_e_904 , 4, 'c', LTS_STATE_e_907 , LTS_STATE_e_906 , 5, 'm', LTS_STATE_e_30 , LTS_STATE_e_908 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_909 , 3, 'k', LTS_STATE_e_36 , LTS_STATE_e_910 , 5, 'r', LTS_STATE_e_30 , LTS_STATE_e_911 , 6, 'l', LTS_STATE_e_912 , LTS_STATE_e_36 , 3, 'l', LTS_STATE_e_238 , LTS_STATE_e_36 , 6, 's', LTS_STATE_e_914 , LTS_STATE_e_913 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_915 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_916 , 6, '#', LTS_STATE_e_160 , LTS_STATE_e_917 , 1, 'r', LTS_STATE_e_160 , LTS_STATE_e_22 , 2, 'n', LTS_STATE_e_919 , LTS_STATE_e_918 , 3, 'b', LTS_STATE_e_921 , LTS_STATE_e_920 , 2, 'e', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'o', LTS_STATE_e_923 , LTS_STATE_e_922 , 6, 'e', LTS_STATE_e_925 , LTS_STATE_e_924 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_926 , 2, 'q', LTS_STATE_e_22 , LTS_STATE_e_36 , 5, 'o', LTS_STATE_e_22 , LTS_STATE_e_927 , 2, 'e', LTS_STATE_e_22 , LTS_STATE_e_928 , 1, 'b', LTS_STATE_e_160 , LTS_STATE_e_929 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_930 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_931 , 1, 'o', LTS_STATE_e_30 , LTS_STATE_e_932 , 4, 'n', LTS_STATE_e_934 , LTS_STATE_e_933 , 4, 'n', LTS_STATE_e_936 , LTS_STATE_e_935 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_937 , 3, 'z', LTS_STATE_e_22 , LTS_STATE_e_238 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_938 , 4, 's', LTS_STATE_e_940 , LTS_STATE_e_939 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_93 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_941 , 3, 'f', LTS_STATE_e_160 , LTS_STATE_e_942 , 2, 'h', LTS_STATE_e_36 , LTS_STATE_e_943 , 1, 'd', LTS_STATE_e_22 , LTS_STATE_e_944 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_945 , 2, 'c', LTS_STATE_e_22 , LTS_STATE_e_946 , 1, 'a', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, 'r', LTS_STATE_e_948 , LTS_STATE_e_947 , 4, 'l', LTS_STATE_e_949 , LTS_STATE_e_22 , 3, 'v', LTS_STATE_e_93 , LTS_STATE_e_950 , 3, 'm', LTS_STATE_e_26 , LTS_STATE_e_951 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_952 , 5, 'a', LTS_STATE_e_36 , LTS_STATE_e_217 , 4, 'q', LTS_STATE_e_954 , LTS_STATE_e_953 , 5, 'b', LTS_STATE_e_956 , LTS_STATE_e_955 , 4, 'v', LTS_STATE_e_132 , LTS_STATE_e_957 , 5, 'e', LTS_STATE_e_22 , LTS_STATE_e_958 , 5, 't', LTS_STATE_e_22 , LTS_STATE_e_959 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_960 , 5, 'u', LTS_STATE_e_962 , LTS_STATE_e_961 , 5, 'e', LTS_STATE_e_30 , LTS_STATE_e_963 , 6, 'a', LTS_STATE_e_965 , LTS_STATE_e_964 , 5, 'l', LTS_STATE_e_82 , LTS_STATE_e_966 , 6, 'e', LTS_STATE_e_160 , LTS_STATE_e_967 , 6, 'l', LTS_STATE_e_132 , LTS_STATE_e_968 , 4, 'p', LTS_STATE_e_970 , LTS_STATE_e_969 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_26 , 6, 'm', LTS_STATE_e_30 , LTS_STATE_e_971 , 6, 'm', LTS_STATE_e_22 , LTS_STATE_e_93 , 5, 'e', LTS_STATE_e_132 , LTS_STATE_e_972 , 6, 't', LTS_STATE_e_93 , LTS_STATE_e_973 , 5, 'o', LTS_STATE_e_974 , LTS_STATE_e_22 , 4, 'q', LTS_STATE_e_976 , LTS_STATE_e_975 , 5, 'r', LTS_STATE_e_132 , LTS_STATE_e_977 , 5, 'i', LTS_STATE_e_93 , LTS_STATE_e_978 , 4, 'c', LTS_STATE_e_93 , LTS_STATE_e_979 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_980 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_981 , 4, 'l', LTS_STATE_e_983 , LTS_STATE_e_982 , 3, 'c', LTS_STATE_e_985 , LTS_STATE_e_984 , 3, 'n', LTS_STATE_e_82 , LTS_STATE_e_30 , 2, 't', LTS_STATE_e_30 , LTS_STATE_e_986 , 6, 't', LTS_STATE_e_581 , LTS_STATE_e_30 , 2, 'a', LTS_STATE_e_987 , LTS_STATE_e_36 , 3, 'b', LTS_STATE_e_988 , LTS_STATE_e_36 , 3, 'p', LTS_STATE_e_36 , LTS_STATE_e_989 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_36 , 3, 'c', LTS_STATE_e_36 , LTS_STATE_e_990 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_991 , 6, 'l', LTS_STATE_e_993 , LTS_STATE_e_992 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_994 , 1, 'a', LTS_STATE_e_82 , LTS_STATE_e_995 , 3, 'r', LTS_STATE_e_162 , LTS_STATE_e_36 , 2, 'n', LTS_STATE_e_30 , LTS_STATE_e_36 , 3, 'f', LTS_STATE_e_36 , LTS_STATE_e_996 , 4, 'y', LTS_STATE_e_36 , LTS_STATE_e_997 , 3, 'i', LTS_STATE_e_36 , LTS_STATE_e_998 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_999 , 4, 'x', LTS_STATE_e_22 , LTS_STATE_e_1000 , 3, 'p', LTS_STATE_e_132 , LTS_STATE_e_1001 , 1, 'a', LTS_STATE_e_1003 , LTS_STATE_e_1002 , 2, 'a', LTS_STATE_e_1004 , LTS_STATE_e_36 , 1, 'n', LTS_STATE_e_82 , LTS_STATE_e_1005 , 1, 'l', LTS_STATE_e_82 , LTS_STATE_e_1006 , 6, 'n', LTS_STATE_e_1008 , LTS_STATE_e_1007 , 6, 'c', LTS_STATE_e_1010 , LTS_STATE_e_1009 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_1011 , 3, 'u', LTS_STATE_e_1013 , LTS_STATE_e_1012 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_1014 , 5, 'h', LTS_STATE_e_1016 , LTS_STATE_e_1015 , 5, 'k', LTS_STATE_e_1017 , LTS_STATE_e_22 , 5, 'x', LTS_STATE_e_1018 , LTS_STATE_e_36 , 4, 's', LTS_STATE_e_1020 , LTS_STATE_e_1019 , 5, 'l', LTS_STATE_e_82 , LTS_STATE_e_1021 , 5, 'd', LTS_STATE_e_30 , LTS_STATE_e_1022 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_36 , 5, 'i', LTS_STATE_e_1024 , LTS_STATE_e_1023 , 5, 'e', LTS_STATE_e_36 , LTS_STATE_e_1025 , 3, 'g', LTS_STATE_e_1027 , LTS_STATE_e_1026 , 5, 'e', LTS_STATE_e_1029 , LTS_STATE_e_1028 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_93 , 6, 'e', LTS_STATE_e_1031 , LTS_STATE_e_1030 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1032 , 2, 'r', LTS_STATE_e_1034 , LTS_STATE_e_1033 , 1, 'a', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'z', LTS_STATE_e_1036 , LTS_STATE_e_1035 , 1, 'b', LTS_STATE_e_30 , LTS_STATE_e_36 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_1037 , 1, 'o', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1038 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1039 , 3, 'l', LTS_STATE_e_162 , LTS_STATE_e_1040 , 2, 'e', LTS_STATE_e_22 , LTS_STATE_e_1041 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_1042 , 3, 'h', LTS_STATE_e_160 , LTS_STATE_e_97 , 1, 'a', LTS_STATE_e_30 , LTS_STATE_e_1043 , 4, 'l', LTS_STATE_e_93 , LTS_STATE_e_1044 , 1, 'i', LTS_STATE_e_1046 , LTS_STATE_e_1045 , 4, 'l', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'l', LTS_STATE_e_93 , LTS_STATE_e_1047 , 1, 'n', LTS_STATE_e_93 , LTS_STATE_e_1048 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_1049 , 4, 'u', LTS_STATE_e_82 , LTS_STATE_e_1050 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_1051 , 2, 'd', LTS_STATE_e_22 , LTS_STATE_e_1052 , 6, 'i', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_1053 , 2, 'i', LTS_STATE_e_160 , LTS_STATE_e_997 , 2, 'q', LTS_STATE_e_22 , LTS_STATE_e_1054 , 2, 'n', LTS_STATE_e_1056 , LTS_STATE_e_1055 , 3, 'c', LTS_STATE_e_1057 , LTS_STATE_e_93 , 3, 'f', LTS_STATE_e_22 , LTS_STATE_e_160 , 3, 'r', LTS_STATE_e_1059 , LTS_STATE_e_1058 , 2, 'b', LTS_STATE_e_160 , LTS_STATE_e_1060 , 2, 'n', LTS_STATE_e_1062 , LTS_STATE_e_1061 , 4, 'v', LTS_STATE_e_1064 , LTS_STATE_e_1063 , 6, 'a', LTS_STATE_e_30 , LTS_STATE_e_132 , 5, 'a', LTS_STATE_e_1066 , LTS_STATE_e_1065 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_160 , 4, 'd', LTS_STATE_e_22 , LTS_STATE_e_1067 , 5, 'u', LTS_STATE_e_93 , LTS_STATE_e_1068 , 5, 'd', LTS_STATE_e_160 , LTS_STATE_e_1069 , 6, 'a', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'i', LTS_STATE_e_1071 , LTS_STATE_e_1070 , 4, 'g', LTS_STATE_e_1073 , LTS_STATE_e_1072 , 5, 'a', LTS_STATE_e_1075 , LTS_STATE_e_1074 , 3, 'b', LTS_STATE_e_22 , LTS_STATE_e_1076 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_1077 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'o', LTS_STATE_e_30 , LTS_STATE_e_1078 , 5, 'p', LTS_STATE_e_1080 , LTS_STATE_e_1079 , 4, 'f', LTS_STATE_e_93 , LTS_STATE_e_1081 , 5, 'r', LTS_STATE_e_1083 , LTS_STATE_e_1082 , 5, 'h', LTS_STATE_e_22 , LTS_STATE_e_1084 , 6, 'l', LTS_STATE_e_1086 , LTS_STATE_e_1085 , 6, 'r', LTS_STATE_e_1088 , LTS_STATE_e_1087 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_26 , 4, 'f', LTS_STATE_e_1090 , LTS_STATE_e_1089 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_132 , 6, 'o', LTS_STATE_e_30 , LTS_STATE_e_22 , 6, 'n', LTS_STATE_e_82 , LTS_STATE_e_1091 , 6, 'a', LTS_STATE_e_1093 , LTS_STATE_e_1092 , 6, 'm', LTS_STATE_e_93 , LTS_STATE_e_82 , 4, 'p', LTS_STATE_e_22 , LTS_STATE_e_82 , 6, '#', LTS_STATE_e_30 , LTS_STATE_e_1094 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'h', LTS_STATE_e_30 , LTS_STATE_e_1095 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_30 , 5, 'l', LTS_STATE_e_30 , LTS_STATE_e_1096 , 1, 'c', LTS_STATE_e_36 , LTS_STATE_e_1097 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_1098 , 6, 'a', LTS_STATE_e_1099 , LTS_STATE_e_36 , 3, 'g', LTS_STATE_e_36 , LTS_STATE_e_735 , 3, 'c', LTS_STATE_e_22 , LTS_STATE_e_1100 , 3, 'p', LTS_STATE_e_1102 , LTS_STATE_e_1101 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_36 , 4, 'i', LTS_STATE_e_162 , LTS_STATE_e_1103 , 2, 'd', LTS_STATE_e_82 , LTS_STATE_e_1104 , 3, 'b', LTS_STATE_e_1102 , LTS_STATE_e_1105 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'e', LTS_STATE_e_291 , LTS_STATE_e_1106 , 1, 'b', LTS_STATE_e_93 , LTS_STATE_e_1107 , 4, 'z', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 'h', LTS_STATE_e_132 , LTS_STATE_e_1108 , 1, '#', LTS_STATE_e_997 , LTS_STATE_e_1109 , 3, 'c', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'd', LTS_STATE_e_36 , LTS_STATE_e_1110 , 1, 'p', LTS_STATE_e_82 , LTS_STATE_e_36 , 1, 'y', LTS_STATE_e_82 , LTS_STATE_e_1111 , 5, 'k', LTS_STATE_e_1113 , LTS_STATE_e_1112 , 4, 'm', LTS_STATE_e_1115 , LTS_STATE_e_1114 , 6, 'o', LTS_STATE_e_1117 , LTS_STATE_e_1116 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_1118 , 2, 'e', LTS_STATE_e_1119 , LTS_STATE_e_30 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_1120 , 2, 'q', LTS_STATE_e_1121 , LTS_STATE_e_36 , 4, 'v', LTS_STATE_e_1123 , LTS_STATE_e_1122 , 5, 'y', LTS_STATE_e_1125 , LTS_STATE_e_1124 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_1126 , 3, 'b', LTS_STATE_e_1128 , LTS_STATE_e_1127 , 255, 10, 0,0 , 0,0 , 4, 't', LTS_STATE_e_1130 , LTS_STATE_e_1129 , 2, 'a', LTS_STATE_e_1132 , LTS_STATE_e_1131 , 5, 'w', LTS_STATE_e_36 , LTS_STATE_e_1133 , 2, 'c', LTS_STATE_e_30 , LTS_STATE_e_520 , 6, 'n', LTS_STATE_e_1135 , LTS_STATE_e_1134 , 6, 'a', LTS_STATE_e_1137 , LTS_STATE_e_1136 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_1138 , 5, 'e', LTS_STATE_e_93 , LTS_STATE_e_1139 , 6, 'c', LTS_STATE_e_22 , LTS_STATE_e_1140 , 5, 'a', LTS_STATE_e_1141 , LTS_STATE_e_22 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1142 , 2, 's', LTS_STATE_e_1144 , LTS_STATE_e_1143 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_1145 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_1146 , 2, 'a', LTS_STATE_e_1148 , LTS_STATE_e_1147 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_1149 , 5, 'i', LTS_STATE_e_1151 , LTS_STATE_e_1150 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_1152 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1153 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_1154 , 5, 'z', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_1155 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_1156 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_1157 , 2, 'a', LTS_STATE_e_30 , LTS_STATE_e_1158 , 6, 'o', LTS_STATE_e_93 , LTS_STATE_e_36 , 6, 'u', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'n', LTS_STATE_e_22 , LTS_STATE_e_1159 , 2, 't', LTS_STATE_e_1161 , LTS_STATE_e_1160 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_935 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_1162 , 3, 'c', LTS_STATE_e_22 , LTS_STATE_e_1163 , 1, 'v', LTS_STATE_e_1165 , LTS_STATE_e_1164 , 3, 'v', LTS_STATE_e_1167 , LTS_STATE_e_1166 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_1168 , 6, 'o', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 'f', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'e', LTS_STATE_e_26 , LTS_STATE_e_1169 , 3, 'r', LTS_STATE_e_160 , LTS_STATE_e_1170 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_1171 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'c', LTS_STATE_e_1173 , LTS_STATE_e_1172 , 6, 'r', LTS_STATE_e_22 , LTS_STATE_e_1174 , 6, 'l', LTS_STATE_e_1176 , LTS_STATE_e_1175 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_30 , 4, 'p', LTS_STATE_e_22 , LTS_STATE_e_132 , 5, 'i', LTS_STATE_e_22 , LTS_STATE_e_1177 , 5, 'v', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'a', LTS_STATE_e_1179 , LTS_STATE_e_1178 , 6, 'o', LTS_STATE_e_30 , LTS_STATE_e_1180 , 4, 'c', LTS_STATE_e_1182 , LTS_STATE_e_1181 , 3, 'b', LTS_STATE_e_132 , LTS_STATE_e_1183 , 5, 'o', LTS_STATE_e_1184 , LTS_STATE_e_22 , 4, 'n', LTS_STATE_e_30 , LTS_STATE_e_1185 , 6, 'u', LTS_STATE_e_1186 , LTS_STATE_e_22 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_1187 , 5, 'n', LTS_STATE_e_960 , LTS_STATE_e_22 , 5, 'h', LTS_STATE_e_1189 , LTS_STATE_e_1188 , 6, 'a', LTS_STATE_e_132 , LTS_STATE_e_1190 , 6, 'r', LTS_STATE_e_1192 , LTS_STATE_e_1191 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_1193 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1194 , 5, 'k', LTS_STATE_e_22 , LTS_STATE_e_1195 , 5, 'a', LTS_STATE_e_22 , LTS_STATE_e_132 , 5, 'a', LTS_STATE_e_132 , LTS_STATE_e_22 , 5, 'g', LTS_STATE_e_160 , LTS_STATE_e_1196 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_160 , 5, 'u', LTS_STATE_e_1198 , LTS_STATE_e_1197 , 5, 'r', LTS_STATE_e_93 , LTS_STATE_e_1199 , 6, 'a', LTS_STATE_e_82 , LTS_STATE_e_1200 , 4, 'b', LTS_STATE_e_93 , LTS_STATE_e_1201 , 4, 'p', LTS_STATE_e_93 , LTS_STATE_e_82 , 6, 'b', LTS_STATE_e_30 , LTS_STATE_e_1202 , 5, 'k', LTS_STATE_e_1204 , LTS_STATE_e_1203 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_1205 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_1206 , 6, 'o', LTS_STATE_e_1207 , LTS_STATE_e_36 , 5, 's', LTS_STATE_e_36 , LTS_STATE_e_1208 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_1209 , 1, '0', LTS_STATE_e_22 , LTS_STATE_e_1210 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_36 , 4, 'z', LTS_STATE_e_1212 , LTS_STATE_e_1211 , 1, 'c', LTS_STATE_e_36 , LTS_STATE_e_1213 , 2, 's', LTS_STATE_e_36 , LTS_STATE_e_1214 , 3, 'j', LTS_STATE_e_93 , LTS_STATE_e_1215 , 3, 'r', LTS_STATE_e_1217 , LTS_STATE_e_1216 , 2, 'a', LTS_STATE_e_132 , LTS_STATE_e_1218 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_1219 , 1, 'n', LTS_STATE_e_82 , LTS_STATE_e_1220 , 2, 'h', LTS_STATE_e_1222 , LTS_STATE_e_1221 , 2, 'e', LTS_STATE_e_1224 , LTS_STATE_e_1223 , 6, 'e', LTS_STATE_e_1225 , LTS_STATE_e_22 , 5, 'e', LTS_STATE_e_1227 , LTS_STATE_e_1226 , 2, 'p', LTS_STATE_e_93 , LTS_STATE_e_1228 , 4, 'd', LTS_STATE_e_1230 , LTS_STATE_e_1229 , 2, 'i', LTS_STATE_e_82 , LTS_STATE_e_1231 , 4, 'v', LTS_STATE_e_132 , LTS_STATE_e_1232 , 4, 'd', LTS_STATE_e_30 , LTS_STATE_e_93 , 4, 'y', LTS_STATE_e_1234 , LTS_STATE_e_1233 , 4, 'b', LTS_STATE_e_93 , LTS_STATE_e_1235 , 6, 'm', LTS_STATE_e_93 , LTS_STATE_e_1236 , 5, 'i', LTS_STATE_e_30 , LTS_STATE_e_132 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_1237 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_1238 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_1239 , 2, 'l', LTS_STATE_e_132 , LTS_STATE_e_1240 , 2, 'e', LTS_STATE_e_160 , LTS_STATE_e_1241 , 4, 'y', LTS_STATE_e_36 , LTS_STATE_e_1242 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_1243 , 1, 'a', LTS_STATE_e_162 , LTS_STATE_e_1244 , 3, 'n', LTS_STATE_e_162 , LTS_STATE_e_30 , 3, 'c', LTS_STATE_e_36 , LTS_STATE_e_1245 , 3, 'o', LTS_STATE_e_1247 , LTS_STATE_e_1246 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_1248 , 2, 'i', LTS_STATE_e_1250 , LTS_STATE_e_1249 , 2, 'o', LTS_STATE_e_22 , LTS_STATE_e_30 , 1, '#', LTS_STATE_e_36 , LTS_STATE_e_1251 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_1252 , 5, 'o', LTS_STATE_e_160 , LTS_STATE_e_1253 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_1254 , 2, 'a', LTS_STATE_e_93 , LTS_STATE_e_639 , 6, 's', LTS_STATE_e_22 , LTS_STATE_e_1255 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1256 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_1257 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'i', LTS_STATE_e_93 , LTS_STATE_e_1258 , 3, 'v', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 'r', LTS_STATE_e_1260 , LTS_STATE_e_1259 , 5, 'n', LTS_STATE_e_1262 , LTS_STATE_e_1261 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_1263 , 1, 'l', LTS_STATE_e_160 , LTS_STATE_e_1264 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_1265 , 2, 'o', LTS_STATE_e_93 , LTS_STATE_e_1266 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_30 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_1267 , 6, 'r', LTS_STATE_e_1269 , LTS_STATE_e_1268 , 1, 'e', LTS_STATE_e_30 , LTS_STATE_e_1270 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_1058 , 3, 'c', LTS_STATE_e_816 , LTS_STATE_e_1271 , 1, 's', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'l', LTS_STATE_e_1273 , LTS_STATE_e_1272 , 3, 'r', LTS_STATE_e_1274 , LTS_STATE_e_93 , 2, 's', LTS_STATE_e_1276 , LTS_STATE_e_1275 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_132 , 1, 'f', LTS_STATE_e_93 , LTS_STATE_e_1277 , 2, 'l', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 's', LTS_STATE_e_93 , LTS_STATE_e_1278 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1279 , 2, 'l', LTS_STATE_e_160 , LTS_STATE_e_1280 , 1, 'r', LTS_STATE_e_1281 , LTS_STATE_e_93 , 4, 'g', LTS_STATE_e_1283 , LTS_STATE_e_1282 , 5, 'o', LTS_STATE_e_132 , LTS_STATE_e_1284 , 5, 'e', LTS_STATE_e_1286 , LTS_STATE_e_1285 , 5, 'e', LTS_STATE_e_22 , LTS_STATE_e_1287 , 5, 'p', LTS_STATE_e_160 , LTS_STATE_e_1288 , 5, 'c', LTS_STATE_e_1290 , LTS_STATE_e_1289 , 5, 'e', LTS_STATE_e_1292 , LTS_STATE_e_1291 , 3, 'm', LTS_STATE_e_1294 , LTS_STATE_e_1293 , 6, 'a', LTS_STATE_e_1296 , LTS_STATE_e_1295 , 4, 'q', LTS_STATE_e_1298 , LTS_STATE_e_1297 , 6, 'r', LTS_STATE_e_132 , LTS_STATE_e_22 , 255, 6, 0,0 , 0,0 , 4, 'n', LTS_STATE_e_162 , LTS_STATE_e_22 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_1299 , 4, 'n', LTS_STATE_e_1300 , LTS_STATE_e_22 , 3, 'c', LTS_STATE_e_160 , LTS_STATE_e_1301 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_1302 , 6, 'i', LTS_STATE_e_132 , LTS_STATE_e_1303 , 6, 'r', LTS_STATE_e_132 , LTS_STATE_e_976 , 5, 't', LTS_STATE_e_1305 , LTS_STATE_e_1304 , 4, 't', LTS_STATE_e_93 , LTS_STATE_e_1306 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1307 , 6, 'i', LTS_STATE_e_93 , LTS_STATE_e_82 , 6, 'd', LTS_STATE_e_132 , LTS_STATE_e_1308 , 5, 'a', LTS_STATE_e_22 , LTS_STATE_e_1309 , 5, 'o', LTS_STATE_e_1311 , LTS_STATE_e_1310 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_1312 , 6, 's', LTS_STATE_e_93 , LTS_STATE_e_1313 , 5, 'y', LTS_STATE_e_82 , LTS_STATE_e_1314 , 4, 'p', LTS_STATE_e_93 , LTS_STATE_e_1315 , 6, 'p', LTS_STATE_e_30 , LTS_STATE_e_1316 , 5, 'v', LTS_STATE_e_1318 , LTS_STATE_e_1317 , 3, 'p', LTS_STATE_e_30 , LTS_STATE_e_1319 , 5, 't', LTS_STATE_e_82 , LTS_STATE_e_30 , 3, 'v', LTS_STATE_e_883 , LTS_STATE_e_36 , 2, 'm', LTS_STATE_e_36 , LTS_STATE_e_22 , 5, 'v', LTS_STATE_e_36 , LTS_STATE_e_1320 , 6, 'n', LTS_STATE_e_1321 , LTS_STATE_e_22 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_1322 , 4, 'm', LTS_STATE_e_1324 , LTS_STATE_e_1323 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1325 , 2, 'a', LTS_STATE_e_30 , LTS_STATE_e_1326 , 3, 'r', LTS_STATE_e_1327 , LTS_STATE_e_36 , 3, 'r', LTS_STATE_e_1329 , LTS_STATE_e_1328 , 2, 'r', LTS_STATE_e_1331 , LTS_STATE_e_1330 , 2, 'r', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'o', LTS_STATE_e_132 , LTS_STATE_e_1332 , 1, 'k', LTS_STATE_e_93 , LTS_STATE_e_1333 , 1, 'i', LTS_STATE_e_82 , LTS_STATE_e_36 , 1, 'o', LTS_STATE_e_82 , LTS_STATE_e_1334 , 1, 's', LTS_STATE_e_82 , LTS_STATE_e_1335 , 2, 'n', LTS_STATE_e_1337 , LTS_STATE_e_1336 , 3, 'l', LTS_STATE_e_1339 , LTS_STATE_e_1338 , 3, 'n', LTS_STATE_e_1341 , LTS_STATE_e_1340 , 4, 'c', LTS_STATE_e_1343 , LTS_STATE_e_1342 , 2, 'p', LTS_STATE_e_93 , LTS_STATE_e_1344 , 2, 'c', LTS_STATE_e_1346 , LTS_STATE_e_1345 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_1347 , 6, 't', LTS_STATE_e_366 , LTS_STATE_e_1348 , 1, 's', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_1349 , 3, 'y', LTS_STATE_e_36 , LTS_STATE_e_1350 , 5, 'e', LTS_STATE_e_36 , LTS_STATE_e_162 , 4, 's', LTS_STATE_e_1183 , LTS_STATE_e_36 , 5, 'i', LTS_STATE_e_1352 , LTS_STATE_e_1351 , 3, 'u', LTS_STATE_e_1354 , LTS_STATE_e_1353 , 1, 's', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 'a', LTS_STATE_e_93 , LTS_STATE_e_160 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1355 , 2, 'r', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_30 , 2, 'c', LTS_STATE_e_30 , LTS_STATE_e_1356 , 1, 'u', LTS_STATE_e_162 , LTS_STATE_e_30 , 2, 'c', LTS_STATE_e_1358 , LTS_STATE_e_1357 , 6, 'p', LTS_STATE_e_22 , LTS_STATE_e_1359 , 5, 'e', LTS_STATE_e_93 , LTS_STATE_e_36 , 3, 'v', LTS_STATE_e_36 , LTS_STATE_e_1360 , 6, 'o', LTS_STATE_e_30 , LTS_STATE_e_1361 , 1, 'l', LTS_STATE_e_36 , LTS_STATE_e_1362 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1363 , 6, 's', LTS_STATE_e_93 , LTS_STATE_e_1364 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_1365 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_1366 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1367 , 1, 'k', LTS_STATE_e_93 , LTS_STATE_e_1368 , 3, 't', LTS_STATE_e_162 , LTS_STATE_e_93 , 1, 'u', LTS_STATE_e_93 , LTS_STATE_e_1369 , 5, 'k', LTS_STATE_e_1371 , LTS_STATE_e_1370 , 6, 'e', LTS_STATE_e_113 , LTS_STATE_e_22 , 6, 'c', LTS_STATE_e_22 , LTS_STATE_e_1372 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_1373 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_1374 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1375 , 2, 'h', LTS_STATE_e_160 , LTS_STATE_e_1376 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_1377 , 1, 'i', LTS_STATE_e_93 , LTS_STATE_e_82 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_1378 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_1379 , 4, 'm', LTS_STATE_e_93 , LTS_STATE_e_1380 , 3, 't', LTS_STATE_e_93 , LTS_STATE_e_1381 , 2, 't', LTS_STATE_e_93 , LTS_STATE_e_1382 , 6, 's', LTS_STATE_e_1384 , LTS_STATE_e_1383 , 3, 't', LTS_STATE_e_1385 , LTS_STATE_e_22 , 1, 'h', LTS_STATE_e_36 , LTS_STATE_e_1386 , 3, 'v', LTS_STATE_e_22 , LTS_STATE_e_1387 , 2, 'o', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'o', LTS_STATE_e_160 , LTS_STATE_e_1388 , 3, 'd', LTS_STATE_e_93 , LTS_STATE_e_22 , 5, 'a', LTS_STATE_e_935 , LTS_STATE_e_1389 , 5, 'g', LTS_STATE_e_22 , LTS_STATE_e_1390 , 5, 'l', LTS_STATE_e_132 , LTS_STATE_e_1391 , 5, 'i', LTS_STATE_e_1393 , LTS_STATE_e_1392 , 6, 'n', LTS_STATE_e_30 , LTS_STATE_e_22 , 5, 'o', LTS_STATE_e_26 , LTS_STATE_e_1394 , 5, 'u', LTS_STATE_e_22 , LTS_STATE_e_1395 , 5, 't', LTS_STATE_e_1397 , LTS_STATE_e_1396 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_160 , 5, 'o', LTS_STATE_e_1399 , LTS_STATE_e_1398 , 6, 'r', LTS_STATE_e_1401 , LTS_STATE_e_1400 , 4, 'l', LTS_STATE_e_1403 , LTS_STATE_e_1402 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_1404 , 6, 'u', LTS_STATE_e_30 , LTS_STATE_e_1405 , 4, 'd', LTS_STATE_e_30 , LTS_STATE_e_1406 , 6, 'c', LTS_STATE_e_93 , LTS_STATE_e_1407 , 3, 's', LTS_STATE_e_30 , LTS_STATE_e_1073 , 4, 'd', LTS_STATE_e_162 , LTS_STATE_e_1408 , 3, 'v', LTS_STATE_e_160 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_1409 , 6, 'o', LTS_STATE_e_1411 , LTS_STATE_e_1410 , 6, 'a', LTS_STATE_e_132 , LTS_STATE_e_160 , 4, 's', LTS_STATE_e_1413 , LTS_STATE_e_1412 , 6, 'a', LTS_STATE_e_82 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_93 , LTS_STATE_e_1414 , 5, 'u', LTS_STATE_e_22 , LTS_STATE_e_93 , 5, 'l', LTS_STATE_e_132 , LTS_STATE_e_1415 , 5, 'l', LTS_STATE_e_22 , LTS_STATE_e_1416 , 5, 'r', LTS_STATE_e_1418 , LTS_STATE_e_1417 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_1419 , 6, 'b', LTS_STATE_e_82 , LTS_STATE_e_1420 , 5, 'i', LTS_STATE_e_1422 , LTS_STATE_e_1421 , 6, 'u', LTS_STATE_e_1424 , LTS_STATE_e_1423 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1425 , 4, 'p', LTS_STATE_e_1427 , LTS_STATE_e_1426 , 2, 'c', LTS_STATE_e_1429 , LTS_STATE_e_1428 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_1430 , 3, 'v', LTS_STATE_e_36 , LTS_STATE_e_1431 , 3, 'b', LTS_STATE_e_22 , LTS_STATE_e_26 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_1432 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_1433 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'i', LTS_STATE_e_160 , LTS_STATE_e_1434 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_1435 , 2, 'f', LTS_STATE_e_93 , LTS_STATE_e_1436 , 2, 'l', LTS_STATE_e_36 , LTS_STATE_e_1437 , 2, 'a', LTS_STATE_e_36 , LTS_STATE_e_1438 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_1439 , 3, 'n', LTS_STATE_e_22 , LTS_STATE_e_160 , 2, 'i', LTS_STATE_e_132 , LTS_STATE_e_1440 , 2, 'u', LTS_STATE_e_1441 , LTS_STATE_e_93 , 1, 's', LTS_STATE_e_1442 , LTS_STATE_e_30 , 1, 'c', LTS_STATE_e_82 , LTS_STATE_e_30 , 4, 't', LTS_STATE_e_1444 , LTS_STATE_e_1443 , 5, 'r', LTS_STATE_e_93 , LTS_STATE_e_1445 , 5, 'e', LTS_STATE_e_1447 , LTS_STATE_e_1446 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'd', LTS_STATE_e_132 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_132 , LTS_STATE_e_160 , 4, 't', LTS_STATE_e_1449 , LTS_STATE_e_1448 , 2, 'o', LTS_STATE_e_22 , LTS_STATE_e_1450 , 4, 's', LTS_STATE_e_82 , LTS_STATE_e_93 , 2, 'e', LTS_STATE_e_1451 , LTS_STATE_e_36 , 3, 'r', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 'a', LTS_STATE_e_1453 , LTS_STATE_e_1452 , 1, 'n', LTS_STATE_e_36 , LTS_STATE_e_1454 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_1455 , 4, 'x', LTS_STATE_e_1457 , LTS_STATE_e_1456 , 4, 'c', LTS_STATE_e_1459 , LTS_STATE_e_1458 , 6, 'e', LTS_STATE_e_160 , LTS_STATE_e_1460 , 5, 'z', LTS_STATE_e_1462 , LTS_STATE_e_1461 , 5, 'a', LTS_STATE_e_22 , LTS_STATE_e_36 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_1463 , 3, 'r', LTS_STATE_e_82 , LTS_STATE_e_30 , 6, 't', LTS_STATE_e_36 , LTS_STATE_e_1464 , 1, 'n', LTS_STATE_e_36 , LTS_STATE_e_82 , 2, 's', LTS_STATE_e_1324 , LTS_STATE_e_1465 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1466 , 1, 'f', LTS_STATE_e_36 , LTS_STATE_e_1467 , 6, 'n', LTS_STATE_e_36 , LTS_STATE_e_1468 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_1469 , 5, 'i', LTS_STATE_e_160 , LTS_STATE_e_1470 , 2, 'n', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'a', LTS_STATE_e_1471 , LTS_STATE_e_22 , 3, 'v', LTS_STATE_e_1441 , LTS_STATE_e_22 , 2, 'o', LTS_STATE_e_93 , LTS_STATE_e_1472 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_1473 , 5, 'g', LTS_STATE_e_1475 , LTS_STATE_e_1474 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_1476 , 6, 'e', LTS_STATE_e_30 , LTS_STATE_e_1477 , 3, 'l', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 'n', LTS_STATE_e_93 , LTS_STATE_e_1478 , 2, 'a', LTS_STATE_e_1339 , LTS_STATE_e_1479 , 2, 'a', LTS_STATE_e_1480 , LTS_STATE_e_22 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_1481 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_82 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_1482 , 4, 't', LTS_STATE_e_1484 , LTS_STATE_e_1483 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'p', LTS_STATE_e_22 , LTS_STATE_e_1485 , 1, 't', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 't', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'e', LTS_STATE_e_160 , LTS_STATE_e_22 , 6, 'r', LTS_STATE_e_1487 , LTS_STATE_e_1486 , 1, 'a', LTS_STATE_e_1489 , LTS_STATE_e_1488 , 2, 'p', LTS_STATE_e_160 , LTS_STATE_e_1490 , 4, 's', LTS_STATE_e_1492 , LTS_STATE_e_1491 , 5, 'l', LTS_STATE_e_22 , LTS_STATE_e_1493 , 5, 'c', LTS_STATE_e_132 , LTS_STATE_e_22 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1494 , 6, 'l', LTS_STATE_e_30 , LTS_STATE_e_22 , 6, 'o', LTS_STATE_e_26 , LTS_STATE_e_1495 , 5, 'i', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'd', LTS_STATE_e_1497 , LTS_STATE_e_1496 , 6, 'a', LTS_STATE_e_160 , LTS_STATE_e_1498 , 5, 'r', LTS_STATE_e_1500 , LTS_STATE_e_1499 , 4, 'g', LTS_STATE_e_912 , LTS_STATE_e_1501 , 3, 't', LTS_STATE_e_1503 , LTS_STATE_e_1502 , 3, 'g', LTS_STATE_e_22 , LTS_STATE_e_1504 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_1505 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1506 , 4, 'g', LTS_STATE_e_22 , LTS_STATE_e_1507 , 3, 'b', LTS_STATE_e_1509 , LTS_STATE_e_1508 , 4, 'n', LTS_STATE_e_30 , LTS_STATE_e_22 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_1510 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_1511 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_160 , 6, 'r', LTS_STATE_e_1411 , LTS_STATE_e_1512 , 5, 't', LTS_STATE_e_132 , LTS_STATE_e_22 , 5, 'u', LTS_STATE_e_1514 , LTS_STATE_e_1513 , 5, 'e', LTS_STATE_e_160 , LTS_STATE_e_1515 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_22 , 5, 'r', LTS_STATE_e_132 , LTS_STATE_e_1516 , 5, 'o', LTS_STATE_e_22 , LTS_STATE_e_1517 , 4, 'd', LTS_STATE_e_1519 , LTS_STATE_e_1518 , 6, 'o', LTS_STATE_e_1521 , LTS_STATE_e_1520 , 4, 's', LTS_STATE_e_1523 , LTS_STATE_e_1522 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_1524 , 5, 'l', LTS_STATE_e_93 , LTS_STATE_e_1525 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_82 , 6, 'v', LTS_STATE_e_132 , LTS_STATE_e_1526 , 5, 'o', LTS_STATE_e_132 , LTS_STATE_e_93 , 6, 'm', LTS_STATE_e_93 , LTS_STATE_e_1527 , 6, 'c', LTS_STATE_e_93 , LTS_STATE_e_1528 , 6, 'c', LTS_STATE_e_30 , LTS_STATE_e_82 , 2, 'r', LTS_STATE_e_1530 , LTS_STATE_e_1529 , 5, 't', LTS_STATE_e_82 , LTS_STATE_e_1531 , 3, 'n', LTS_STATE_e_30 , LTS_STATE_e_1532 , 3, 'h', LTS_STATE_e_36 , LTS_STATE_e_1533 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_1534 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_1535 , 3, 'u', LTS_STATE_e_22 , LTS_STATE_e_160 , 3, 'n', LTS_STATE_e_82 , LTS_STATE_e_1536 , 2, 'd', LTS_STATE_e_93 , LTS_STATE_e_36 , 1, 'i', LTS_STATE_e_36 , LTS_STATE_e_1537 , 2, 'd', LTS_STATE_e_162 , LTS_STATE_e_36 , 1, 'i', LTS_STATE_e_22 , LTS_STATE_e_1538 , 2, 'u', LTS_STATE_e_132 , LTS_STATE_e_1539 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_22 , 2, 'l', LTS_STATE_e_30 , LTS_STATE_e_82 , 4, 'd', LTS_STATE_e_1541 , LTS_STATE_e_1540 , 5, 'e', LTS_STATE_e_1543 , LTS_STATE_e_1542 , 3, 't', LTS_STATE_e_1545 , LTS_STATE_e_1544 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_1546 , 4, 'v', LTS_STATE_e_132 , LTS_STATE_e_1547 , 3, 't', LTS_STATE_e_1549 , LTS_STATE_e_1548 , 5, 'a', LTS_STATE_e_160 , LTS_STATE_e_36 , 5, 'o', LTS_STATE_e_1551 , LTS_STATE_e_1550 , 5, 'a', LTS_STATE_e_36 , LTS_STATE_e_93 , 6, 'l', LTS_STATE_e_1553 , LTS_STATE_e_1552 , 3, 't', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 'm', LTS_STATE_e_22 , LTS_STATE_e_1554 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_1555 , 5, 'e', LTS_STATE_e_1557 , LTS_STATE_e_1556 , 3, 'n', LTS_STATE_e_132 , LTS_STATE_e_1414 , 3, 'r', LTS_STATE_e_1558 , LTS_STATE_e_22 , 5, 'e', LTS_STATE_e_93 , LTS_STATE_e_1559 , 6, 'c', LTS_STATE_e_93 , LTS_STATE_e_1560 , 4, 'd', LTS_STATE_e_1562 , LTS_STATE_e_1561 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_160 , 2, 'h', LTS_STATE_e_22 , LTS_STATE_e_1563 , 5, 'n', LTS_STATE_e_82 , LTS_STATE_e_1564 , 6, 'h', LTS_STATE_e_22 , LTS_STATE_e_1565 , 5, 'a', LTS_STATE_e_1566 , LTS_STATE_e_93 , 6, 'c', LTS_STATE_e_1568 , LTS_STATE_e_1567 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_36 , 1, 'i', LTS_STATE_e_22 , LTS_STATE_e_1569 , 1, 'e', LTS_STATE_e_160 , LTS_STATE_e_93 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1570 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_162 , 5, 'u', LTS_STATE_e_1572 , LTS_STATE_e_1571 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_1573 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_1574 , 6, 'a', LTS_STATE_e_30 , LTS_STATE_e_1575 , 2, 'i', LTS_STATE_e_93 , LTS_STATE_e_1576 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_1577 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_1324 , 3, 'v', LTS_STATE_e_93 , LTS_STATE_e_36 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_1058 , 4, 'd', LTS_STATE_e_1568 , LTS_STATE_e_981 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'n', LTS_STATE_e_93 , LTS_STATE_e_1578 , 1, 'c', LTS_STATE_e_160 , LTS_STATE_e_1579 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_1580 , 1, 'l', LTS_STATE_e_1582 , LTS_STATE_e_1581 , 2, 'c', LTS_STATE_e_22 , LTS_STATE_e_1583 , 1, 'e', LTS_STATE_e_160 , LTS_STATE_e_1584 , 4, 'l', LTS_STATE_e_1586 , LTS_STATE_e_1585 , 6, 'a', LTS_STATE_e_1588 , LTS_STATE_e_1587 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_1589 , 5, 'a', LTS_STATE_e_132 , LTS_STATE_e_1590 , 6, 's', LTS_STATE_e_22 , LTS_STATE_e_1591 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1592 , 6, 'a', LTS_STATE_e_160 , LTS_STATE_e_1593 , 6, 'h', LTS_STATE_e_160 , LTS_STATE_e_1594 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_1595 , 4, 't', LTS_STATE_e_1597 , LTS_STATE_e_1596 , 4, 'c', LTS_STATE_e_1599 , LTS_STATE_e_1598 , 4, 'v', LTS_STATE_e_1601 , LTS_STATE_e_1600 , 4, 'l', LTS_STATE_e_22 , LTS_STATE_e_1602 , 3, 'p', LTS_STATE_e_1604 , LTS_STATE_e_1603 , 4, 'c', LTS_STATE_e_132 , LTS_STATE_e_1605 , 3, 'v', LTS_STATE_e_160 , LTS_STATE_e_1606 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1607 , 4, 'v', LTS_STATE_e_22 , LTS_STATE_e_1608 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1609 , 3, 'l', LTS_STATE_e_160 , LTS_STATE_e_1610 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_162 , 5, 't', LTS_STATE_e_132 , LTS_STATE_e_1611 , 5, 'a', LTS_STATE_e_1613 , LTS_STATE_e_1612 , 4, 'b', LTS_STATE_e_22 , LTS_STATE_e_93 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1614 , 5, 'a', LTS_STATE_e_132 , LTS_STATE_e_1615 , 5, 'e', LTS_STATE_e_22 , LTS_STATE_e_1616 , 4, 'm', LTS_STATE_e_1519 , LTS_STATE_e_1617 , 5, 'i', LTS_STATE_e_1618 , LTS_STATE_e_22 , 4, 'p', LTS_STATE_e_1619 , LTS_STATE_e_82 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_1620 , 4, 'b', LTS_STATE_e_82 , LTS_STATE_e_1621 , 6, 'u', LTS_STATE_e_82 , LTS_STATE_e_1622 , 6, 'm', LTS_STATE_e_93 , LTS_STATE_e_1623 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_1624 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_1625 , 4, 'l', LTS_STATE_e_1627 , LTS_STATE_e_1626 , 4, 'c', LTS_STATE_e_82 , LTS_STATE_e_1628 , 2, 'l', LTS_STATE_e_36 , LTS_STATE_e_1629 , 5, 'l', LTS_STATE_e_30 , LTS_STATE_e_82 , 1, 'a', LTS_STATE_e_36 , LTS_STATE_e_1630 , 6, '#', LTS_STATE_e_36 , LTS_STATE_e_30 , 3, 'g', LTS_STATE_e_36 , LTS_STATE_e_1631 , 6, 'c', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_1632 , 2, 'r', LTS_STATE_e_30 , LTS_STATE_e_1633 , 2, 'n', LTS_STATE_e_36 , LTS_STATE_e_1634 , 2, 'm', LTS_STATE_e_93 , LTS_STATE_e_1635 , 1, 'r', LTS_STATE_e_132 , LTS_STATE_e_1636 , 5, 'c', LTS_STATE_e_22 , LTS_STATE_e_1637 , 5, 'g', LTS_STATE_e_1639 , LTS_STATE_e_1638 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_1640 , 3, 'm', LTS_STATE_e_93 , LTS_STATE_e_1641 , 4, 'b', LTS_STATE_e_912 , LTS_STATE_e_1642 , 5, 'p', LTS_STATE_e_22 , LTS_STATE_e_1643 , 3, 'n', LTS_STATE_e_1645 , LTS_STATE_e_1644 , 6, 'r', LTS_STATE_e_82 , LTS_STATE_e_1646 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1647 , 5, 'a', LTS_STATE_e_160 , LTS_STATE_e_93 , 5, 'h', LTS_STATE_e_93 , LTS_STATE_e_36 , 1, 'c', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'f', LTS_STATE_e_1649 , LTS_STATE_e_1648 , 2, 'e', LTS_STATE_e_22 , LTS_STATE_e_912 , 3, 'p', LTS_STATE_e_30 , LTS_STATE_e_1650 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_1651 , 2, 'a', LTS_STATE_e_1653 , LTS_STATE_e_1652 , 4, 's', LTS_STATE_e_36 , LTS_STATE_e_1654 , 6, 'r', LTS_STATE_e_1656 , LTS_STATE_e_1655 , 6, 'n', LTS_STATE_e_30 , LTS_STATE_e_1657 , 4, 's', LTS_STATE_e_93 , LTS_STATE_e_1658 , 4, 'j', LTS_STATE_e_162 , LTS_STATE_e_1659 , 5, 'i', LTS_STATE_e_22 , LTS_STATE_e_1660 , 3, 'n', LTS_STATE_e_22 , LTS_STATE_e_1661 , 1, 'g', LTS_STATE_e_36 , LTS_STATE_e_82 , 6, 'd', LTS_STATE_e_93 , LTS_STATE_e_1662 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_93 , 1, '#', LTS_STATE_e_1664 , LTS_STATE_e_1663 , 3, 'r', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_1665 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_1666 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1667 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_1365 , 1, 'e', LTS_STATE_e_132 , LTS_STATE_e_1668 , 2, 'o', LTS_STATE_e_22 , LTS_STATE_e_1665 , 2, 'u', LTS_STATE_e_93 , LTS_STATE_e_1669 , 1, 'i', LTS_STATE_e_93 , LTS_STATE_e_22 , 2, 'u', LTS_STATE_e_160 , LTS_STATE_e_1670 , 2, 'g', LTS_STATE_e_22 , LTS_STATE_e_1671 , 2, 'l', LTS_STATE_e_36 , LTS_STATE_e_1672 , 2, 'c', LTS_STATE_e_93 , LTS_STATE_e_1673 , 2, 'm', LTS_STATE_e_160 , LTS_STATE_e_1674 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_160 , 6, 'i', LTS_STATE_e_1217 , LTS_STATE_e_1675 , 3, 'h', LTS_STATE_e_160 , LTS_STATE_e_1676 , 5, 'f', LTS_STATE_e_1675 , LTS_STATE_e_1677 , 5, 'i', LTS_STATE_e_1679 , LTS_STATE_e_1678 , 5, 'c', LTS_STATE_e_1681 , LTS_STATE_e_1680 , 5, 't', LTS_STATE_e_93 , LTS_STATE_e_1682 , 5, 'e', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'l', LTS_STATE_e_132 , LTS_STATE_e_22 , 6, 'g', LTS_STATE_e_22 , LTS_STATE_e_1683 , 5, 'a', LTS_STATE_e_160 , LTS_STATE_e_1684 , 6, 'o', LTS_STATE_e_160 , LTS_STATE_e_22 , 6, 'i', LTS_STATE_e_160 , LTS_STATE_e_1685 , 6, 'a', LTS_STATE_e_1687 , LTS_STATE_e_1686 , 4, 'h', LTS_STATE_e_1689 , LTS_STATE_e_1688 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_1690 , 3, 'h', LTS_STATE_e_1692 , LTS_STATE_e_1691 , 6, 'm', LTS_STATE_e_132 , LTS_STATE_e_22 , 4, 'g', LTS_STATE_e_1694 , LTS_STATE_e_1693 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1695 , 4, 'n', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'd', LTS_STATE_e_22 , LTS_STATE_e_1696 , 4, 't', LTS_STATE_e_30 , LTS_STATE_e_22 , 6, 'l', LTS_STATE_e_1698 , LTS_STATE_e_1697 , 6, 'g', LTS_STATE_e_93 , LTS_STATE_e_1699 , 6, 'm', LTS_STATE_e_22 , LTS_STATE_e_1700 , 4, 't', LTS_STATE_e_1702 , LTS_STATE_e_1701 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1703 , 6, 's', LTS_STATE_e_93 , LTS_STATE_e_1704 , 6, 'h', LTS_STATE_e_132 , LTS_STATE_e_1705 , 5, 'e', LTS_STATE_e_1707 , LTS_STATE_e_1706 , 6, 't', LTS_STATE_e_93 , LTS_STATE_e_1708 , 5, 'i', LTS_STATE_e_1709 , LTS_STATE_e_1414 , 6, 'n', LTS_STATE_e_82 , LTS_STATE_e_22 , 5, 'b', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'i', LTS_STATE_e_1711 , LTS_STATE_e_1710 , 6, 's', LTS_STATE_e_82 , LTS_STATE_e_22 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_82 , 4, 'p', LTS_STATE_e_82 , LTS_STATE_e_22 , 4, 'p', LTS_STATE_e_93 , LTS_STATE_e_1712 , 6, 'l', LTS_STATE_e_82 , LTS_STATE_e_93 , 6, 'i', LTS_STATE_e_82 , LTS_STATE_e_1713 , 5, 'u', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'i', LTS_STATE_e_1714 , LTS_STATE_e_22 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_1715 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 't', LTS_STATE_e_30 , LTS_STATE_e_82 , 3, 'n', LTS_STATE_e_36 , LTS_STATE_e_1716 , 6, 's', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'b', LTS_STATE_e_36 , LTS_STATE_e_1717 , 4, 'c', LTS_STATE_e_1719 , LTS_STATE_e_1718 , 1, 'n', LTS_STATE_e_82 , LTS_STATE_e_1720 , 2, 'a', LTS_STATE_e_1721 , LTS_STATE_e_36 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_1722 , 3, 'b', LTS_STATE_e_132 , LTS_STATE_e_160 , 6, 't', LTS_STATE_e_1724 , LTS_STATE_e_1723 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_1725 , 1, 'o', LTS_STATE_e_132 , LTS_STATE_e_22 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_1726 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_1727 , 3, 'd', LTS_STATE_e_1729 , LTS_STATE_e_1728 , 1, 'o', LTS_STATE_e_160 , LTS_STATE_e_93 , 1, 'r', LTS_STATE_e_1731 , LTS_STATE_e_1730 , 6, 't', LTS_STATE_e_132 , LTS_STATE_e_1732 , 6, 'd', LTS_STATE_e_30 , LTS_STATE_e_93 , 4, 's', LTS_STATE_e_1734 , LTS_STATE_e_1733 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_1735 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_1736 , 3, 'c', LTS_STATE_e_30 , LTS_STATE_e_93 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_30 , 2, 'i', LTS_STATE_e_1738 , LTS_STATE_e_1737 , 5, 'o', LTS_STATE_e_36 , LTS_STATE_e_1739 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_1740 , 6, 'n', LTS_STATE_e_1742 , LTS_STATE_e_1741 , 4, 'p', LTS_STATE_e_82 , LTS_STATE_e_1743 , 6, 'u', LTS_STATE_e_132 , LTS_STATE_e_82 , 4, 'c', LTS_STATE_e_93 , LTS_STATE_e_1744 , 5, 'a', LTS_STATE_e_1746 , LTS_STATE_e_1745 , 5, 'o', LTS_STATE_e_162 , LTS_STATE_e_1747 , 2, 'c', LTS_STATE_e_22 , LTS_STATE_e_132 , 5, 'e', LTS_STATE_e_1749 , LTS_STATE_e_1748 , 6, 'n', LTS_STATE_e_1751 , LTS_STATE_e_1750 , 3, 'm', LTS_STATE_e_160 , LTS_STATE_e_1752 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_1753 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_1754 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_1755 , 2, 'l', LTS_STATE_e_93 , LTS_STATE_e_1756 , 5, 'h', LTS_STATE_e_93 , LTS_STATE_e_22 , 2, 'd', LTS_STATE_e_22 , LTS_STATE_e_93 , 2, 'q', LTS_STATE_e_22 , LTS_STATE_e_1757 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 'a', LTS_STATE_e_1759 , LTS_STATE_e_1758 , 6, 'e', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'u', LTS_STATE_e_93 , LTS_STATE_e_1760 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_1761 , 5, 'u', LTS_STATE_e_93 , LTS_STATE_e_1762 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_1763 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_1764 , 6, 'h', LTS_STATE_e_22 , LTS_STATE_e_1765 , 5, 'c', LTS_STATE_e_22 , LTS_STATE_e_1766 , 5, 'm', LTS_STATE_e_22 , LTS_STATE_e_1767 , 6, 'o', LTS_STATE_e_1769 , LTS_STATE_e_1768 , 6, 'r', LTS_STATE_e_160 , LTS_STATE_e_1593 , 4, 'n', LTS_STATE_e_1771 , LTS_STATE_e_1770 , 3, 's', LTS_STATE_e_1772 , LTS_STATE_e_22 , 4, 'd', LTS_STATE_e_1774 , LTS_STATE_e_1773 , 6, 'a', LTS_STATE_e_162 , LTS_STATE_e_22 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_1775 , 6, 's', LTS_STATE_e_1777 , LTS_STATE_e_1776 , 6, 'r', LTS_STATE_e_22 , LTS_STATE_e_1778 , 6, 'o', LTS_STATE_e_30 , LTS_STATE_e_1779 , 3, 'b', LTS_STATE_e_132 , LTS_STATE_e_22 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_1780 , 3, 'f', LTS_STATE_e_30 , LTS_STATE_e_1781 , 4, 'p', LTS_STATE_e_22 , LTS_STATE_e_1782 , 4, 'g', LTS_STATE_e_30 , LTS_STATE_e_1783 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_683 , 6, 'c', LTS_STATE_e_22 , LTS_STATE_e_1784 , 4, 'g', LTS_STATE_e_1702 , LTS_STATE_e_1785 , 6, 't', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 's', LTS_STATE_e_22 , LTS_STATE_e_1786 , 6, 'd', LTS_STATE_e_93 , LTS_STATE_e_22 , 5, 'c', LTS_STATE_e_132 , LTS_STATE_e_1787 , 5, 'o', LTS_STATE_e_1789 , LTS_STATE_e_1788 , 4, 't', LTS_STATE_e_93 , LTS_STATE_e_1790 , 4, 't', LTS_STATE_e_93 , LTS_STATE_e_1791 , 6, 'g', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_1793 , LTS_STATE_e_1792 , 4, 's', LTS_STATE_e_1795 , LTS_STATE_e_1794 , 4, 'm', LTS_STATE_e_93 , LTS_STATE_e_1796 , 4, 'p', LTS_STATE_e_1798 , LTS_STATE_e_1797 , 5, 't', LTS_STATE_e_22 , LTS_STATE_e_132 , 6, 'p', LTS_STATE_e_30 , LTS_STATE_e_1799 , 1, 'r', LTS_STATE_e_30 , LTS_STATE_e_1800 , 3, 'f', LTS_STATE_e_36 , LTS_STATE_e_1801 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_1802 , 2, 'a', LTS_STATE_e_132 , LTS_STATE_e_1462 , 2, 'o', LTS_STATE_e_82 , LTS_STATE_e_1803 , 3, 'l', LTS_STATE_e_1804 , LTS_STATE_e_36 , 2, 'i', LTS_STATE_e_601 , LTS_STATE_e_1805 , 4, 'g', LTS_STATE_e_1807 , LTS_STATE_e_1806 , 5, 'h', LTS_STATE_e_1809 , LTS_STATE_e_1808 , 1, 's', LTS_STATE_e_22 , LTS_STATE_e_1810 , 6, 'e', LTS_STATE_e_1812 , LTS_STATE_e_1811 , 2, 'p', LTS_STATE_e_1814 , LTS_STATE_e_1813 , 1, 'u', LTS_STATE_e_1816 , LTS_STATE_e_1815 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_1339 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_1817 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_1818 , 5, 'r', LTS_STATE_e_93 , LTS_STATE_e_1414 , 4, 'b', LTS_STATE_e_36 , LTS_STATE_e_1819 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_93 , 3, 'r', LTS_STATE_e_1821 , LTS_STATE_e_1820 , 6, 'n', LTS_STATE_e_36 , LTS_STATE_e_1734 , 4, 'q', LTS_STATE_e_1823 , LTS_STATE_e_1822 , 3, 'n', LTS_STATE_e_1824 , LTS_STATE_e_1751 , 3, 'r', LTS_STATE_e_160 , LTS_STATE_e_1825 , 6, 'r', LTS_STATE_e_1827 , LTS_STATE_e_1826 , 4, 'p', LTS_STATE_e_1829 , LTS_STATE_e_1828 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_82 , 4, 'f', LTS_STATE_e_22 , LTS_STATE_e_1830 , 4, 'd', LTS_STATE_e_30 , LTS_STATE_e_1630 , 5, 'o', LTS_STATE_e_1832 , LTS_STATE_e_1831 , 4, 'm', LTS_STATE_e_1834 , LTS_STATE_e_1833 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_1835 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1836 , 3, 'c', LTS_STATE_e_22 , LTS_STATE_e_1837 , 2, 'a', LTS_STATE_e_93 , LTS_STATE_e_217 , 3, 'c', LTS_STATE_e_36 , LTS_STATE_e_93 , 3, 'r', LTS_STATE_e_93 , LTS_STATE_e_1838 , 2, 'n', LTS_STATE_e_93 , LTS_STATE_e_1839 , 5, 'h', LTS_STATE_e_93 , LTS_STATE_e_1840 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_1841 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_1842 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_1843 , 6, 'a', LTS_STATE_e_1845 , LTS_STATE_e_1844 , 6, 'i', LTS_STATE_e_1847 , LTS_STATE_e_1846 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_160 , 5, 'h', LTS_STATE_e_22 , LTS_STATE_e_1848 , 5, 'o', LTS_STATE_e_93 , LTS_STATE_e_1849 , 6, 'm', LTS_STATE_e_93 , LTS_STATE_e_1850 , 5, 's', LTS_STATE_e_22 , LTS_STATE_e_1851 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_160 , 5, 'p', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'i', LTS_STATE_e_1853 , LTS_STATE_e_1852 , 5, 'l', LTS_STATE_e_1855 , LTS_STATE_e_1854 , 5, 'f', LTS_STATE_e_160 , LTS_STATE_e_1856 , 6, 'u', LTS_STATE_e_1857 , LTS_STATE_e_22 , 3, 'm', LTS_STATE_e_1859 , LTS_STATE_e_1858 , 5, 's', LTS_STATE_e_160 , LTS_STATE_e_22 , 4, 'n', LTS_STATE_e_22 , LTS_STATE_e_1860 , 3, 'p', LTS_STATE_e_1183 , LTS_STATE_e_1339 , 6, 'u', LTS_STATE_e_160 , LTS_STATE_e_22 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_1861 , 4, 'l', LTS_STATE_e_160 , LTS_STATE_e_30 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'b', LTS_STATE_e_1863 , LTS_STATE_e_1862 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_132 , 4, 'v', LTS_STATE_e_22 , LTS_STATE_e_1864 , 6, 'v', LTS_STATE_e_1866 , LTS_STATE_e_1865 , 4, 'f', LTS_STATE_e_93 , LTS_STATE_e_1867 , 6, 'p', LTS_STATE_e_22 , LTS_STATE_e_1868 , 3, 'v', LTS_STATE_e_22 , LTS_STATE_e_1869 , 6, 't', LTS_STATE_e_93 , LTS_STATE_e_1870 , 6, 'n', LTS_STATE_e_132 , LTS_STATE_e_22 , 4, 'n', LTS_STATE_e_22 , LTS_STATE_e_1871 , 4, 'n', LTS_STATE_e_93 , LTS_STATE_e_1872 , 4, 'n', LTS_STATE_e_26 , LTS_STATE_e_1514 , 4, 'b', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'o', LTS_STATE_e_82 , LTS_STATE_e_1873 , 6, 'o', LTS_STATE_e_93 , LTS_STATE_e_1874 , 4, 'w', LTS_STATE_e_82 , LTS_STATE_e_1875 , 6, 's', LTS_STATE_e_93 , LTS_STATE_e_1876 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_82 , 4, 's', LTS_STATE_e_728 , LTS_STATE_e_93 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_82 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_1877 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_1878 , 5, 'n', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 'p', LTS_STATE_e_22 , LTS_STATE_e_1879 , 3, 'h', LTS_STATE_e_30 , LTS_STATE_e_82 , 1, 'r', LTS_STATE_e_160 , LTS_STATE_e_36 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_1880 , 4, 'v', LTS_STATE_e_1882 , LTS_STATE_e_1881 , 5, 'a', LTS_STATE_e_1884 , LTS_STATE_e_1883 , 3, 's', LTS_STATE_e_1886 , LTS_STATE_e_1885 , 2, 'b', LTS_STATE_e_132 , LTS_STATE_e_1887 , 6, 'w', LTS_STATE_e_36 , LTS_STATE_e_1888 , 1, 'e', LTS_STATE_e_1890 , LTS_STATE_e_1889 , 5, 'h', LTS_STATE_e_22 , LTS_STATE_e_1891 , 6, 'r', LTS_STATE_e_1893 , LTS_STATE_e_1892 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_93 , 4, 'f', LTS_STATE_e_36 , LTS_STATE_e_1894 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_1895 , 1, 'v', LTS_STATE_e_132 , LTS_STATE_e_1896 , 5, 'o', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'h', LTS_STATE_e_36 , LTS_STATE_e_1897 , 6, 'n', LTS_STATE_e_1899 , LTS_STATE_e_1898 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_1365 , 5, 'a', LTS_STATE_e_1901 , LTS_STATE_e_1900 , 2, 'f', LTS_STATE_e_30 , LTS_STATE_e_132 , 4, 'f', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 'l', LTS_STATE_e_1183 , LTS_STATE_e_1902 , 4, 'v', LTS_STATE_e_1904 , LTS_STATE_e_1903 , 2, 'f', LTS_STATE_e_22 , LTS_STATE_e_1905 , 6, 'd', LTS_STATE_e_1907 , LTS_STATE_e_1906 , 5, 'a', LTS_STATE_e_82 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_93 , LTS_STATE_e_82 , 5, 'i', LTS_STATE_e_22 , LTS_STATE_e_1908 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_1909 , 4, 'b', LTS_STATE_e_30 , LTS_STATE_e_1910 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_1911 , 2, 'a', LTS_STATE_e_162 , LTS_STATE_e_1909 , 5, 'k', LTS_STATE_e_22 , LTS_STATE_e_1912 , 2, 'r', LTS_STATE_e_22 , LTS_STATE_e_1913 , 6, 'n', LTS_STATE_e_1914 , LTS_STATE_e_36 , 2, 'p', LTS_STATE_e_93 , LTS_STATE_e_1915 , 2, 'o', LTS_STATE_e_93 , LTS_STATE_e_1916 , 6, 'a', LTS_STATE_e_162 , LTS_STATE_e_93 , 6, 's', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'd', LTS_STATE_e_93 , LTS_STATE_e_1917 , 2, 'o', LTS_STATE_e_1918 , LTS_STATE_e_22 , 3, 't', LTS_STATE_e_93 , LTS_STATE_e_1919 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_1920 , 1, 'v', LTS_STATE_e_93 , LTS_STATE_e_160 , 4, 'd', LTS_STATE_e_22 , LTS_STATE_e_1921 , 5, 'l', LTS_STATE_e_22 , LTS_STATE_e_1922 , 6, 'z', LTS_STATE_e_26 , LTS_STATE_e_1923 , 5, 't', LTS_STATE_e_22 , LTS_STATE_e_1924 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_1925 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_160 , 5, 'r', LTS_STATE_e_160 , LTS_STATE_e_1926 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_160 , 5, 'j', LTS_STATE_e_160 , LTS_STATE_e_1927 , 3, 's', LTS_STATE_e_132 , LTS_STATE_e_22 , 3, 'z', LTS_STATE_e_22 , LTS_STATE_e_1928 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_1929 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_1930 , 4, 'm', LTS_STATE_e_1932 , LTS_STATE_e_1931 , 4, 'h', LTS_STATE_e_30 , LTS_STATE_e_1933 , 4, 'n', LTS_STATE_e_22 , LTS_STATE_e_1934 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_1935 , 4, 'm', LTS_STATE_e_1937 , LTS_STATE_e_1936 , 4, 'h', LTS_STATE_e_93 , LTS_STATE_e_1183 , 4, 'v', LTS_STATE_e_1183 , LTS_STATE_e_93 , 4, 't', LTS_STATE_e_1939 , LTS_STATE_e_1938 , 6, 'l', LTS_STATE_e_160 , LTS_STATE_e_1940 , 4, 'n', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'd', LTS_STATE_e_22 , LTS_STATE_e_1941 , 6, 'n', LTS_STATE_e_1942 , LTS_STATE_e_1384 , 5, 'l', LTS_STATE_e_1944 , LTS_STATE_e_1943 , 6, 'i', LTS_STATE_e_1946 , LTS_STATE_e_1945 , 4, 't', LTS_STATE_e_1948 , LTS_STATE_e_1947 , 6, 'g', LTS_STATE_e_22 , LTS_STATE_e_93 , 6, 'n', LTS_STATE_e_1949 , LTS_STATE_e_82 , 1, 'o', LTS_STATE_e_36 , LTS_STATE_e_1950 , 1, 'n', LTS_STATE_e_1952 , LTS_STATE_e_1951 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_1953 , 4, 'm', LTS_STATE_e_1955 , LTS_STATE_e_1954 , 5, 'a', LTS_STATE_e_1183 , LTS_STATE_e_1956 , 3, 'r', LTS_STATE_e_1958 , LTS_STATE_e_1957 , 6, 'l', LTS_STATE_e_30 , LTS_STATE_e_132 , 2, 'g', LTS_STATE_e_93 , LTS_STATE_e_1959 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_132 , 2, 'k', LTS_STATE_e_132 , LTS_STATE_e_22 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_1960 , 5, 'c', LTS_STATE_e_22 , LTS_STATE_e_1961 , 5, 'r', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 't', LTS_STATE_e_160 , LTS_STATE_e_36 , 6, 'd', LTS_STATE_e_93 , LTS_STATE_e_36 , 2, 'a', LTS_STATE_e_93 , LTS_STATE_e_36 , 5, 'u', LTS_STATE_e_93 , LTS_STATE_e_1962 , 4, 'c', LTS_STATE_e_22 , LTS_STATE_e_82 , 4, 'g', LTS_STATE_e_1964 , LTS_STATE_e_1963 , 2, 'c', LTS_STATE_e_93 , LTS_STATE_e_1965 , 4, 's', LTS_STATE_e_1967 , LTS_STATE_e_1966 , 4, 't', LTS_STATE_e_93 , LTS_STATE_e_1968 , 2, 'o', LTS_STATE_e_1970 , LTS_STATE_e_1969 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_1971 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_1972 , 4, 'd', LTS_STATE_e_1286 , LTS_STATE_e_22 , 6, 'n', LTS_STATE_e_1973 , LTS_STATE_e_30 , 4, 'v', LTS_STATE_e_22 , LTS_STATE_e_1974 , 5, 'e', LTS_STATE_e_30 , LTS_STATE_e_1975 , 4, 'j', LTS_STATE_e_22 , LTS_STATE_e_82 , 5, 'r', LTS_STATE_e_22 , LTS_STATE_e_1976 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_162 , 1, 'a', LTS_STATE_e_22 , LTS_STATE_e_1977 , 3, 'd', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_1978 , 2, 'c', LTS_STATE_e_93 , LTS_STATE_e_1979 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 't', LTS_STATE_e_93 , LTS_STATE_e_1980 , 1, 'h', LTS_STATE_e_93 , LTS_STATE_e_1981 , 2, 'e', LTS_STATE_e_1383 , LTS_STATE_e_22 , 1, 'p', LTS_STATE_e_22 , LTS_STATE_e_1982 , 2, 'u', LTS_STATE_e_22 , LTS_STATE_e_1983 , 1, 'p', LTS_STATE_e_93 , LTS_STATE_e_22 , 5, 'i', LTS_STATE_e_1985 , LTS_STATE_e_1984 , 5, 'e', LTS_STATE_e_22 , LTS_STATE_e_1986 , 6, 's', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'i', LTS_STATE_e_1766 , LTS_STATE_e_22 , 6, 'h', LTS_STATE_e_22 , LTS_STATE_e_1987 , 5, 'h', LTS_STATE_e_160 , LTS_STATE_e_1988 , 5, 'r', LTS_STATE_e_160 , LTS_STATE_e_22 , 5, 'd', LTS_STATE_e_1300 , LTS_STATE_e_22 , 5, 's', LTS_STATE_e_22 , LTS_STATE_e_1989 , 4, 'l', LTS_STATE_e_22 , LTS_STATE_e_1990 , 4, 'l', LTS_STATE_e_1992 , LTS_STATE_e_1991 , 6, 'n', LTS_STATE_e_22 , LTS_STATE_e_1972 , 6, 'd', LTS_STATE_e_1183 , LTS_STATE_e_1993 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_1994 , 4, 't', LTS_STATE_e_1995 , LTS_STATE_e_22 , 4, 'd', LTS_STATE_e_1997 , LTS_STATE_e_1996 , 6, 'n', LTS_STATE_e_30 , LTS_STATE_e_1998 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_1870 , 6, 'l', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_1999 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_2000 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_93 , 5, 'y', LTS_STATE_e_82 , LTS_STATE_e_22 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_82 , 5, 'p', LTS_STATE_e_93 , LTS_STATE_e_2001 , 5, 'c', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'l', LTS_STATE_e_93 , LTS_STATE_e_82 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'g', LTS_STATE_e_82 , LTS_STATE_e_22 , 1, '#', LTS_STATE_e_2003 , LTS_STATE_e_2002 , 1, '#', LTS_STATE_e_2005 , LTS_STATE_e_2004 , 4, 'x', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'o', LTS_STATE_e_1365 , LTS_STATE_e_22 , 4, 'x', LTS_STATE_e_22 , LTS_STATE_e_2006 , 5, 'a', LTS_STATE_e_2008 , LTS_STATE_e_2007 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_2009 , 5, 'o', LTS_STATE_e_2011 , LTS_STATE_e_2010 , 2, 'g', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 't', LTS_STATE_e_36 , LTS_STATE_e_2012 , 5, 'r', LTS_STATE_e_2014 , LTS_STATE_e_2013 , 5, 'r', LTS_STATE_e_2016 , LTS_STATE_e_2015 , 3, 'n', LTS_STATE_e_93 , LTS_STATE_e_2017 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_2018 , 1, 'd', LTS_STATE_e_22 , LTS_STATE_e_93 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_2019 , 2, 'l', LTS_STATE_e_36 , LTS_STATE_e_2020 , 1, 'a', LTS_STATE_e_30 , LTS_STATE_e_93 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_2021 , 5, 'u', LTS_STATE_e_2023 , LTS_STATE_e_2022 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_2024 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_2025 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_93 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'a', LTS_STATE_e_22 , LTS_STATE_e_2026 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_2027 , 1, '#', LTS_STATE_e_22 , LTS_STATE_e_2028 , 4, 't', LTS_STATE_e_2030 , LTS_STATE_e_2029 , 5, 'a', LTS_STATE_e_1324 , LTS_STATE_e_2031 , 3, 't', LTS_STATE_e_36 , LTS_STATE_e_2032 , 3, 'm', LTS_STATE_e_93 , LTS_STATE_e_2033 , 1, 'c', LTS_STATE_e_93 , LTS_STATE_e_2034 , 6, 'i', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_2035 , 6, 't', LTS_STATE_e_22 , LTS_STATE_e_2036 , 5, 'y', LTS_STATE_e_22 , LTS_STATE_e_2037 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_1766 , 6, 'u', LTS_STATE_e_160 , LTS_STATE_e_2038 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_2039 , 4, 'c', LTS_STATE_e_582 , LTS_STATE_e_2040 , 6, 'n', LTS_STATE_e_1602 , LTS_STATE_e_2041 , 3, 'b', LTS_STATE_e_93 , LTS_STATE_e_2042 , 4, 'l', LTS_STATE_e_2044 , LTS_STATE_e_2043 , 4, 'd', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_2045 , 4, 'b', LTS_STATE_e_1983 , LTS_STATE_e_2046 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_30 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_22 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_2047 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_2048 , 6, 'r', LTS_STATE_e_82 , LTS_STATE_e_2049 , 2, 'u', LTS_STATE_e_82 , LTS_STATE_e_2050 , 3, 'l', LTS_STATE_e_2052 , LTS_STATE_e_2051 , 2, 's', LTS_STATE_e_132 , LTS_STATE_e_2053 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_2054 , 4, 'q', LTS_STATE_e_2056 , LTS_STATE_e_2055 , 5, 'e', LTS_STATE_e_2058 , LTS_STATE_e_2057 , 6, 'k', LTS_STATE_e_36 , LTS_STATE_e_2059 , 3, 'r', LTS_STATE_e_2061 , LTS_STATE_e_2060 , 3, 'l', LTS_STATE_e_2063 , LTS_STATE_e_2062 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_2064 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_2065 , 3, 'c', LTS_STATE_e_30 , LTS_STATE_e_2066 , 2, 'a', LTS_STATE_e_30 , LTS_STATE_e_22 , 2, 'o', LTS_STATE_e_36 , LTS_STATE_e_2067 , 6, 'i', LTS_STATE_e_1972 , LTS_STATE_e_2068 , 6, 'e', LTS_STATE_e_36 , LTS_STATE_e_2069 , 1, 'l', LTS_STATE_e_162 , LTS_STATE_e_2070 , 4, 'p', LTS_STATE_e_36 , LTS_STATE_e_2071 , 1, 'o', LTS_STATE_e_22 , LTS_STATE_e_2072 , 4, 's', LTS_STATE_e_160 , LTS_STATE_e_2073 , 5, 'i', LTS_STATE_e_2075 , LTS_STATE_e_2074 , 4, 'c', LTS_STATE_e_1914 , LTS_STATE_e_1054 , 5, 'i', LTS_STATE_e_30 , LTS_STATE_e_162 , 3, 'r', LTS_STATE_e_2077 , LTS_STATE_e_2076 , 4, 'g', LTS_STATE_e_30 , LTS_STATE_e_2078 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_2079 , 1, 'c', LTS_STATE_e_22 , LTS_STATE_e_2080 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_2081 , 1, '#', LTS_STATE_e_30 , LTS_STATE_e_22 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_2082 , 3, 'd', LTS_STATE_e_93 , LTS_STATE_e_2083 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_2084 , 3, 'd', LTS_STATE_e_93 , LTS_STATE_e_2085 , 5, 'o', LTS_STATE_e_22 , LTS_STATE_e_2086 , 6, 's', LTS_STATE_e_26 , LTS_STATE_e_22 , 5, 'v', LTS_STATE_e_22 , LTS_STATE_e_2087 , 5, 'v', LTS_STATE_e_160 , LTS_STATE_e_2088 , 5, 'd', LTS_STATE_e_160 , LTS_STATE_e_22 , 6, 'e', LTS_STATE_e_22 , LTS_STATE_e_2089 , 3, 'g', LTS_STATE_e_22 , LTS_STATE_e_2090 , 6, 'd', LTS_STATE_e_22 , LTS_STATE_e_2091 , 6, 'z', LTS_STATE_e_22 , LTS_STATE_e_2092 , 6, 'c', LTS_STATE_e_93 , LTS_STATE_e_2093 , 3, 'v', LTS_STATE_e_22 , LTS_STATE_e_30 , 6, 's', LTS_STATE_e_30 , LTS_STATE_e_2094 , 4, 'l', LTS_STATE_e_2096 , LTS_STATE_e_2095 , 4, 'b', LTS_STATE_e_2098 , LTS_STATE_e_2097 , 6, 'a', LTS_STATE_e_82 , LTS_STATE_e_2099 , 5, 't', LTS_STATE_e_1335 , LTS_STATE_e_2100 , 2, 'g', LTS_STATE_e_36 , LTS_STATE_e_30 , 6, 'o', LTS_STATE_e_36 , LTS_STATE_e_30 , 3, 'w', LTS_STATE_e_22 , LTS_STATE_e_2101 , 2, 'a', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 'i', LTS_STATE_e_2103 , LTS_STATE_e_2102 , 1, 'a', LTS_STATE_e_132 , LTS_STATE_e_2104 , 5, 'b', LTS_STATE_e_2106 , LTS_STATE_e_2105 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_2107 , 1, 'a', LTS_STATE_e_93 , LTS_STATE_e_2108 , 6, 'r', LTS_STATE_e_22 , LTS_STATE_e_680 , 1, 'i', LTS_STATE_e_22 , LTS_STATE_e_160 , 3, 'u', LTS_STATE_e_36 , LTS_STATE_e_2109 , 5, 'r', LTS_STATE_e_160 , LTS_STATE_e_2110 , 2, 'a', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 't', LTS_STATE_e_2112 , LTS_STATE_e_2111 , 3, 'p', LTS_STATE_e_30 , LTS_STATE_e_2113 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_2114 , 6, 'y', LTS_STATE_e_93 , LTS_STATE_e_36 , 1, 'o', LTS_STATE_e_22 , LTS_STATE_e_2115 , 3, 's', LTS_STATE_e_93 , LTS_STATE_e_2116 , 2, 'o', LTS_STATE_e_132 , LTS_STATE_e_93 , 4, 'x', LTS_STATE_e_22 , LTS_STATE_e_2117 , 2, 'n', LTS_STATE_e_132 , LTS_STATE_e_22 , 5, 'o', LTS_STATE_e_2119 , LTS_STATE_e_2118 , 6, 'e', LTS_STATE_e_2121 , LTS_STATE_e_2120 , 4, 'h', LTS_STATE_e_22 , LTS_STATE_e_2122 , 2, 'c', LTS_STATE_e_30 , LTS_STATE_e_22 , 3, 'r', LTS_STATE_e_30 , LTS_STATE_e_36 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_2123 , 1, 's', LTS_STATE_e_22 , LTS_STATE_e_160 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_1137 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_2124 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_285 , 3, 'z', LTS_STATE_e_93 , LTS_STATE_e_2125 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_2126 , 5, 'l', LTS_STATE_e_22 , LTS_STATE_e_2127 , 6, 'r', LTS_STATE_e_2129 , LTS_STATE_e_2128 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_1772 , 3, 'n', LTS_STATE_e_30 , LTS_STATE_e_22 , 6, 'p', LTS_STATE_e_22 , LTS_STATE_e_2130 , 6, 'n', LTS_STATE_e_949 , LTS_STATE_e_22 , 3, 'w', LTS_STATE_e_22 , LTS_STATE_e_2131 , 3, 'm', LTS_STATE_e_93 , LTS_STATE_e_2132 , 6, 'r', LTS_STATE_e_2134 , LTS_STATE_e_2133 , 6, 'e', LTS_STATE_e_30 , LTS_STATE_e_2135 , 3, 'f', LTS_STATE_e_93 , LTS_STATE_e_2136 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_82 , 5, 'i', LTS_STATE_e_93 , LTS_STATE_e_22 , 6, 'h', LTS_STATE_e_82 , LTS_STATE_e_22 , 3, 'l', LTS_STATE_e_30 , LTS_STATE_e_2137 , 1, 'a', LTS_STATE_e_2139 , LTS_STATE_e_2138 , 4, 'j', LTS_STATE_e_36 , LTS_STATE_e_2140 , 3, 'r', LTS_STATE_e_2142 , LTS_STATE_e_2141 , 6, 'e', LTS_STATE_e_30 , LTS_STATE_e_93 , 5, 'u', LTS_STATE_e_93 , LTS_STATE_e_2143 , 2, 's', LTS_STATE_e_22 , LTS_STATE_e_1471 , 3, 'h', LTS_STATE_e_30 , LTS_STATE_e_2144 , 6, 'r', LTS_STATE_e_2064 , LTS_STATE_e_93 , 6, 'e', LTS_STATE_e_132 , LTS_STATE_e_2145 , 2, 'l', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'm', LTS_STATE_e_93 , LTS_STATE_e_2146 , 3, 'h', LTS_STATE_e_93 , LTS_STATE_e_22 , 5, 'n', LTS_STATE_e_93 , LTS_STATE_e_2147 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_2148 , 1, 'e', LTS_STATE_e_22 , LTS_STATE_e_2149 , 4, 'c', LTS_STATE_e_22 , LTS_STATE_e_2150 , 2, 'p', LTS_STATE_e_93 , LTS_STATE_e_2151 , 2, 'u', LTS_STATE_e_93 , LTS_STATE_e_2152 , 3, 'r', LTS_STATE_e_22 , LTS_STATE_e_2153 , 3, 'h', LTS_STATE_e_2154 , LTS_STATE_e_22 , 2, 'c', LTS_STATE_e_22 , LTS_STATE_e_30 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_2155 , 5, 'a', LTS_STATE_e_90 , LTS_STATE_e_22 , 5, 'v', LTS_STATE_e_22 , LTS_STATE_e_2156 , 1, 'u', LTS_STATE_e_93 , LTS_STATE_e_2157 , 3, 'p', LTS_STATE_e_22 , LTS_STATE_e_2158 , 4, 'h', LTS_STATE_e_22 , LTS_STATE_e_2159 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_2160 , 5, 'd', LTS_STATE_e_22 , LTS_STATE_e_160 , 6, 'y', LTS_STATE_e_22 , LTS_STATE_e_2161 , 6, 's', LTS_STATE_e_2163 , LTS_STATE_e_2162 , 6, 'b', LTS_STATE_e_22 , LTS_STATE_e_2164 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_2165 , 4, 'g', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_2166 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_2167 , 6, '#', LTS_STATE_e_2168 , LTS_STATE_e_30 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_2169 , 4, 'v', LTS_STATE_e_160 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_2171 , LTS_STATE_e_2170 , 4, 'b', LTS_STATE_e_93 , LTS_STATE_e_2172 , 4, 'p', LTS_STATE_e_2173 , LTS_STATE_e_93 , 3, 'm', LTS_STATE_e_22 , LTS_STATE_e_2174 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_93 , 5, 'r', LTS_STATE_e_36 , LTS_STATE_e_2175 , 4, 'g', LTS_STATE_e_93 , LTS_STATE_e_36 , 5, 'a', LTS_STATE_e_93 , LTS_STATE_e_2176 , 5, 'o', LTS_STATE_e_36 , LTS_STATE_e_2177 , 3, 'c', LTS_STATE_e_2178 , LTS_STATE_e_22 , 1, 'h', LTS_STATE_e_36 , LTS_STATE_e_1942 , 3, 'l', LTS_STATE_e_1673 , LTS_STATE_e_2179 , 6, 'a', LTS_STATE_e_22 , LTS_STATE_e_2180 , 4, 'm', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_30 , 4, 'f', LTS_STATE_e_22 , LTS_STATE_e_2181 , 6, 'i', LTS_STATE_e_22 , LTS_STATE_e_2182 , 3, 'n', LTS_STATE_e_1551 , LTS_STATE_e_2183 , 5, 'f', LTS_STATE_e_93 , LTS_STATE_e_2184 , 5, 'p', LTS_STATE_e_22 , LTS_STATE_e_2185 , 5, 'g', LTS_STATE_e_160 , LTS_STATE_e_22 , 4, 's', LTS_STATE_e_22 , LTS_STATE_e_2186 , 6, 'a', LTS_STATE_e_93 , LTS_STATE_e_2187 , 4, 'c', LTS_STATE_e_93 , LTS_STATE_e_1994 , 3, 'c', LTS_STATE_e_160 , LTS_STATE_e_1627 , 6, 'd', LTS_STATE_e_93 , LTS_STATE_e_2188 , 4, 'p', LTS_STATE_e_160 , LTS_STATE_e_2189 , 3, 'm', LTS_STATE_e_160 , LTS_STATE_e_22 , 3, 'r', LTS_STATE_e_82 , LTS_STATE_e_2190 , 4, 'x', LTS_STATE_e_2192 , LTS_STATE_e_2191 , 5, 'q', LTS_STATE_e_22 , LTS_STATE_e_2193 , 2, 'r', LTS_STATE_e_917 , LTS_STATE_e_2194 , 2, 'd', LTS_STATE_e_36 , LTS_STATE_e_2195 , 5, 'r', LTS_STATE_e_22 , LTS_STATE_e_93 , 5, 'o', LTS_STATE_e_36 , LTS_STATE_e_22 , 5, 'u', LTS_STATE_e_36 , LTS_STATE_e_2196 , 2, 'a', LTS_STATE_e_36 , LTS_STATE_e_2197 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_2198 , 6, 'o', LTS_STATE_e_22 , LTS_STATE_e_36 , 2, 's', LTS_STATE_e_93 , LTS_STATE_e_2199 , 4, 's', LTS_STATE_e_2200 , LTS_STATE_e_22 , 3, 'h', LTS_STATE_e_22 , LTS_STATE_e_2201 , 1, 'i', LTS_STATE_e_93 , LTS_STATE_e_2202 , 2, 't', LTS_STATE_e_22 , LTS_STATE_e_2203 , 6, 'n', LTS_STATE_e_93 , LTS_STATE_e_2204 , 4, 'b', LTS_STATE_e_22 , LTS_STATE_e_2205 , 4, 'd', LTS_STATE_e_1948 , LTS_STATE_e_2206 , 4, 'b', LTS_STATE_e_22 , LTS_STATE_e_2207 , 6, 'c', LTS_STATE_e_93 , LTS_STATE_e_2208 , 3, 'g', LTS_STATE_e_22 , LTS_STATE_e_2209 , 1, 'a', LTS_STATE_e_82 , LTS_STATE_e_30 , 4, 'v', LTS_STATE_e_997 , LTS_STATE_e_93 , 2, 'i', LTS_STATE_e_160 , LTS_STATE_e_2210 , 2, 'h', LTS_STATE_e_2212 , LTS_STATE_e_2211 , 2, 'f', LTS_STATE_e_22 , LTS_STATE_e_2213 , 4, 'h', LTS_STATE_e_93 , LTS_STATE_e_2214 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_22 , 3, 'l', LTS_STATE_e_93 , LTS_STATE_e_2215 , 5, 'h', LTS_STATE_e_36 , LTS_STATE_e_22 , 2, 'g', LTS_STATE_e_93 , LTS_STATE_e_2216 , 2, 'c', LTS_STATE_e_2217 , LTS_STATE_e_22 , 4, 'p', LTS_STATE_e_93 , LTS_STATE_e_22 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_2218 , 3, 'r', LTS_STATE_e_93 , LTS_STATE_e_2219 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_2220 , 5, 's', LTS_STATE_e_22 , LTS_STATE_e_2221 , 3, 'l', LTS_STATE_e_22 , LTS_STATE_e_1062 , 3, 'g', LTS_STATE_e_1702 , LTS_STATE_e_2222 , 4, 'g', LTS_STATE_e_22 , LTS_STATE_e_2223 , 4, 'd', LTS_STATE_e_22 , LTS_STATE_e_2224 , 2, 'u', LTS_STATE_e_93 , LTS_STATE_e_2225 , 3, 'h', LTS_STATE_e_2227 , LTS_STATE_e_2226 , 3, 'o', LTS_STATE_e_36 , LTS_STATE_e_2228 , 2, 'm', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, 's', LTS_STATE_e_36 , LTS_STATE_e_93 , 5, 'e', LTS_STATE_e_728 , LTS_STATE_e_93 , 2, 'e', LTS_STATE_e_93 , LTS_STATE_e_2229 , 5, 'c', LTS_STATE_e_160 , LTS_STATE_e_22 , 2, 'o', LTS_STATE_e_22 , LTS_STATE_e_93 , 1, 'o', LTS_STATE_e_93 , LTS_STATE_e_2230 , 2, 'r', LTS_STATE_e_93 , LTS_STATE_e_2231 , 5, 'e', LTS_STATE_e_30 , LTS_STATE_e_22 , 4, 'f', LTS_STATE_e_93 , LTS_STATE_e_2232 , 4, 't', LTS_STATE_e_22 , LTS_STATE_e_2233 , 3, 'f', LTS_STATE_e_22 , LTS_STATE_e_2234 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_2235 , 4, 'c', LTS_STATE_e_2237 , LTS_STATE_e_2236 , 4, 'u', LTS_STATE_e_36 , LTS_STATE_e_1161 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_22 , 2, 'n', LTS_STATE_e_93 , LTS_STATE_e_22 , 1, 'e', LTS_STATE_e_93 , LTS_STATE_e_2238 , 2, 'u', LTS_STATE_e_93 , LTS_STATE_e_1339 , 3, 'c', LTS_STATE_e_93 , LTS_STATE_e_2239 , 3, 't', LTS_STATE_e_22 , LTS_STATE_e_2240 , 6, 'n', LTS_STATE_e_2241 , LTS_STATE_e_22 , 2, 'o', LTS_STATE_e_160 , LTS_STATE_e_1914 , 5, 'h', LTS_STATE_e_2243 , LTS_STATE_e_2242 , 6, 'l', LTS_STATE_e_93 , LTS_STATE_e_2244 , 3, 'k', LTS_STATE_e_93 , LTS_STATE_e_22 , 4, 'm', LTS_STATE_e_22 , LTS_STATE_e_1675 , 3, 's', LTS_STATE_e_22 , LTS_STATE_e_2245 , 4, 'n', LTS_STATE_e_625 , LTS_STATE_e_30 , 3, 'd', LTS_STATE_e_2247 , LTS_STATE_e_2246 , 1, 'j', LTS_STATE_e_93 , LTS_STATE_e_2248 , 5, 'e', LTS_STATE_e_132 , LTS_STATE_e_2249 , 4, 'v', LTS_STATE_e_22 , LTS_STATE_e_2250 , 4, 'h', LTS_STATE_e_36 , LTS_STATE_e_2251 , 2, 'i', LTS_STATE_e_36 , LTS_STATE_e_2252 , 3, 'r', LTS_STATE_e_36 , LTS_STATE_e_2253 , 6, 'e', LTS_STATE_e_2254 , LTS_STATE_e_1550 , 4, 'n', LTS_STATE_e_22 , LTS_STATE_e_2255 , 6, 's', LTS_STATE_e_36 , LTS_STATE_e_2256 , 1, 'r', LTS_STATE_e_93 , LTS_STATE_e_2257 , 6, 'o', LTS_STATE_e_36 , LTS_STATE_e_2258 , 5, 'h', LTS_STATE_e_22 , LTS_STATE_e_132 , 3, 'b', LTS_STATE_e_22 , LTS_STATE_e_160 , 5, 'n', LTS_STATE_e_36 , LTS_STATE_e_2259 , 4, 'b', LTS_STATE_e_36 , LTS_STATE_e_93 , 2, 'a', LTS_STATE_e_22 , LTS_STATE_e_2260 , 5, 'u', LTS_STATE_e_36 , LTS_STATE_e_2261 , 6, 'i', LTS_STATE_e_36 , LTS_STATE_e_132 , 1, 'f', LTS_STATE_e_36 , LTS_STATE_e_2262 , 3, 'r', LTS_STATE_e_2264 , LTS_STATE_e_2263 , 2, 'i', LTS_STATE_e_2266 , LTS_STATE_e_2265 , 2, 't', LTS_STATE_e_93 , LTS_STATE_e_2267 , 4, 'p', LTS_STATE_e_2269 , LTS_STATE_e_2268 , 5, 'o', LTS_STATE_e_36 , LTS_STATE_e_2270 , 2, 'r', LTS_STATE_e_93 , LTS_STATE_e_2271 , 3, 'g', LTS_STATE_e_93 , LTS_STATE_e_2272 , 5, 'p', LTS_STATE_e_22 , LTS_STATE_e_36 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_2273 , 6, 'r', LTS_STATE_e_93 , LTS_STATE_e_36 , 3, 'a', LTS_STATE_e_36 , LTS_STATE_e_2274 , 5, 'e', LTS_STATE_e_93 , LTS_STATE_e_2275 , 1, 'a', LTS_STATE_e_2277 , LTS_STATE_e_2276 , 3, 'n', LTS_STATE_e_2278 , LTS_STATE_e_36 , 6, 'a', LTS_STATE_e_36 , LTS_STATE_e_2279 , 4, 'b', LTS_STATE_e_93 , LTS_STATE_e_36 , 4, 's', LTS_STATE_e_36 , LTS_STATE_e_93 , 4, 'f', LTS_STATE_e_36 , LTS_STATE_e_2280 , 3, 'l', LTS_STATE_e_36 , LTS_STATE_e_2281 , 1, 'n', LTS_STATE_e_36 , LTS_STATE_e_2282 , 5, 'e', LTS_STATE_e_2283 , LTS_STATE_e_36 , 6, 'r', LTS_STATE_e_36 , LTS_STATE_e_2284 , 4, 'k', LTS_STATE_e_36 , LTS_STATE_e_93 , /** letter f **/ 4, 'f', LTS_STATE_f_2 , LTS_STATE_f_1 , 255, 37, 0,0 , 0,0 , 255, 0, 0,0 , 0,0 , /** letter g **/ 3, 'n', LTS_STATE_g_2 , LTS_STATE_g_1 , 4, 'h', LTS_STATE_g_4 , LTS_STATE_g_3 , 4, '#', LTS_STATE_g_6 , LTS_STATE_g_5 , 4, 'g', LTS_STATE_g_8 , LTS_STATE_g_7 , 5, 't', LTS_STATE_g_6 , LTS_STATE_g_9 , 4, 's', LTS_STATE_g_6 , LTS_STATE_g_10 , 255, 0, 0,0 , 0,0 , 4, 'e', LTS_STATE_g_13 , LTS_STATE_g_12 , 2, 's', LTS_STATE_g_15 , LTS_STATE_g_14 , 3, 'u', LTS_STATE_g_17 , LTS_STATE_g_16 , 4, 'e', LTS_STATE_g_19 , LTS_STATE_g_18 , 4, 'i', LTS_STATE_g_21 , LTS_STATE_g_20 , 5, 'r', LTS_STATE_g_23 , LTS_STATE_g_22 , 1, '#', LTS_STATE_g_6 , LTS_STATE_g_24 , 6, 's', LTS_STATE_g_25 , LTS_STATE_g_6 , 3, 'i', LTS_STATE_g_27 , LTS_STATE_g_26 , 5, '#', LTS_STATE_g_6 , LTS_STATE_g_28 , 4, 'i', LTS_STATE_g_30 , LTS_STATE_g_29 , 6, '#', LTS_STATE_g_32 , LTS_STATE_g_31 , 4, 'y', LTS_STATE_g_34 , LTS_STATE_g_33 , 2, 'l', LTS_STATE_g_36 , LTS_STATE_g_35 , 3, 'd', LTS_STATE_g_38 , LTS_STATE_g_37 , 6, '#', LTS_STATE_g_40 , LTS_STATE_g_39 , 5, 'l', LTS_STATE_g_42 , LTS_STATE_g_41 , 255, 38, 0,0 , 0,0 , 1, '0', LTS_STATE_g_25 , LTS_STATE_g_43 , 5, 'a', LTS_STATE_g_25 , LTS_STATE_g_44 , 1, 't', LTS_STATE_g_46 , LTS_STATE_g_45 , 4, 't', LTS_STATE_g_48 , LTS_STATE_g_47 , 6, 'g', LTS_STATE_g_50 , LTS_STATE_g_49 , 5, '#', LTS_STATE_g_38 , LTS_STATE_g_51 , 5, 'l', LTS_STATE_g_25 , LTS_STATE_g_52 , 4, 'n', LTS_STATE_g_54 , LTS_STATE_g_53 , 3, 'g', LTS_STATE_g_25 , LTS_STATE_g_55 , 5, 'a', LTS_STATE_g_38 , LTS_STATE_g_56 , 5, 'n', LTS_STATE_g_57 , LTS_STATE_g_38 , 3, 'g', LTS_STATE_g_59 , LTS_STATE_g_58 , 255, 28, 0,0 , 0,0 , 6, 'a', LTS_STATE_g_38 , LTS_STATE_g_60 , 3, 'd', LTS_STATE_g_38 , LTS_STATE_g_61 , 2, 'b', LTS_STATE_g_25 , LTS_STATE_g_6 , 1, 't', LTS_STATE_g_25 , LTS_STATE_g_6 , 1, 'b', LTS_STATE_g_25 , LTS_STATE_g_62 , 5, 'e', LTS_STATE_g_25 , LTS_STATE_g_6 , 1, 'l', LTS_STATE_g_64 , LTS_STATE_g_63 , 255, 37, 0,0 , 0,0 , 4, 'y', LTS_STATE_g_38 , LTS_STATE_g_65 , 2, 'e', LTS_STATE_g_66 , LTS_STATE_g_6 , 5, 'l', LTS_STATE_g_25 , LTS_STATE_g_67 , 2, 'i', LTS_STATE_g_6 , LTS_STATE_g_68 , 5, 'r', LTS_STATE_g_70 , LTS_STATE_g_69 , 5, 's', LTS_STATE_g_38 , LTS_STATE_g_71 , 3, 'd', LTS_STATE_g_73 , LTS_STATE_g_72 , 5, '#', LTS_STATE_g_6 , LTS_STATE_g_74 , 2, 'l', LTS_STATE_g_38 , LTS_STATE_g_75 , 2, '0', LTS_STATE_g_77 , LTS_STATE_g_76 , 6, 'g', LTS_STATE_g_38 , LTS_STATE_g_25 , 5, '#', LTS_STATE_g_38 , LTS_STATE_g_78 , 1, 's', LTS_STATE_g_38 , LTS_STATE_g_25 , 3, 'g', LTS_STATE_g_25 , LTS_STATE_g_79 , 1, 'c', LTS_STATE_g_38 , LTS_STATE_g_80 , 3, 'e', LTS_STATE_g_25 , LTS_STATE_g_81 , 2, 'o', LTS_STATE_g_83 , LTS_STATE_g_82 , 2, 'a', LTS_STATE_g_84 , LTS_STATE_g_6 , 5, 'y', LTS_STATE_g_86 , LTS_STATE_g_85 , 6, 'e', LTS_STATE_g_6 , LTS_STATE_g_87 , 6, 'e', LTS_STATE_g_38 , LTS_STATE_g_88 , 2, 'o', LTS_STATE_g_6 , LTS_STATE_g_38 , 5, 'l', LTS_STATE_g_90 , LTS_STATE_g_89 , 1, 'f', LTS_STATE_g_25 , LTS_STATE_g_91 , 1, 's', LTS_STATE_g_93 , LTS_STATE_g_92 , 3, 'g', LTS_STATE_g_95 , LTS_STATE_g_94 , 4, 'r', LTS_STATE_g_25 , LTS_STATE_g_96 , 2, '0', LTS_STATE_g_6 , LTS_STATE_g_97 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_98 , 3, 'g', LTS_STATE_g_100 , LTS_STATE_g_99 , 5, 'l', LTS_STATE_g_25 , LTS_STATE_g_101 , 5, 'l', LTS_STATE_g_103 , LTS_STATE_g_102 , 3, 'd', LTS_STATE_g_38 , LTS_STATE_g_104 , 3, 'a', LTS_STATE_g_106 , LTS_STATE_g_105 , 2, 'a', LTS_STATE_g_25 , LTS_STATE_g_107 , 2, 'a', LTS_STATE_g_6 , LTS_STATE_g_108 , 1, 'c', LTS_STATE_g_46 , LTS_STATE_g_6 , 5, 'l', LTS_STATE_g_87 , LTS_STATE_g_46 , 4, 'h', LTS_STATE_g_110 , LTS_STATE_g_109 , 4, 'l', LTS_STATE_g_6 , LTS_STATE_g_25 , 255, 22, 0,0 , 0,0 , 6, 'l', LTS_STATE_g_38 , LTS_STATE_g_111 , 6, 'b', LTS_STATE_g_6 , LTS_STATE_g_112 , 2, 'a', LTS_STATE_g_113 , LTS_STATE_g_25 , 1, 'd', LTS_STATE_g_38 , LTS_STATE_g_114 , 2, 'i', LTS_STATE_g_116 , LTS_STATE_g_115 , 2, 'i', LTS_STATE_g_38 , LTS_STATE_g_6 , 4, 't', LTS_STATE_g_117 , LTS_STATE_g_25 , 1, 'r', LTS_STATE_g_86 , LTS_STATE_g_25 , 6, 'n', LTS_STATE_g_38 , LTS_STATE_g_118 , 6, 'd', LTS_STATE_g_6 , LTS_STATE_g_119 , 6, 'e', LTS_STATE_g_25 , LTS_STATE_g_38 , 3, 'c', LTS_STATE_g_25 , LTS_STATE_g_120 , 5, 'o', LTS_STATE_g_38 , LTS_STATE_g_121 , 5, 'o', LTS_STATE_g_38 , LTS_STATE_g_122 , 5, 'i', LTS_STATE_g_25 , LTS_STATE_g_123 , 6, 'l', LTS_STATE_g_125 , LTS_STATE_g_124 , 6, 't', LTS_STATE_g_25 , LTS_STATE_g_126 , 1, 'm', LTS_STATE_g_38 , LTS_STATE_g_25 , 2, 'r', LTS_STATE_g_25 , LTS_STATE_g_127 , 5, '#', LTS_STATE_g_6 , LTS_STATE_g_128 , 5, 'e', LTS_STATE_g_6 , LTS_STATE_g_25 , 4, 'm', LTS_STATE_g_6 , LTS_STATE_g_129 , 5, 'i', LTS_STATE_g_25 , LTS_STATE_g_6 , 1, '#', LTS_STATE_g_38 , LTS_STATE_g_130 , 1, 'l', LTS_STATE_g_25 , LTS_STATE_g_131 , 6, 'o', LTS_STATE_g_25 , LTS_STATE_g_132 , 6, 's', LTS_STATE_g_134 , LTS_STATE_g_133 , 1, 'w', LTS_STATE_g_6 , LTS_STATE_g_135 , 1, 'h', LTS_STATE_g_38 , LTS_STATE_g_6 , 3, 'a', LTS_STATE_g_25 , LTS_STATE_g_136 , 5, 'e', LTS_STATE_g_38 , LTS_STATE_g_137 , 6, 't', LTS_STATE_g_25 , LTS_STATE_g_138 , 5, 'v', LTS_STATE_g_25 , LTS_STATE_g_139 , 5, '#', LTS_STATE_g_38 , LTS_STATE_g_140 , 5, 'u', LTS_STATE_g_38 , LTS_STATE_g_141 , 5, 't', LTS_STATE_g_143 , LTS_STATE_g_142 , 2, '0', LTS_STATE_g_144 , LTS_STATE_g_25 , 3, 'a', LTS_STATE_g_38 , LTS_STATE_g_25 , 6, 's', LTS_STATE_g_146 , LTS_STATE_g_145 , 1, 's', LTS_STATE_g_25 , LTS_STATE_g_147 , 1, 'o', LTS_STATE_g_6 , LTS_STATE_g_25 , 4, 'b', LTS_STATE_g_6 , LTS_STATE_g_148 , 1, 'r', LTS_STATE_g_38 , LTS_STATE_g_149 , 6, 't', LTS_STATE_g_38 , LTS_STATE_g_150 , 1, 'v', LTS_STATE_g_38 , LTS_STATE_g_151 , 1, 'l', LTS_STATE_g_25 , LTS_STATE_g_152 , 2, 'i', LTS_STATE_g_6 , LTS_STATE_g_153 , 2, 'o', LTS_STATE_g_6 , LTS_STATE_g_154 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_6 , 4, 'a', LTS_STATE_g_25 , LTS_STATE_g_155 , 3, 'i', LTS_STATE_g_157 , LTS_STATE_g_156 , 3, 'o', LTS_STATE_g_25 , LTS_STATE_g_158 , 5, 'n', LTS_STATE_g_25 , LTS_STATE_g_159 , 5, 'n', LTS_STATE_g_161 , LTS_STATE_g_160 , 2, 'h', LTS_STATE_g_163 , LTS_STATE_g_162 , 1, '0', LTS_STATE_g_25 , LTS_STATE_g_164 , 6, 'a', LTS_STATE_g_38 , LTS_STATE_g_25 , 2, 'e', LTS_STATE_g_25 , LTS_STATE_g_165 , 3, 'a', LTS_STATE_g_166 , LTS_STATE_g_25 , 1, 'h', LTS_STATE_g_25 , LTS_STATE_g_167 , 4, 'd', LTS_STATE_g_6 , LTS_STATE_g_168 , 5, 'n', LTS_STATE_g_25 , LTS_STATE_g_169 , 2, 'o', LTS_STATE_g_38 , LTS_STATE_g_170 , 1, '#', LTS_STATE_g_171 , LTS_STATE_g_25 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_172 , 2, 'e', LTS_STATE_g_38 , LTS_STATE_g_6 , 5, 'd', LTS_STATE_g_38 , LTS_STATE_g_173 , 4, 'o', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, '#', LTS_STATE_g_108 , LTS_STATE_g_25 , 5, 'm', LTS_STATE_g_6 , LTS_STATE_g_174 , 6, '#', LTS_STATE_g_176 , LTS_STATE_g_175 , 1, 'r', LTS_STATE_g_38 , LTS_STATE_g_25 , 5, 'v', LTS_STATE_g_25 , LTS_STATE_g_177 , 6, 'n', LTS_STATE_g_38 , LTS_STATE_g_178 , 6, 's', LTS_STATE_g_180 , LTS_STATE_g_179 , 1, 'n', LTS_STATE_g_25 , LTS_STATE_g_181 , 2, 'v', LTS_STATE_g_38 , LTS_STATE_g_182 , 6, 'g', LTS_STATE_g_25 , LTS_STATE_g_183 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_38 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_184 , 4, 'f', LTS_STATE_g_6 , LTS_STATE_g_185 , 2, 'i', LTS_STATE_g_25 , LTS_STATE_g_186 , 6, 'i', LTS_STATE_g_25 , LTS_STATE_g_187 , 6, 'i', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, 't', LTS_STATE_g_25 , LTS_STATE_g_188 , 2, 'e', LTS_STATE_g_38 , LTS_STATE_g_189 , 5, 's', LTS_STATE_g_6 , LTS_STATE_g_190 , 6, 'l', LTS_STATE_g_192 , LTS_STATE_g_191 , 2, 'r', LTS_STATE_g_38 , LTS_STATE_g_193 , 5, 'f', LTS_STATE_g_25 , LTS_STATE_g_194 , 6, 't', LTS_STATE_g_38 , LTS_STATE_g_195 , 6, 'h', LTS_STATE_g_25 , LTS_STATE_g_196 , 1, 'j', LTS_STATE_g_25 , LTS_STATE_g_197 , 5, 'm', LTS_STATE_g_25 , LTS_STATE_g_198 , 6, 't', LTS_STATE_g_199 , LTS_STATE_g_25 , 6, 'l', LTS_STATE_g_25 , LTS_STATE_g_200 , 2, 'e', LTS_STATE_g_25 , LTS_STATE_g_38 , 4, 'w', LTS_STATE_g_6 , LTS_STATE_g_201 , 5, 'e', LTS_STATE_g_6 , LTS_STATE_g_38 , 6, 'u', LTS_STATE_g_38 , LTS_STATE_g_202 , 2, 'i', LTS_STATE_g_38 , LTS_STATE_g_25 , 1, 'r', LTS_STATE_g_38 , LTS_STATE_g_203 , 1, '0', LTS_STATE_g_25 , LTS_STATE_g_204 , 2, 'b', LTS_STATE_g_25 , LTS_STATE_g_205 , 1, 'c', LTS_STATE_g_25 , LTS_STATE_g_206 , 2, 'o', LTS_STATE_g_206 , LTS_STATE_g_207 , 6, 'd', LTS_STATE_g_25 , LTS_STATE_g_208 , 6, 'g', LTS_STATE_g_25 , LTS_STATE_g_38 , 5, 'u', LTS_STATE_g_210 , LTS_STATE_g_209 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_211 , 5, 'n', LTS_STATE_g_25 , LTS_STATE_g_38 , 3, 'r', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, 'b', LTS_STATE_g_25 , LTS_STATE_g_212 , 4, 'p', LTS_STATE_g_6 , LTS_STATE_g_213 , 2, 'a', LTS_STATE_g_38 , LTS_STATE_g_214 , 1, 'l', LTS_STATE_g_6 , LTS_STATE_g_215 , 5, 'a', LTS_STATE_g_25 , LTS_STATE_g_216 , 2, 'h', LTS_STATE_g_25 , LTS_STATE_g_217 , 5, 'e', LTS_STATE_g_25 , LTS_STATE_g_38 , 1, '#', LTS_STATE_g_38 , LTS_STATE_g_218 , 6, 's', LTS_STATE_g_25 , LTS_STATE_g_219 , 1, 'b', LTS_STATE_g_199 , LTS_STATE_g_220 , 255, 39, 0,0 , 0,0 , 5, 'm', LTS_STATE_g_38 , LTS_STATE_g_221 , 6, 'y', LTS_STATE_g_38 , LTS_STATE_g_222 , 5, 'u', LTS_STATE_g_224 , LTS_STATE_g_223 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_225 , 5, 'r', LTS_STATE_g_226 , LTS_STATE_g_38 , 6, 'f', LTS_STATE_g_25 , LTS_STATE_g_227 , 2, 's', LTS_STATE_g_25 , LTS_STATE_g_38 , 5, 's', LTS_STATE_g_25 , LTS_STATE_g_228 , 5, 's', LTS_STATE_g_38 , LTS_STATE_g_229 , 2, 'b', LTS_STATE_g_25 , LTS_STATE_g_230 , 5, 'n', LTS_STATE_g_231 , LTS_STATE_g_25 , 2, 'n', LTS_STATE_g_38 , LTS_STATE_g_232 , 4, 'o', LTS_STATE_g_25 , LTS_STATE_g_233 , 2, 'a', LTS_STATE_g_6 , LTS_STATE_g_234 , 2, 'i', LTS_STATE_g_25 , LTS_STATE_g_38 , 2, 'a', LTS_STATE_g_6 , LTS_STATE_g_25 , 2, 'm', LTS_STATE_g_25 , LTS_STATE_g_235 , 1, 'r', LTS_STATE_g_25 , LTS_STATE_g_236 , 5, 'r', LTS_STATE_g_25 , LTS_STATE_g_237 , 6, 'r', LTS_STATE_g_239 , LTS_STATE_g_238 , 1, '0', LTS_STATE_g_38 , LTS_STATE_g_25 , 2, '0', LTS_STATE_g_241 , LTS_STATE_g_240 , 4, 'a', LTS_STATE_g_243 , LTS_STATE_g_242 , 6, 'i', LTS_STATE_g_6 , LTS_STATE_g_25 , 6, 'n', LTS_STATE_g_245 , LTS_STATE_g_244 , 2, 'e', LTS_STATE_g_25 , LTS_STATE_g_246 , 6, 'g', LTS_STATE_g_25 , LTS_STATE_g_247 , 3, 'a', LTS_STATE_g_249 , LTS_STATE_g_248 , 5, 'o', LTS_STATE_g_38 , LTS_STATE_g_250 , 3, 'i', LTS_STATE_g_38 , LTS_STATE_g_251 , 6, 'm', LTS_STATE_g_38 , LTS_STATE_g_252 , 4, 'r', LTS_STATE_g_25 , LTS_STATE_g_253 , 1, 'h', LTS_STATE_g_6 , LTS_STATE_g_25 , 6, 'r', LTS_STATE_g_6 , LTS_STATE_g_254 , 5, 'i', LTS_STATE_g_6 , LTS_STATE_g_25 , 3, 'a', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, 'm', LTS_STATE_g_25 , LTS_STATE_g_255 , 6, 't', LTS_STATE_g_38 , LTS_STATE_g_256 , 5, 'n', LTS_STATE_g_166 , LTS_STATE_g_38 , 5, 'a', LTS_STATE_g_25 , LTS_STATE_g_257 , 6, 'i', LTS_STATE_g_38 , LTS_STATE_g_25 , 6, 'r', LTS_STATE_g_38 , LTS_STATE_g_258 , 4, 'l', LTS_STATE_g_260 , LTS_STATE_g_259 , 6, '#', LTS_STATE_g_6 , LTS_STATE_g_25 , 5, 'd', LTS_STATE_g_25 , LTS_STATE_g_261 , 5, 'o', LTS_STATE_g_38 , LTS_STATE_g_262 , 5, 'e', LTS_STATE_g_25 , LTS_STATE_g_263 , 6, 'i', LTS_STATE_g_38 , LTS_STATE_g_264 , 5, 'e', LTS_STATE_g_6 , LTS_STATE_g_265 , 2, 'e', LTS_STATE_g_108 , LTS_STATE_g_266 , 5, 'b', LTS_STATE_g_268 , LTS_STATE_g_267 , 5, 'n', LTS_STATE_g_270 , LTS_STATE_g_269 , 5, 'h', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, 'o', LTS_STATE_g_38 , LTS_STATE_g_25 , 4, 'u', LTS_STATE_g_25 , LTS_STATE_g_6 , 5, 'e', LTS_STATE_g_272 , LTS_STATE_g_271 , 6, 'l', LTS_STATE_g_38 , LTS_STATE_g_273 , 6, 'b', LTS_STATE_g_25 , LTS_STATE_g_38 , 6, '#', LTS_STATE_g_38 , LTS_STATE_g_274 , 6, '#', LTS_STATE_g_275 , LTS_STATE_g_225 , 6, 's', LTS_STATE_g_25 , LTS_STATE_g_276 , 1, 'l', LTS_STATE_g_6 , LTS_STATE_g_25 , 5, 'e', LTS_STATE_g_25 , LTS_STATE_g_277 , 5, 'a', LTS_STATE_g_38 , LTS_STATE_g_278 , 3, 'o', LTS_STATE_g_38 , LTS_STATE_g_279 , 6, 'n', LTS_STATE_g_25 , LTS_STATE_g_280 , 6, 'a', LTS_STATE_g_25 , LTS_STATE_g_281 , 6, 'i', LTS_STATE_g_38 , LTS_STATE_g_282 , 3, 'r', LTS_STATE_g_25 , LTS_STATE_g_283 , 6, 'm', LTS_STATE_g_25 , LTS_STATE_g_284 , 6, 't', LTS_STATE_g_25 , LTS_STATE_g_38 , 3, 'l', LTS_STATE_g_25 , LTS_STATE_g_285 , 1, '#', LTS_STATE_g_25 , LTS_STATE_g_286 , 5, 'a', LTS_STATE_g_6 , LTS_STATE_g_245 , 6, 'a', LTS_STATE_g_25 , LTS_STATE_g_287 , 3, 'i', LTS_STATE_g_38 , LTS_STATE_g_25 , 5, 'm', LTS_STATE_g_38 , LTS_STATE_g_288 , 1, '0', LTS_STATE_g_289 , LTS_STATE_g_25 , 5, 'b', LTS_STATE_g_38 , LTS_STATE_g_25 , /** letter h **/ 3, '#', LTS_STATE_h_2 , LTS_STATE_h_1 , 3, 'c', LTS_STATE_h_4 , LTS_STATE_h_3 , 4, 'a', LTS_STATE_h_6 , LTS_STATE_h_5 , 3, 's', LTS_STATE_h_8 , LTS_STATE_h_7 , 4, 'o', LTS_STATE_h_9 , LTS_STATE_h_8 , 4, 'o', LTS_STATE_h_6 , LTS_STATE_h_10 , 255, 40, 0,0 , 0,0 , 3, 't', LTS_STATE_h_13 , LTS_STATE_h_12 , 255, 0, 0,0 , 0,0 , 1, 'i', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'i', LTS_STATE_h_6 , LTS_STATE_h_14 , 3, 'p', LTS_STATE_h_16 , LTS_STATE_h_15 , 4, 'o', LTS_STATE_h_17 , LTS_STATE_h_8 , 4, 'u', LTS_STATE_h_6 , LTS_STATE_h_18 , 3, 'g', LTS_STATE_h_20 , LTS_STATE_h_19 , 1, '#', LTS_STATE_h_8 , LTS_STATE_h_21 , 1, '0', LTS_STATE_h_8 , LTS_STATE_h_22 , 4, 'y', LTS_STATE_h_6 , LTS_STATE_h_23 , 1, '0', LTS_STATE_h_25 , LTS_STATE_h_24 , 1, 'i', LTS_STATE_h_27 , LTS_STATE_h_26 , 1, 'h', LTS_STATE_h_28 , LTS_STATE_h_8 , 1, 'g', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'e', LTS_STATE_h_6 , LTS_STATE_h_29 , 4, 'l', LTS_STATE_h_8 , LTS_STATE_h_30 , 4, 'o', LTS_STATE_h_32 , LTS_STATE_h_31 , 4, 'o', LTS_STATE_h_34 , LTS_STATE_h_33 , 4, 'o', LTS_STATE_h_6 , LTS_STATE_h_35 , 4, 'e', LTS_STATE_h_8 , LTS_STATE_h_6 , 4, 'r', LTS_STATE_h_6 , LTS_STATE_h_36 , 4, '#', LTS_STATE_h_8 , LTS_STATE_h_37 , 3, 'o', LTS_STATE_h_39 , LTS_STATE_h_38 , 3, 'r', LTS_STATE_h_8 , LTS_STATE_h_40 , 4, 'a', LTS_STATE_h_42 , LTS_STATE_h_41 , 1, '0', LTS_STATE_h_8 , LTS_STATE_h_6 , 4, 'a', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'l', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'n', LTS_STATE_h_8 , LTS_STATE_h_43 , 3, 'a', LTS_STATE_h_35 , LTS_STATE_h_8 , 4, 'a', LTS_STATE_h_6 , LTS_STATE_h_44 , 3, 'w', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'u', LTS_STATE_h_6 , LTS_STATE_h_8 , 1, '0', LTS_STATE_h_8 , LTS_STATE_h_45 , 4, 'r', LTS_STATE_h_8 , LTS_STATE_h_46 , 4, 'l', LTS_STATE_h_8 , LTS_STATE_h_47 , 1, 'n', LTS_STATE_h_6 , LTS_STATE_h_8 , 4, 'm', LTS_STATE_h_8 , LTS_STATE_h_48 , 4, 'm', LTS_STATE_h_8 , LTS_STATE_h_6 , 4, 's', LTS_STATE_h_8 , LTS_STATE_h_49 , 3, 'w', LTS_STATE_h_45 , LTS_STATE_h_50 , 3, 'x', LTS_STATE_h_52 , LTS_STATE_h_51 , 4, 't', LTS_STATE_h_8 , LTS_STATE_h_53 , 4, 'i', LTS_STATE_h_8 , LTS_STATE_h_54 , 4, 'd', LTS_STATE_h_8 , LTS_STATE_h_55 , 4, 'a', LTS_STATE_h_8 , LTS_STATE_h_6 , 4, 'o', LTS_STATE_h_57 , LTS_STATE_h_56 , 3, 'n', LTS_STATE_h_6 , LTS_STATE_h_58 , 1, 's', LTS_STATE_h_6 , LTS_STATE_h_59 , 4, 'y', LTS_STATE_h_61 , LTS_STATE_h_60 , 1, 'c', LTS_STATE_h_6 , LTS_STATE_h_62 , 1, 'h', LTS_STATE_h_54 , LTS_STATE_h_63 , 3, 'e', LTS_STATE_h_6 , LTS_STATE_h_64 , 3, 'e', LTS_STATE_h_6 , LTS_STATE_h_65 , 3, 'z', LTS_STATE_h_67 , LTS_STATE_h_66 , 3, 'a', LTS_STATE_h_6 , LTS_STATE_h_8 , 3, 'd', LTS_STATE_h_6 , LTS_STATE_h_68 , 3, 'd', LTS_STATE_h_70 , LTS_STATE_h_69 , 4, 'a', LTS_STATE_h_6 , LTS_STATE_h_71 , 3, 'n', LTS_STATE_h_6 , LTS_STATE_h_72 , 1, 'u', LTS_STATE_h_6 , LTS_STATE_h_73 , 4, 'e', LTS_STATE_h_6 , LTS_STATE_h_74 , 4, 'e', LTS_STATE_h_6 , LTS_STATE_h_8 , 1, 'o', LTS_STATE_h_75 , LTS_STATE_h_6 , 1, 'e', LTS_STATE_h_6 , LTS_STATE_h_76 , 4, 'u', LTS_STATE_h_6 , LTS_STATE_h_77 , 3, 'r', LTS_STATE_h_8 , LTS_STATE_h_6 , 4, 'a', LTS_STATE_h_79 , LTS_STATE_h_78 , 1, 'e', LTS_STATE_h_6 , LTS_STATE_h_8 , 1, '#', LTS_STATE_h_81 , LTS_STATE_h_80 , 1, '#', LTS_STATE_h_6 , LTS_STATE_h_82 , 1, 'k', LTS_STATE_h_8 , LTS_STATE_h_83 , 4, 'i', LTS_STATE_h_6 , LTS_STATE_h_84 , 1, 'b', LTS_STATE_h_6 , LTS_STATE_h_85 , 3, 'o', LTS_STATE_h_6 , LTS_STATE_h_86 , 4, 'e', LTS_STATE_h_6 , LTS_STATE_h_41 , 1, 'v', LTS_STATE_h_6 , LTS_STATE_h_87 , 1, 'p', LTS_STATE_h_6 , LTS_STATE_h_88 , 1, 'm', LTS_STATE_h_8 , LTS_STATE_h_89 , 1, 't', LTS_STATE_h_6 , LTS_STATE_h_90 , 3, 'i', LTS_STATE_h_6 , LTS_STATE_h_91 , 1, 'i', LTS_STATE_h_6 , LTS_STATE_h_92 , 1, 'f', LTS_STATE_h_6 , LTS_STATE_h_93 , 1, 'l', LTS_STATE_h_6 , LTS_STATE_h_94 , 1, 'd', LTS_STATE_h_6 , LTS_STATE_h_95 , 1, 'o', LTS_STATE_h_6 , LTS_STATE_h_96 , 3, 'o', LTS_STATE_h_6 , LTS_STATE_h_97 , 1, 'g', LTS_STATE_h_6 , LTS_STATE_h_98 , 3, 'a', LTS_STATE_h_6 , LTS_STATE_h_99 , 3, 'i', LTS_STATE_h_101 , LTS_STATE_h_100 , 3, 'm', LTS_STATE_h_6 , LTS_STATE_h_102 , 1, 'c', LTS_STATE_h_6 , LTS_STATE_h_103 , 1, 'n', LTS_STATE_h_8 , LTS_STATE_h_6 , 1, 'r', LTS_STATE_h_104 , LTS_STATE_h_6 , 1, 'n', LTS_STATE_h_6 , LTS_STATE_h_105 , 3, 'u', LTS_STATE_h_8 , LTS_STATE_h_6 , 3, 'e', LTS_STATE_h_6 , LTS_STATE_h_106 , 1, 'w', LTS_STATE_h_6 , LTS_STATE_h_107 , 1, 'r', LTS_STATE_h_6 , LTS_STATE_h_108 , 1, 'a', LTS_STATE_h_6 , LTS_STATE_h_109 , 3, 'r', LTS_STATE_h_6 , LTS_STATE_h_110 , 1, 's', LTS_STATE_h_6 , LTS_STATE_h_111 , 1, 'm', LTS_STATE_h_6 , LTS_STATE_h_64 , /** letter i **/ 5, 'g', LTS_STATE_i_2 , LTS_STATE_i_1 , 4, '#', LTS_STATE_i_4 , LTS_STATE_i_3 , 6, '#', LTS_STATE_i_6 , LTS_STATE_i_5 , 4, 'o', LTS_STATE_i_8 , LTS_STATE_i_7 , 3, 'a', LTS_STATE_i_10 , LTS_STATE_i_9 , 2, '#', LTS_STATE_i_12 , LTS_STATE_i_11 , 4, 'n', LTS_STATE_i_14 , LTS_STATE_i_13 , 4, 'e', LTS_STATE_i_16 , LTS_STATE_i_15 , 3, 't', LTS_STATE_i_18 , LTS_STATE_i_17 , 3, 'e', LTS_STATE_i_20 , LTS_STATE_i_19 , 2, 'h', LTS_STATE_i_22 , LTS_STATE_i_21 , 4, 'n', LTS_STATE_i_24 , LTS_STATE_i_23 , 4, 'e', LTS_STATE_i_26 , LTS_STATE_i_25 , 4, 'e', LTS_STATE_i_26 , LTS_STATE_i_27 , 2, '#', LTS_STATE_i_27 , LTS_STATE_i_28 , 4, 'a', LTS_STATE_i_30 , LTS_STATE_i_29 , 2, '#', LTS_STATE_i_32 , LTS_STATE_i_31 , 3, 's', LTS_STATE_i_34 , LTS_STATE_i_33 , 5, 'n', LTS_STATE_i_36 , LTS_STATE_i_35 , 255, 31, 0,0 , 0,0 , 2, 'm', LTS_STATE_i_22 , LTS_STATE_i_36 , 2, 'k', LTS_STATE_i_22 , LTS_STATE_i_38 , 255, 19, 0,0 , 0,0 , 4, 'e', LTS_STATE_i_26 , LTS_STATE_i_39 , 3, 's', LTS_STATE_i_41 , LTS_STATE_i_40 , 4, 'r', LTS_STATE_i_36 , LTS_STATE_i_42 , 255, 29, 0,0 , 0,0 , 255, 12, 0,0 , 0,0 , 3, 'r', LTS_STATE_i_44 , LTS_STATE_i_43 , 3, 'a', LTS_STATE_i_46 , LTS_STATE_i_45 , 3, 'c', LTS_STATE_i_48 , LTS_STATE_i_47 , 5, 'r', LTS_STATE_i_50 , LTS_STATE_i_49 , 5, 'r', LTS_STATE_i_52 , LTS_STATE_i_51 , 2, '#', LTS_STATE_i_54 , LTS_STATE_i_53 , 5, 'n', LTS_STATE_i_36 , LTS_STATE_i_19 , 5, 'u', LTS_STATE_i_36 , LTS_STATE_i_19 , 255, 0, 0,0 , 0,0 , 2, 'd', LTS_STATE_i_36 , LTS_STATE_i_22 , 6, 'e', LTS_STATE_i_56 , LTS_STATE_i_55 , 2, '0', LTS_STATE_i_27 , LTS_STATE_i_57 , 6, 'e', LTS_STATE_i_59 , LTS_STATE_i_58 , 4, 'a', LTS_STATE_i_61 , LTS_STATE_i_60 , 3, 'w', LTS_STATE_i_62 , LTS_STATE_i_58 , 2, 'd', LTS_STATE_i_27 , LTS_STATE_i_63 , 5, 'e', LTS_STATE_i_65 , LTS_STATE_i_64 , 4, 'c', LTS_STATE_i_67 , LTS_STATE_i_66 , 3, 't', LTS_STATE_i_69 , LTS_STATE_i_68 , 5, 't', LTS_STATE_i_19 , LTS_STATE_i_70 , 5, '#', LTS_STATE_i_19 , LTS_STATE_i_71 , 3, 'e', LTS_STATE_i_73 , LTS_STATE_i_72 , 5, 'w', LTS_STATE_i_36 , LTS_STATE_i_74 , 3, 'h', LTS_STATE_i_22 , LTS_STATE_i_75 , 5, 'n', LTS_STATE_i_77 , LTS_STATE_i_76 , 3, 'g', LTS_STATE_i_36 , LTS_STATE_i_78 , 4, 'o', LTS_STATE_i_80 , LTS_STATE_i_79 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_81 , 3, 'e', LTS_STATE_i_22 , LTS_STATE_i_82 , 255, 16, 0,0 , 0,0 , 255, 5, 0,0 , 0,0 , 4, 'o', LTS_STATE_i_83 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_22 , LTS_STATE_i_19 , 2, 'o', LTS_STATE_i_58 , LTS_STATE_i_84 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_85 , 4, 'c', LTS_STATE_i_87 , LTS_STATE_i_86 , 4, 'v', LTS_STATE_i_89 , LTS_STATE_i_88 , 2, 'z', LTS_STATE_i_27 , LTS_STATE_i_90 , 5, '#', LTS_STATE_i_58 , LTS_STATE_i_36 , 2, '#', LTS_STATE_i_92 , LTS_STATE_i_91 , 5, 't', LTS_STATE_i_19 , LTS_STATE_i_93 , 6, 'o', LTS_STATE_i_19 , LTS_STATE_i_94 , 5, 's', LTS_STATE_i_96 , LTS_STATE_i_95 , 6, '#', LTS_STATE_i_98 , LTS_STATE_i_97 , 2, 'm', LTS_STATE_i_83 , LTS_STATE_i_22 , 3, 'd', LTS_STATE_i_100 , LTS_STATE_i_99 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_101 , 5, 'u', LTS_STATE_i_103 , LTS_STATE_i_102 , 2, 'l', LTS_STATE_i_105 , LTS_STATE_i_104 , 3, 'f', LTS_STATE_i_19 , LTS_STATE_i_106 , 4, 'a', LTS_STATE_i_19 , LTS_STATE_i_107 , 2, 'o', LTS_STATE_i_83 , LTS_STATE_i_19 , 4, 'd', LTS_STATE_i_109 , LTS_STATE_i_108 , 2, 's', LTS_STATE_i_111 , LTS_STATE_i_110 , 255, 13, 0,0 , 0,0 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_112 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_113 , 4, 'r', LTS_STATE_i_115 , LTS_STATE_i_114 , 2, '#', LTS_STATE_i_117 , LTS_STATE_i_116 , 3, 'o', LTS_STATE_i_119 , LTS_STATE_i_118 , 3, 't', LTS_STATE_i_58 , LTS_STATE_i_120 , 5, 'a', LTS_STATE_i_122 , LTS_STATE_i_121 , 3, 's', LTS_STATE_i_124 , LTS_STATE_i_123 , 3, 'g', LTS_STATE_i_36 , LTS_STATE_i_125 , 6, '#', LTS_STATE_i_36 , LTS_STATE_i_126 , 5, 'l', LTS_STATE_i_36 , LTS_STATE_i_127 , 5, 'd', LTS_STATE_i_129 , LTS_STATE_i_128 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_130 , 6, 's', LTS_STATE_i_132 , LTS_STATE_i_131 , 3, 'a', LTS_STATE_i_83 , LTS_STATE_i_133 , 6, 'e', LTS_STATE_i_26 , LTS_STATE_i_134 , 5, 't', LTS_STATE_i_136 , LTS_STATE_i_135 , 3, 's', LTS_STATE_i_19 , LTS_STATE_i_137 , 5, 'r', LTS_STATE_i_139 , LTS_STATE_i_138 , 3, 'c', LTS_STATE_i_36 , LTS_STATE_i_140 , 3, 'n', LTS_STATE_i_105 , LTS_STATE_i_141 , 255, 41, 0,0 , 0,0 , 5, 'l', LTS_STATE_i_143 , LTS_STATE_i_142 , 6, 'r', LTS_STATE_i_36 , LTS_STATE_i_27 , 4, 'g', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'r', LTS_STATE_i_144 , LTS_STATE_i_58 , 3, 'r', LTS_STATE_i_146 , LTS_STATE_i_145 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_147 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_27 , 2, 'u', LTS_STATE_i_58 , LTS_STATE_i_148 , 3, 'e', LTS_STATE_i_150 , LTS_STATE_i_149 , 6, 'n', LTS_STATE_i_152 , LTS_STATE_i_151 , 5, '#', LTS_STATE_i_58 , LTS_STATE_i_153 , 5, 'r', LTS_STATE_i_22 , LTS_STATE_i_154 , 6, '#', LTS_STATE_i_156 , LTS_STATE_i_155 , 4, 'r', LTS_STATE_i_157 , LTS_STATE_i_36 , 3, 's', LTS_STATE_i_58 , LTS_STATE_i_158 , 5, 'o', LTS_STATE_i_160 , LTS_STATE_i_159 , 4, 'n', LTS_STATE_i_36 , LTS_STATE_i_161 , 3, 'l', LTS_STATE_i_163 , LTS_STATE_i_162 , 5, 'k', LTS_STATE_i_19 , LTS_STATE_i_164 , 3, 'd', LTS_STATE_i_22 , LTS_STATE_i_165 , 2, 's', LTS_STATE_i_167 , LTS_STATE_i_166 , 5, 'n', LTS_STATE_i_36 , LTS_STATE_i_168 , 5, 'w', LTS_STATE_i_170 , LTS_STATE_i_169 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_171 , 6, '#', LTS_STATE_i_173 , LTS_STATE_i_172 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_174 , 2, 'i', LTS_STATE_i_22 , LTS_STATE_i_175 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_176 , 5, 's', LTS_STATE_i_135 , LTS_STATE_i_177 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_26 , 6, 'z', LTS_STATE_i_26 , LTS_STATE_i_178 , 6, 'a', LTS_STATE_i_26 , LTS_STATE_i_179 , 2, '0', LTS_STATE_i_22 , LTS_STATE_i_180 , 3, 'r', LTS_STATE_i_182 , LTS_STATE_i_181 , 3, 'g', LTS_STATE_i_36 , LTS_STATE_i_19 , 2, '0', LTS_STATE_i_83 , LTS_STATE_i_183 , 3, 'b', LTS_STATE_i_22 , LTS_STATE_i_184 , 6, 'e', LTS_STATE_i_22 , LTS_STATE_i_185 , 2, 'b', LTS_STATE_i_27 , LTS_STATE_i_186 , 6, 's', LTS_STATE_i_58 , LTS_STATE_i_187 , 6, 't', LTS_STATE_i_58 , LTS_STATE_i_188 , 6, 'u', LTS_STATE_i_27 , LTS_STATE_i_189 , 2, 'o', LTS_STATE_i_58 , LTS_STATE_i_190 , 3, 'o', LTS_STATE_i_192 , LTS_STATE_i_191 , 4, 'g', LTS_STATE_i_194 , LTS_STATE_i_193 , 3, 'o', LTS_STATE_i_196 , LTS_STATE_i_195 , 5, 'a', LTS_STATE_i_58 , LTS_STATE_i_197 , 5, 'a', LTS_STATE_i_199 , LTS_STATE_i_198 , 5, 'k', LTS_STATE_i_27 , LTS_STATE_i_200 , 2, '#', LTS_STATE_i_202 , LTS_STATE_i_201 , 4, 'n', LTS_STATE_i_204 , LTS_STATE_i_203 , 255, 2, 0,0 , 0,0 , 3, 'e', LTS_STATE_i_26 , LTS_STATE_i_205 , 4, 'v', LTS_STATE_i_36 , LTS_STATE_i_206 , 4, 'n', LTS_STATE_i_36 , LTS_STATE_i_207 , 2, 't', LTS_STATE_i_22 , LTS_STATE_i_36 , 3, 'g', LTS_STATE_i_209 , LTS_STATE_i_208 , 6, 'e', LTS_STATE_i_211 , LTS_STATE_i_210 , 6, 'i', LTS_STATE_i_19 , LTS_STATE_i_212 , 5, 'n', LTS_STATE_i_214 , LTS_STATE_i_213 , 2, 'n', LTS_STATE_i_36 , LTS_STATE_i_215 , 5, '#', LTS_STATE_i_19 , LTS_STATE_i_216 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_36 , 5, 'n', LTS_STATE_i_218 , LTS_STATE_i_217 , 3, 'v', LTS_STATE_i_36 , LTS_STATE_i_219 , 6, '#', LTS_STATE_i_221 , LTS_STATE_i_220 , 3, 'r', LTS_STATE_i_26 , LTS_STATE_i_222 , 3, 'l', LTS_STATE_i_224 , LTS_STATE_i_223 , 6, 'e', LTS_STATE_i_226 , LTS_STATE_i_225 , 3, 'l', LTS_STATE_i_105 , LTS_STATE_i_227 , 3, 's', LTS_STATE_i_19 , LTS_STATE_i_228 , 3, 'b', LTS_STATE_i_230 , LTS_STATE_i_229 , 6, 'e', LTS_STATE_i_26 , LTS_STATE_i_22 , 6, 'n', LTS_STATE_i_27 , LTS_STATE_i_231 , 5, '#', LTS_STATE_i_233 , LTS_STATE_i_232 , 2, 'a', LTS_STATE_i_105 , LTS_STATE_i_234 , 2, 'p', LTS_STATE_i_83 , LTS_STATE_i_19 , 3, 'l', LTS_STATE_i_236 , LTS_STATE_i_235 , 6, 't', LTS_STATE_i_19 , LTS_STATE_i_237 , 6, 'i', LTS_STATE_i_83 , LTS_STATE_i_238 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_239 , 2, 'k', LTS_STATE_i_27 , LTS_STATE_i_240 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_241 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_242 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_243 , 2, '#', LTS_STATE_i_245 , LTS_STATE_i_244 , 4, 's', LTS_STATE_i_247 , LTS_STATE_i_246 , 5, '#', LTS_STATE_i_249 , LTS_STATE_i_248 , 5, 'h', LTS_STATE_i_251 , LTS_STATE_i_250 , 5, 'a', LTS_STATE_i_253 , LTS_STATE_i_252 , 5, '#', LTS_STATE_i_157 , LTS_STATE_i_36 , 2, '#', LTS_STATE_i_255 , LTS_STATE_i_254 , 6, '#', LTS_STATE_i_257 , LTS_STATE_i_256 , 6, 't', LTS_STATE_i_259 , LTS_STATE_i_258 , 3, 'e', LTS_STATE_i_22 , LTS_STATE_i_260 , 3, 'e', LTS_STATE_i_262 , LTS_STATE_i_261 , 4, 'r', LTS_STATE_i_264 , LTS_STATE_i_263 , 4, 'c', LTS_STATE_i_266 , LTS_STATE_i_265 , 3, 'l', LTS_STATE_i_268 , LTS_STATE_i_267 , 3, 'd', LTS_STATE_i_270 , LTS_STATE_i_269 , 4, 's', LTS_STATE_i_271 , LTS_STATE_i_36 , 6, 'r', LTS_STATE_i_36 , LTS_STATE_i_272 , 3, 'o', LTS_STATE_i_105 , LTS_STATE_i_273 , 2, 'r', LTS_STATE_i_36 , LTS_STATE_i_274 , 2, 'g', LTS_STATE_i_19 , LTS_STATE_i_275 , 5, 'm', LTS_STATE_i_36 , LTS_STATE_i_19 , 5, 's', LTS_STATE_i_19 , LTS_STATE_i_276 , 3, 'h', LTS_STATE_i_22 , LTS_STATE_i_277 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_19 , 6, 's', LTS_STATE_i_36 , LTS_STATE_i_278 , 6, 'i', LTS_STATE_i_36 , LTS_STATE_i_19 , 5, 't', LTS_STATE_i_280 , LTS_STATE_i_279 , 2, 'f', LTS_STATE_i_36 , LTS_STATE_i_281 , 6, 'i', LTS_STATE_i_59 , LTS_STATE_i_19 , 2, 'f', LTS_STATE_i_26 , LTS_STATE_i_19 , 2, 'p', LTS_STATE_i_22 , LTS_STATE_i_282 , 6, 't', LTS_STATE_i_19 , LTS_STATE_i_283 , 2, 'i', LTS_STATE_i_19 , LTS_STATE_i_284 , 2, 'l', LTS_STATE_i_19 , LTS_STATE_i_22 , 2, 'n', LTS_STATE_i_19 , LTS_STATE_i_27 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_285 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_286 , 2, 'r', LTS_STATE_i_19 , LTS_STATE_i_287 , 5, 'n', LTS_STATE_i_289 , LTS_STATE_i_288 , 5, 'n', LTS_STATE_i_59 , LTS_STATE_i_26 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_290 , 3, 'a', LTS_STATE_i_22 , LTS_STATE_i_291 , 3, 'h', LTS_STATE_i_292 , LTS_STATE_i_19 , 3, 'n', LTS_STATE_i_105 , LTS_STATE_i_293 , 3, 'r', LTS_STATE_i_19 , LTS_STATE_i_294 , 2, 'g', LTS_STATE_i_19 , LTS_STATE_i_105 , 5, 'n', LTS_STATE_i_22 , LTS_STATE_i_295 , 3, 'b', LTS_STATE_i_83 , LTS_STATE_i_22 , 2, 'd', LTS_STATE_i_58 , LTS_STATE_i_296 , 6, 'u', LTS_STATE_i_27 , LTS_STATE_i_297 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_298 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_299 , 2, 'i', LTS_STATE_i_58 , LTS_STATE_i_296 , 2, '0', LTS_STATE_i_301 , LTS_STATE_i_300 , 4, 'g', LTS_STATE_i_303 , LTS_STATE_i_302 , 5, 'c', LTS_STATE_i_59 , LTS_STATE_i_36 , 5, '#', LTS_STATE_i_157 , LTS_STATE_i_304 , 2, 'r', LTS_STATE_i_306 , LTS_STATE_i_305 , 2, 'h', LTS_STATE_i_308 , LTS_STATE_i_307 , 5, 'n', LTS_STATE_i_310 , LTS_STATE_i_309 , 6, '#', LTS_STATE_i_36 , LTS_STATE_i_311 , 5, 'o', LTS_STATE_i_313 , LTS_STATE_i_312 , 3, 'e', LTS_STATE_i_36 , LTS_STATE_i_314 , 2, '0', LTS_STATE_i_22 , LTS_STATE_i_315 , 5, 'o', LTS_STATE_i_58 , LTS_STATE_i_36 , 3, 'e', LTS_STATE_i_22 , LTS_STATE_i_316 , 5, 'o', LTS_STATE_i_318 , LTS_STATE_i_317 , 6, 'l', LTS_STATE_i_320 , LTS_STATE_i_319 , 3, 'r', LTS_STATE_i_58 , LTS_STATE_i_321 , 5, 'h', LTS_STATE_i_323 , LTS_STATE_i_322 , 4, 'z', LTS_STATE_i_325 , LTS_STATE_i_324 , 6, 'd', LTS_STATE_i_36 , LTS_STATE_i_326 , 6, 's', LTS_STATE_i_328 , LTS_STATE_i_327 , 3, 'd', LTS_STATE_i_36 , LTS_STATE_i_329 , 4, 'l', LTS_STATE_i_331 , LTS_STATE_i_330 , 2, '#', LTS_STATE_i_22 , LTS_STATE_i_332 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_333 , 2, 'o', LTS_STATE_i_26 , LTS_STATE_i_334 , 2, 'o', LTS_STATE_i_336 , LTS_STATE_i_335 , 2, '#', LTS_STATE_i_337 , LTS_STATE_i_22 , 6, '#', LTS_STATE_i_338 , LTS_STATE_i_36 , 6, 'n', LTS_STATE_i_36 , LTS_STATE_i_339 , 3, 'n', LTS_STATE_i_341 , LTS_STATE_i_340 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_342 , 2, 'p', LTS_STATE_i_22 , LTS_STATE_i_343 , 6, '#', LTS_STATE_i_36 , LTS_STATE_i_344 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_345 , 5, '#', LTS_STATE_i_36 , LTS_STATE_i_346 , 6, 'l', LTS_STATE_i_19 , LTS_STATE_i_347 , 3, 'u', LTS_STATE_i_22 , LTS_STATE_i_348 , 3, 'c', LTS_STATE_i_350 , LTS_STATE_i_349 , 2, 'r', LTS_STATE_i_19 , LTS_STATE_i_351 , 6, 'c', LTS_STATE_i_19 , LTS_STATE_i_352 , 2, 'c', LTS_STATE_i_22 , LTS_STATE_i_19 , 2, 'i', LTS_STATE_i_19 , LTS_STATE_i_27 , 3, 'r', LTS_STATE_i_19 , LTS_STATE_i_27 , 3, 'r', LTS_STATE_i_19 , LTS_STATE_i_353 , 3, 'l', LTS_STATE_i_26 , LTS_STATE_i_354 , 3, 'v', LTS_STATE_i_19 , LTS_STATE_i_26 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_355 , 5, 't', LTS_STATE_i_19 , LTS_STATE_i_356 , 2, 'c', LTS_STATE_i_19 , LTS_STATE_i_22 , 6, 'a', LTS_STATE_i_105 , LTS_STATE_i_19 , 3, 'p', LTS_STATE_i_19 , LTS_STATE_i_357 , 5, 'c', LTS_STATE_i_22 , LTS_STATE_i_358 , 2, 'h', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 'a', LTS_STATE_i_58 , LTS_STATE_i_359 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_296 , 6, 'l', LTS_STATE_i_27 , LTS_STATE_i_360 , 5, 'a', LTS_STATE_i_362 , LTS_STATE_i_361 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_363 , 5, 'a', LTS_STATE_i_365 , LTS_STATE_i_364 , 5, 'h', LTS_STATE_i_22 , LTS_STATE_i_366 , 2, 'b', LTS_STATE_i_36 , LTS_STATE_i_367 , 6, '#', LTS_STATE_i_369 , LTS_STATE_i_368 , 4, 'n', LTS_STATE_i_371 , LTS_STATE_i_370 , 2, 't', LTS_STATE_i_373 , LTS_STATE_i_372 , 4, 's', LTS_STATE_i_83 , LTS_STATE_i_374 , 2, 'w', LTS_STATE_i_376 , LTS_STATE_i_375 , 6, 'i', LTS_STATE_i_58 , LTS_STATE_i_377 , 2, 'h', LTS_STATE_i_22 , LTS_STATE_i_36 , 5, 'r', LTS_STATE_i_379 , LTS_STATE_i_378 , 3, 'e', LTS_STATE_i_36 , LTS_STATE_i_380 , 3, 'p', LTS_STATE_i_382 , LTS_STATE_i_381 , 2, 'n', LTS_STATE_i_22 , LTS_STATE_i_383 , 5, 'i', LTS_STATE_i_385 , LTS_STATE_i_384 , 3, 'e', LTS_STATE_i_387 , LTS_STATE_i_386 , 3, 'r', LTS_STATE_i_26 , LTS_STATE_i_388 , 6, '#', LTS_STATE_i_58 , LTS_STATE_i_389 , 3, 'g', LTS_STATE_i_58 , LTS_STATE_i_390 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_391 , 3, 'b', LTS_STATE_i_22 , LTS_STATE_i_392 , 3, 'm', LTS_STATE_i_393 , LTS_STATE_i_27 , 6, 's', LTS_STATE_i_395 , LTS_STATE_i_394 , 6, 'n', LTS_STATE_i_59 , LTS_STATE_i_396 , 4, 't', LTS_STATE_i_397 , LTS_STATE_i_22 , 3, 'e', LTS_STATE_i_22 , LTS_STATE_i_398 , 4, 'g', LTS_STATE_i_83 , LTS_STATE_i_22 , 6, 'l', LTS_STATE_i_58 , LTS_STATE_i_22 , 4, 'r', LTS_STATE_i_22 , LTS_STATE_i_399 , 2, '#', LTS_STATE_i_22 , LTS_STATE_i_400 , 3, 'r', LTS_STATE_i_402 , LTS_STATE_i_401 , 2, '#', LTS_STATE_i_22 , LTS_STATE_i_403 , 2, 'a', LTS_STATE_i_26 , LTS_STATE_i_22 , 3, 'n', LTS_STATE_i_405 , LTS_STATE_i_404 , 6, 'r', LTS_STATE_i_19 , LTS_STATE_i_58 , 6, 's', LTS_STATE_i_83 , LTS_STATE_i_406 , 5, 'e', LTS_STATE_i_36 , LTS_STATE_i_27 , 4, 'd', LTS_STATE_i_22 , LTS_STATE_i_36 , 3, 'a', LTS_STATE_i_105 , LTS_STATE_i_407 , 6, 'u', LTS_STATE_i_19 , LTS_STATE_i_408 , 5, 'n', LTS_STATE_i_19 , LTS_STATE_i_409 , 2, 'e', LTS_STATE_i_411 , LTS_STATE_i_410 , 5, '#', LTS_STATE_i_413 , LTS_STATE_i_412 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_414 , 2, 'i', LTS_STATE_i_36 , LTS_STATE_i_19 , 5, 'u', LTS_STATE_i_416 , LTS_STATE_i_415 , 2, 'p', LTS_STATE_i_22 , LTS_STATE_i_417 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_418 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_419 , 2, 'a', LTS_STATE_i_19 , LTS_STATE_i_420 , 6, 'o', LTS_STATE_i_19 , LTS_STATE_i_26 , 3, 'z', LTS_STATE_i_19 , LTS_STATE_i_421 , 5, 't', LTS_STATE_i_423 , LTS_STATE_i_422 , 3, 'g', LTS_STATE_i_27 , LTS_STATE_i_424 , 2, 'i', LTS_STATE_i_426 , LTS_STATE_i_425 , 2, 's', LTS_STATE_i_36 , LTS_STATE_i_427 , 5, 't', LTS_STATE_i_22 , LTS_STATE_i_428 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_429 , 3, 't', LTS_STATE_i_430 , LTS_STATE_i_58 , 5, 'y', LTS_STATE_i_432 , LTS_STATE_i_431 , 6, '#', LTS_STATE_i_434 , LTS_STATE_i_433 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_435 , 5, 'o', LTS_STATE_i_437 , LTS_STATE_i_436 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_438 , 5, 'r', LTS_STATE_i_440 , LTS_STATE_i_439 , 2, 'a', LTS_STATE_i_27 , LTS_STATE_i_36 , 4, 'n', LTS_STATE_i_442 , LTS_STATE_i_441 , 4, 's', LTS_STATE_i_444 , LTS_STATE_i_443 , 6, 'u', LTS_STATE_i_59 , LTS_STATE_i_445 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_446 , 4, 'n', LTS_STATE_i_448 , LTS_STATE_i_447 , 4, 'n', LTS_STATE_i_83 , LTS_STATE_i_22 , 4, 't', LTS_STATE_i_83 , LTS_STATE_i_22 , 5, '#', LTS_STATE_i_26 , LTS_STATE_i_22 , 5, '#', LTS_STATE_i_83 , LTS_STATE_i_22 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_36 , 5, 'i', LTS_STATE_i_450 , LTS_STATE_i_449 , 2, '0', LTS_STATE_i_452 , LTS_STATE_i_451 , 6, '#', LTS_STATE_i_27 , LTS_STATE_i_453 , 6, '#', LTS_STATE_i_27 , LTS_STATE_i_454 , 2, '#', LTS_STATE_i_22 , LTS_STATE_i_455 , 5, 'o', LTS_STATE_i_36 , LTS_STATE_i_22 , 5, 'k', LTS_STATE_i_457 , LTS_STATE_i_456 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_458 , 5, 'i', LTS_STATE_i_26 , LTS_STATE_i_459 , 5, 'h', LTS_STATE_i_460 , LTS_STATE_i_26 , 3, 'n', LTS_STATE_i_26 , LTS_STATE_i_461 , 2, 'n', LTS_STATE_i_19 , LTS_STATE_i_462 , 2, 's', LTS_STATE_i_58 , LTS_STATE_i_463 , 3, 'd', LTS_STATE_i_464 , LTS_STATE_i_59 , 5, 't', LTS_STATE_i_466 , LTS_STATE_i_465 , 6, 'e', LTS_STATE_i_58 , LTS_STATE_i_27 , 2, '0', LTS_STATE_i_468 , LTS_STATE_i_467 , 4, 'n', LTS_STATE_i_470 , LTS_STATE_i_469 , 6, 'd', LTS_STATE_i_22 , LTS_STATE_i_471 , 6, 'r', LTS_STATE_i_472 , LTS_STATE_i_22 , 4, 'b', LTS_STATE_i_474 , LTS_STATE_i_473 , 3, 'e', LTS_STATE_i_476 , LTS_STATE_i_475 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_477 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_478 , 2, 'o', LTS_STATE_i_27 , LTS_STATE_i_22 , 2, 'a', LTS_STATE_i_26 , LTS_STATE_i_479 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_480 , 2, 'u', LTS_STATE_i_58 , LTS_STATE_i_22 , 6, 'r', LTS_STATE_i_83 , LTS_STATE_i_22 , 5, 'h', LTS_STATE_i_22 , LTS_STATE_i_481 , 2, 'e', LTS_STATE_i_482 , LTS_STATE_i_19 , 2, 'e', LTS_STATE_i_19 , LTS_STATE_i_36 , 5, 'r', LTS_STATE_i_105 , LTS_STATE_i_483 , 5, '#', LTS_STATE_i_19 , LTS_STATE_i_484 , 6, 's', LTS_STATE_i_36 , LTS_STATE_i_19 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_36 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_485 , 2, 'c', LTS_STATE_i_487 , LTS_STATE_i_486 , 6, '#', LTS_STATE_i_36 , LTS_STATE_i_19 , 6, 'y', LTS_STATE_i_22 , LTS_STATE_i_488 , 3, 'n', LTS_STATE_i_105 , LTS_STATE_i_489 , 2, 's', LTS_STATE_i_22 , LTS_STATE_i_19 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_490 , 2, 'l', LTS_STATE_i_19 , LTS_STATE_i_491 , 3, 's', LTS_STATE_i_26 , LTS_STATE_i_492 , 6, 'z', LTS_STATE_i_26 , LTS_STATE_i_493 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_494 , 3, 'c', LTS_STATE_i_413 , LTS_STATE_i_495 , 6, 'a', LTS_STATE_i_36 , LTS_STATE_i_19 , 3, 'g', LTS_STATE_i_36 , LTS_STATE_i_496 , 3, 'r', LTS_STATE_i_19 , LTS_STATE_i_497 , 6, 't', LTS_STATE_i_58 , LTS_STATE_i_498 , 6, 's', LTS_STATE_i_58 , LTS_STATE_i_27 , 5, 'h', LTS_STATE_i_500 , LTS_STATE_i_499 , 4, 'n', LTS_STATE_i_501 , LTS_STATE_i_59 , 6, 't', LTS_STATE_i_503 , LTS_STATE_i_502 , 4, 'k', LTS_STATE_i_58 , LTS_STATE_i_504 , 5, 'o', LTS_STATE_i_22 , LTS_STATE_i_505 , 4, 'u', LTS_STATE_i_140 , LTS_STATE_i_506 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_507 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_508 , 6, '#', LTS_STATE_i_510 , LTS_STATE_i_509 , 6, 'e', LTS_STATE_i_83 , LTS_STATE_i_22 , 5, 't', LTS_STATE_i_73 , LTS_STATE_i_511 , 6, 't', LTS_STATE_i_59 , LTS_STATE_i_22 , 2, 'h', LTS_STATE_i_22 , LTS_STATE_i_512 , 5, 't', LTS_STATE_i_59 , LTS_STATE_i_513 , 6, '#', LTS_STATE_i_514 , LTS_STATE_i_22 , 5, 'f', LTS_STATE_i_27 , LTS_STATE_i_515 , 2, 'f', LTS_STATE_i_22 , LTS_STATE_i_516 , 2, 'r', LTS_STATE_i_36 , LTS_STATE_i_517 , 5, '#', LTS_STATE_i_519 , LTS_STATE_i_518 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_520 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_36 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'l', LTS_STATE_i_58 , LTS_STATE_i_521 , 2, 'd', LTS_STATE_i_36 , LTS_STATE_i_522 , 6, 't', LTS_STATE_i_36 , LTS_STATE_i_22 , 5, 't', LTS_STATE_i_524 , LTS_STATE_i_523 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_525 , 6, 'z', LTS_STATE_i_59 , LTS_STATE_i_526 , 5, 's', LTS_STATE_i_58 , LTS_STATE_i_527 , 2, 'r', LTS_STATE_i_83 , LTS_STATE_i_22 , 3, 't', LTS_STATE_i_58 , LTS_STATE_i_26 , 3, 'r', LTS_STATE_i_529 , LTS_STATE_i_528 , 3, 'd', LTS_STATE_i_531 , LTS_STATE_i_530 , 2, 'n', LTS_STATE_i_59 , LTS_STATE_i_532 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_533 , 6, 'o', LTS_STATE_i_58 , LTS_STATE_i_27 , 4, 'g', LTS_STATE_i_535 , LTS_STATE_i_534 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_536 , 4, 'g', LTS_STATE_i_58 , LTS_STATE_i_537 , 3, 's', LTS_STATE_i_539 , LTS_STATE_i_538 , 6, 's', LTS_STATE_i_22 , LTS_STATE_i_540 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 't', LTS_STATE_i_22 , LTS_STATE_i_541 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_542 , 3, 'u', LTS_STATE_i_544 , LTS_STATE_i_543 , 4, 'd', LTS_STATE_i_22 , LTS_STATE_i_26 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_545 , 2, 's', LTS_STATE_i_547 , LTS_STATE_i_546 , 3, 't', LTS_STATE_i_26 , LTS_STATE_i_548 , 6, 's', LTS_STATE_i_550 , LTS_STATE_i_549 , 5, 's', LTS_STATE_i_552 , LTS_STATE_i_551 , 6, '#', LTS_STATE_i_553 , LTS_STATE_i_19 , 6, 's', LTS_STATE_i_105 , LTS_STATE_i_554 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_22 , 5, 'l', LTS_STATE_i_19 , LTS_STATE_i_555 , 2, 'a', LTS_STATE_i_557 , LTS_STATE_i_556 , 6, '#', LTS_STATE_i_59 , LTS_STATE_i_26 , 3, 't', LTS_STATE_i_19 , LTS_STATE_i_558 , 2, 'b', LTS_STATE_i_22 , LTS_STATE_i_559 , 2, 'l', LTS_STATE_i_19 , LTS_STATE_i_560 , 2, 'a', LTS_STATE_i_562 , LTS_STATE_i_561 , 6, 'h', LTS_STATE_i_564 , LTS_STATE_i_563 , 3, 'v', LTS_STATE_i_19 , LTS_STATE_i_565 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_26 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_19 , 3, 'z', LTS_STATE_i_19 , LTS_STATE_i_566 , 6, 'i', LTS_STATE_i_22 , LTS_STATE_i_61 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_567 , 5, 'o', LTS_STATE_i_569 , LTS_STATE_i_568 , 4, 'g', LTS_STATE_i_22 , LTS_STATE_i_570 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_27 , 4, 'g', LTS_STATE_i_572 , LTS_STATE_i_571 , 4, 'v', LTS_STATE_i_574 , LTS_STATE_i_573 , 4, 'l', LTS_STATE_i_575 , LTS_STATE_i_26 , 5, 'a', LTS_STATE_i_577 , LTS_STATE_i_576 , 5, 'i', LTS_STATE_i_579 , LTS_STATE_i_578 , 4, 'k', LTS_STATE_i_58 , LTS_STATE_i_580 , 4, 'y', LTS_STATE_i_26 , LTS_STATE_i_581 , 5, 'u', LTS_STATE_i_583 , LTS_STATE_i_582 , 5, 's', LTS_STATE_i_27 , LTS_STATE_i_26 , 2, 'c', LTS_STATE_i_26 , LTS_STATE_i_584 , 4, 'n', LTS_STATE_i_26 , LTS_STATE_i_585 , 5, 's', LTS_STATE_i_22 , LTS_STATE_i_27 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_26 , 5, 'i', LTS_STATE_i_22 , LTS_STATE_i_586 , 2, 'b', LTS_STATE_i_83 , LTS_STATE_i_587 , 2, 'b', LTS_STATE_i_83 , LTS_STATE_i_22 , 5, 'u', LTS_STATE_i_589 , LTS_STATE_i_588 , 3, 'e', LTS_STATE_i_27 , LTS_STATE_i_590 , 2, '0', LTS_STATE_i_22 , LTS_STATE_i_591 , 2, '#', LTS_STATE_i_592 , LTS_STATE_i_22 , 2, '#', LTS_STATE_i_594 , LTS_STATE_i_593 , 6, 'i', LTS_STATE_i_596 , LTS_STATE_i_595 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_597 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_598 , 6, 'd', LTS_STATE_i_59 , LTS_STATE_i_599 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_600 , 3, 'h', LTS_STATE_i_58 , LTS_STATE_i_601 , 2, 'f', LTS_STATE_i_58 , LTS_STATE_i_59 , 2, 'c', LTS_STATE_i_603 , LTS_STATE_i_602 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_58 , 2, 'u', LTS_STATE_i_58 , LTS_STATE_i_59 , 5, 'c', LTS_STATE_i_605 , LTS_STATE_i_604 , 6, 'n', LTS_STATE_i_607 , LTS_STATE_i_606 , 6, 'n', LTS_STATE_i_609 , LTS_STATE_i_608 , 4, 'd', LTS_STATE_i_611 , LTS_STATE_i_610 , 4, 'l', LTS_STATE_i_613 , LTS_STATE_i_612 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_614 , 2, 'u', LTS_STATE_i_36 , LTS_STATE_i_19 , 6, 'r', LTS_STATE_i_22 , LTS_STATE_i_27 , 6, 'r', LTS_STATE_i_616 , LTS_STATE_i_615 , 6, 'r', LTS_STATE_i_27 , LTS_STATE_i_617 , 4, 't', LTS_STATE_i_619 , LTS_STATE_i_618 , 4, 's', LTS_STATE_i_36 , LTS_STATE_i_22 , 3, 's', LTS_STATE_i_59 , LTS_STATE_i_620 , 2, 'n', LTS_STATE_i_59 , LTS_STATE_i_621 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_22 , 2, 's', LTS_STATE_i_22 , LTS_STATE_i_622 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_623 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'f', LTS_STATE_i_625 , LTS_STATE_i_624 , 6, '#', LTS_STATE_i_626 , LTS_STATE_i_22 , 5, 'n', LTS_STATE_i_19 , LTS_STATE_i_105 , 6, 'i', LTS_STATE_i_19 , LTS_STATE_i_627 , 3, 'l', LTS_STATE_i_22 , LTS_STATE_i_19 , 6, '#', LTS_STATE_i_629 , LTS_STATE_i_628 , 3, 'n', LTS_STATE_i_105 , LTS_STATE_i_630 , 6, 't', LTS_STATE_i_19 , LTS_STATE_i_631 , 3, 'l', LTS_STATE_i_19 , LTS_STATE_i_632 , 2, 'n', LTS_STATE_i_19 , LTS_STATE_i_633 , 2, 't', LTS_STATE_i_19 , LTS_STATE_i_634 , 3, 'n', LTS_STATE_i_19 , LTS_STATE_i_635 , 6, 'b', LTS_STATE_i_19 , LTS_STATE_i_26 , 3, 'p', LTS_STATE_i_19 , LTS_STATE_i_26 , 6, 'r', LTS_STATE_i_26 , LTS_STATE_i_636 , 3, 'c', LTS_STATE_i_638 , LTS_STATE_i_637 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_639 , 4, 'u', LTS_STATE_i_641 , LTS_STATE_i_640 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_642 , 4, 's', LTS_STATE_i_644 , LTS_STATE_i_643 , 4, 'v', LTS_STATE_i_646 , LTS_STATE_i_645 , 6, 'n', LTS_STATE_i_58 , LTS_STATE_i_647 , 2, 'c', LTS_STATE_i_648 , LTS_STATE_i_59 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_649 , 3, 'u', LTS_STATE_i_26 , LTS_STATE_i_650 , 5, 'l', LTS_STATE_i_652 , LTS_STATE_i_651 , 6, 'l', LTS_STATE_i_59 , LTS_STATE_i_653 , 5, 'd', LTS_STATE_i_655 , LTS_STATE_i_654 , 6, 'n', LTS_STATE_i_657 , LTS_STATE_i_656 , 4, 'v', LTS_STATE_i_58 , LTS_STATE_i_658 , 6, 't', LTS_STATE_i_660 , LTS_STATE_i_659 , 6, 'e', LTS_STATE_i_27 , LTS_STATE_i_661 , 6, 'r', LTS_STATE_i_27 , LTS_STATE_i_19 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_662 , 5, 'y', LTS_STATE_i_59 , LTS_STATE_i_663 , 5, 'v', LTS_STATE_i_27 , LTS_STATE_i_664 , 4, 'l', LTS_STATE_i_26 , LTS_STATE_i_665 , 3, 'e', LTS_STATE_i_667 , LTS_STATE_i_666 , 6, 's', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_668 , 6, 'c', LTS_STATE_i_22 , LTS_STATE_i_669 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_58 , 2, 'e', LTS_STATE_i_22 , LTS_STATE_i_670 , 6, 'd', LTS_STATE_i_83 , LTS_STATE_i_671 , 5, 'o', LTS_STATE_i_673 , LTS_STATE_i_672 , 5, 'h', LTS_STATE_i_26 , LTS_STATE_i_58 , 6, 's', LTS_STATE_i_674 , LTS_STATE_i_27 , 6, 's', LTS_STATE_i_676 , LTS_STATE_i_675 , 6, 'n', LTS_STATE_i_678 , LTS_STATE_i_677 , 2, 's', LTS_STATE_i_680 , LTS_STATE_i_679 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_681 , 3, 'm', LTS_STATE_i_682 , LTS_STATE_i_58 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_58 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_683 , 6, 'i', LTS_STATE_i_19 , LTS_STATE_i_27 , 6, 'd', LTS_STATE_i_685 , LTS_STATE_i_684 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_686 , 2, 's', LTS_STATE_i_688 , LTS_STATE_i_687 , 3, 'l', LTS_STATE_i_59 , LTS_STATE_i_689 , 4, 'r', LTS_STATE_i_58 , LTS_STATE_i_690 , 6, 'o', LTS_STATE_i_22 , LTS_STATE_i_83 , 4, 'c', LTS_STATE_i_547 , LTS_STATE_i_691 , 2, 'o', LTS_STATE_i_26 , LTS_STATE_i_22 , 3, 'g', LTS_STATE_i_59 , LTS_STATE_i_692 , 3, 'l', LTS_STATE_i_694 , LTS_STATE_i_693 , 3, 'n', LTS_STATE_i_83 , LTS_STATE_i_695 , 6, 'l', LTS_STATE_i_22 , LTS_STATE_i_27 , 4, 's', LTS_STATE_i_697 , LTS_STATE_i_696 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_698 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_699 , 3, 'v', LTS_STATE_i_59 , LTS_STATE_i_700 , 2, 'o', LTS_STATE_i_26 , LTS_STATE_i_701 , 2, '0', LTS_STATE_i_22 , LTS_STATE_i_702 , 2, 't', LTS_STATE_i_704 , LTS_STATE_i_703 , 2, 'i', LTS_STATE_i_22 , LTS_STATE_i_19 , 3, 'r', LTS_STATE_i_26 , LTS_STATE_i_19 , 2, 'l', LTS_STATE_i_705 , LTS_STATE_i_19 , 5, 'v', LTS_STATE_i_26 , LTS_STATE_i_706 , 5, 'f', LTS_STATE_i_26 , LTS_STATE_i_707 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_26 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_708 , 6, 't', LTS_STATE_i_19 , LTS_STATE_i_709 , 2, 'e', LTS_STATE_i_19 , LTS_STATE_i_710 , 3, 'v', LTS_STATE_i_19 , LTS_STATE_i_711 , 3, 'v', LTS_STATE_i_105 , LTS_STATE_i_19 , 3, 'p', LTS_STATE_i_22 , LTS_STATE_i_26 , 3, 'x', LTS_STATE_i_36 , LTS_STATE_i_19 , 6, 'a', LTS_STATE_i_19 , LTS_STATE_i_36 , 2, 'm', LTS_STATE_i_58 , LTS_STATE_i_712 , 6, 'n', LTS_STATE_i_714 , LTS_STATE_i_713 , 6, '#', LTS_STATE_i_19 , LTS_STATE_i_715 , 4, 'k', LTS_STATE_i_58 , LTS_STATE_i_716 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_717 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_718 , 6, 's', LTS_STATE_i_720 , LTS_STATE_i_719 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_721 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_531 , 4, 'n', LTS_STATE_i_59 , LTS_STATE_i_22 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_722 , 2, 'a', LTS_STATE_i_27 , LTS_STATE_i_26 , 4, 'g', LTS_STATE_i_724 , LTS_STATE_i_723 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_725 , 6, 'n', LTS_STATE_i_727 , LTS_STATE_i_726 , 5, 'u', LTS_STATE_i_729 , LTS_STATE_i_728 , 4, 'd', LTS_STATE_i_27 , LTS_STATE_i_730 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_731 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_732 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_733 , 6, 'r', LTS_STATE_i_735 , LTS_STATE_i_734 , 4, 'l', LTS_STATE_i_83 , LTS_STATE_i_27 , 5, 'a', LTS_STATE_i_737 , LTS_STATE_i_736 , 2, 'f', LTS_STATE_i_59 , LTS_STATE_i_738 , 4, 't', LTS_STATE_i_26 , LTS_STATE_i_739 , 6, 'e', LTS_STATE_i_741 , LTS_STATE_i_740 , 2, 'r', LTS_STATE_i_26 , LTS_STATE_i_514 , 5, 'y', LTS_STATE_i_22 , LTS_STATE_i_36 , 2, 'w', LTS_STATE_i_27 , LTS_STATE_i_36 , 2, 'a', LTS_STATE_i_36 , LTS_STATE_i_742 , 6, 'l', LTS_STATE_i_58 , LTS_STATE_i_743 , 3, 'h', LTS_STATE_i_58 , LTS_STATE_i_744 , 3, 'g', LTS_STATE_i_36 , LTS_STATE_i_745 , 6, 'l', LTS_STATE_i_747 , LTS_STATE_i_746 , 2, '0', LTS_STATE_i_22 , LTS_STATE_i_748 , 3, 'd', LTS_STATE_i_58 , LTS_STATE_i_27 , 2, 'i', LTS_STATE_i_58 , LTS_STATE_i_749 , 2, 'd', LTS_STATE_i_58 , LTS_STATE_i_750 , 2, 'e', LTS_STATE_i_752 , LTS_STATE_i_751 , 3, 'd', LTS_STATE_i_59 , LTS_STATE_i_22 , 3, 'w', LTS_STATE_i_754 , LTS_STATE_i_753 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'b', LTS_STATE_i_27 , LTS_STATE_i_755 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_58 , 5, 'i', LTS_STATE_i_27 , LTS_STATE_i_756 , 2, 'w', LTS_STATE_i_22 , LTS_STATE_i_757 , 4, 't', LTS_STATE_i_759 , LTS_STATE_i_758 , 2, 'w', LTS_STATE_i_22 , LTS_STATE_i_760 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'r', LTS_STATE_i_22 , LTS_STATE_i_58 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_59 , 4, 'k', LTS_STATE_i_22 , LTS_STATE_i_761 , 4, 'f', LTS_STATE_i_59 , LTS_STATE_i_762 , 3, 'l', LTS_STATE_i_22 , LTS_STATE_i_763 , 4, 'p', LTS_STATE_i_22 , LTS_STATE_i_764 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_765 , 4, 't', LTS_STATE_i_27 , LTS_STATE_i_766 , 4, 'g', LTS_STATE_i_58 , LTS_STATE_i_22 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_767 , 2, 'e', LTS_STATE_i_22 , LTS_STATE_i_768 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_460 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_769 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_770 , 6, 'a', LTS_STATE_i_58 , LTS_STATE_i_771 , 3, 'e', LTS_STATE_i_36 , LTS_STATE_i_772 , 5, '#', LTS_STATE_i_19 , LTS_STATE_i_773 , 6, '#', LTS_STATE_i_775 , LTS_STATE_i_774 , 6, 'a', LTS_STATE_i_26 , LTS_STATE_i_776 , 2, 't', LTS_STATE_i_26 , LTS_STATE_i_777 , 3, 'p', LTS_STATE_i_26 , LTS_STATE_i_778 , 6, 'c', LTS_STATE_i_19 , LTS_STATE_i_779 , 2, 'f', LTS_STATE_i_19 , LTS_STATE_i_780 , 2, 'p', LTS_STATE_i_19 , LTS_STATE_i_781 , 3, 'd', LTS_STATE_i_58 , LTS_STATE_i_782 , 4, 'k', LTS_STATE_i_784 , LTS_STATE_i_783 , 4, 'z', LTS_STATE_i_22 , LTS_STATE_i_785 , 6, 'p', LTS_STATE_i_22 , LTS_STATE_i_216 , 6, 's', LTS_STATE_i_787 , LTS_STATE_i_786 , 6, 'o', LTS_STATE_i_59 , LTS_STATE_i_788 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_789 , 4, 'k', LTS_STATE_i_791 , LTS_STATE_i_790 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_26 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_792 , 2, 'c', LTS_STATE_i_59 , LTS_STATE_i_58 , 4, 's', LTS_STATE_i_793 , LTS_STATE_i_27 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'e', LTS_STATE_i_22 , LTS_STATE_i_794 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_795 , 4, 'v', LTS_STATE_i_22 , LTS_STATE_i_58 , 3, 'v', LTS_STATE_i_797 , LTS_STATE_i_796 , 4, 'l', LTS_STATE_i_59 , LTS_STATE_i_798 , 4, 'l', LTS_STATE_i_800 , LTS_STATE_i_799 , 4, 'v', LTS_STATE_i_674 , LTS_STATE_i_801 , 4, 'v', LTS_STATE_i_674 , LTS_STATE_i_802 , 3, 's', LTS_STATE_i_804 , LTS_STATE_i_803 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_805 , 3, 'b', LTS_STATE_i_83 , LTS_STATE_i_806 , 5, 'n', LTS_STATE_i_808 , LTS_STATE_i_807 , 3, 'g', LTS_STATE_i_27 , LTS_STATE_i_809 , 2, 'v', LTS_STATE_i_36 , LTS_STATE_i_810 , 2, 'n', LTS_STATE_i_26 , LTS_STATE_i_811 , 5, 'c', LTS_STATE_i_27 , LTS_STATE_i_812 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_36 , 3, 'h', LTS_STATE_i_36 , LTS_STATE_i_27 , 2, '#', LTS_STATE_i_27 , LTS_STATE_i_813 , 2, '0', LTS_STATE_i_58 , LTS_STATE_i_22 , 3, 'm', LTS_STATE_i_815 , LTS_STATE_i_814 , 5, 'h', LTS_STATE_i_817 , LTS_STATE_i_816 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_818 , 3, 't', LTS_STATE_i_19 , LTS_STATE_i_819 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_820 , 2, 'n', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_821 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_822 , 5, 'k', LTS_STATE_i_823 , LTS_STATE_i_58 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_824 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_825 , 6, 'r', LTS_STATE_i_827 , LTS_STATE_i_826 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_828 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_829 , 3, 'r', LTS_STATE_i_831 , LTS_STATE_i_830 , 6, 'n', LTS_STATE_i_27 , LTS_STATE_i_832 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_833 , 3, 'b', LTS_STATE_i_22 , LTS_STATE_i_834 , 4, 'l', LTS_STATE_i_836 , LTS_STATE_i_835 , 4, 'c', LTS_STATE_i_22 , LTS_STATE_i_837 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_804 , 3, 'm', LTS_STATE_i_22 , LTS_STATE_i_838 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_460 , 2, 'i', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'b', LTS_STATE_i_22 , LTS_STATE_i_839 , 6, 't', LTS_STATE_i_27 , LTS_STATE_i_840 , 3, 'h', LTS_STATE_i_19 , LTS_STATE_i_841 , 5, 'n', LTS_STATE_i_19 , LTS_STATE_i_842 , 6, 't', LTS_STATE_i_105 , LTS_STATE_i_19 , 5, 'm', LTS_STATE_i_105 , LTS_STATE_i_19 , 5, 'b', LTS_STATE_i_26 , LTS_STATE_i_843 , 2, 's', LTS_STATE_i_26 , LTS_STATE_i_626 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_26 , 6, 'n', LTS_STATE_i_19 , LTS_STATE_i_630 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_19 , 3, 'd', LTS_STATE_i_19 , LTS_STATE_i_844 , 3, 'n', LTS_STATE_i_58 , LTS_STATE_i_845 , 4, 'g', LTS_STATE_i_847 , LTS_STATE_i_846 , 5, 'i', LTS_STATE_i_26 , LTS_STATE_i_58 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_848 , 4, 'g', LTS_STATE_i_850 , LTS_STATE_i_849 , 4, 't', LTS_STATE_i_26 , LTS_STATE_i_851 , 6, 'e', LTS_STATE_i_853 , LTS_STATE_i_852 , 6, '#', LTS_STATE_i_855 , LTS_STATE_i_854 , 6, 'l', LTS_STATE_i_857 , LTS_STATE_i_856 , 6, 'w', LTS_STATE_i_19 , LTS_STATE_i_858 , 3, 'n', LTS_STATE_i_58 , LTS_STATE_i_859 , 6, 'i', LTS_STATE_i_860 , LTS_STATE_i_27 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_22 , 6, 'r', LTS_STATE_i_27 , LTS_STATE_i_22 , 5, 'r', LTS_STATE_i_862 , LTS_STATE_i_861 , 4, 'b', LTS_STATE_i_22 , LTS_STATE_i_863 , 6, 's', LTS_STATE_i_865 , LTS_STATE_i_864 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_866 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_27 , 4, 'p', LTS_STATE_i_19 , LTS_STATE_i_27 , 4, 'm', LTS_STATE_i_867 , LTS_STATE_i_22 , 6, 'r', LTS_STATE_i_869 , LTS_STATE_i_868 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'd', LTS_STATE_i_871 , LTS_STATE_i_870 , 4, 'l', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_873 , LTS_STATE_i_872 , 3, 's', LTS_STATE_i_875 , LTS_STATE_i_874 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_876 , 6, 'h', LTS_STATE_i_36 , LTS_STATE_i_877 , 5, 'a', LTS_STATE_i_26 , LTS_STATE_i_878 , 5, 's', LTS_STATE_i_27 , LTS_STATE_i_879 , 6, '#', LTS_STATE_i_27 , LTS_STATE_i_880 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'b', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 'e', LTS_STATE_i_882 , LTS_STATE_i_881 , 2, 'c', LTS_STATE_i_884 , LTS_STATE_i_883 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_885 , 3, 'n', LTS_STATE_i_876 , LTS_STATE_i_886 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_887 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_888 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_889 , 2, 'd', LTS_STATE_i_58 , LTS_STATE_i_890 , 6, 'n', LTS_STATE_i_891 , LTS_STATE_i_682 , 5, 'a', LTS_STATE_i_893 , LTS_STATE_i_892 , 4, 'r', LTS_STATE_i_895 , LTS_STATE_i_894 , 4, 'k', LTS_STATE_i_58 , LTS_STATE_i_896 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_897 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_22 , 4, 'd', LTS_STATE_i_899 , LTS_STATE_i_898 , 2, 'b', LTS_STATE_i_27 , LTS_STATE_i_22 , 4, 'c', LTS_STATE_i_22 , LTS_STATE_i_900 , 2, 'i', LTS_STATE_i_901 , LTS_STATE_i_22 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_902 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_903 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_904 , 4, 'f', LTS_STATE_i_22 , LTS_STATE_i_905 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_906 , 3, 'd', LTS_STATE_i_908 , LTS_STATE_i_907 , 2, 'd', LTS_STATE_i_22 , LTS_STATE_i_909 , 5, '#', LTS_STATE_i_19 , LTS_STATE_i_910 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_911 , 5, 'f', LTS_STATE_i_26 , LTS_STATE_i_912 , 2, 'e', LTS_STATE_i_19 , LTS_STATE_i_913 , 6, 'l', LTS_STATE_i_58 , LTS_STATE_i_914 , 5, 'd', LTS_STATE_i_916 , LTS_STATE_i_915 , 5, '#', LTS_STATE_i_918 , LTS_STATE_i_917 , 4, 'g', LTS_STATE_i_27 , LTS_STATE_i_919 , 4, 'v', LTS_STATE_i_921 , LTS_STATE_i_920 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_922 , 3, 'h', LTS_STATE_i_59 , LTS_STATE_i_923 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_924 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'r', LTS_STATE_i_926 , LTS_STATE_i_925 , 3, 'k', LTS_STATE_i_58 , LTS_STATE_i_927 , 6, 'b', LTS_STATE_i_929 , LTS_STATE_i_928 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_930 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_58 , 6, 'r', LTS_STATE_i_19 , LTS_STATE_i_931 , 5, 'h', LTS_STATE_i_58 , LTS_STATE_i_27 , 5, 'l', LTS_STATE_i_933 , LTS_STATE_i_932 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_934 , 6, 'a', LTS_STATE_i_936 , LTS_STATE_i_935 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_937 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'm', LTS_STATE_i_939 , LTS_STATE_i_938 , 3, 'd', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'b', LTS_STATE_i_59 , LTS_STATE_i_940 , 4, 'm', LTS_STATE_i_83 , LTS_STATE_i_941 , 3, 'm', LTS_STATE_i_943 , LTS_STATE_i_942 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_59 , 5, 'l', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 't', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_944 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_945 , 6, 'l', LTS_STATE_i_19 , LTS_STATE_i_58 , 2, 'h', LTS_STATE_i_22 , LTS_STATE_i_946 , 4, 'l', LTS_STATE_i_22 , LTS_STATE_i_36 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_22 , 2, 'a', LTS_STATE_i_36 , LTS_STATE_i_27 , 5, 'y', LTS_STATE_i_59 , LTS_STATE_i_947 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_948 , 6, 'o', LTS_STATE_i_59 , LTS_STATE_i_949 , 6, 'e', LTS_STATE_i_19 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'p', LTS_STATE_i_59 , LTS_STATE_i_950 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_951 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_952 , 2, 'h', LTS_STATE_i_860 , LTS_STATE_i_58 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_58 , 3, 'f', LTS_STATE_i_58 , LTS_STATE_i_953 , 6, 'n', LTS_STATE_i_27 , LTS_STATE_i_954 , 3, 'r', LTS_STATE_i_58 , LTS_STATE_i_955 , 6, 'k', LTS_STATE_i_957 , LTS_STATE_i_956 , 3, 'd', LTS_STATE_i_36 , LTS_STATE_i_958 , 4, 't', LTS_STATE_i_960 , LTS_STATE_i_959 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_961 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_59 , 2, 'i', LTS_STATE_i_83 , LTS_STATE_i_59 , 4, 't', LTS_STATE_i_22 , LTS_STATE_i_540 , 3, 'c', LTS_STATE_i_22 , LTS_STATE_i_59 , 2, 'r', LTS_STATE_i_26 , LTS_STATE_i_962 , 3, 's', LTS_STATE_i_964 , LTS_STATE_i_963 , 6, 'y', LTS_STATE_i_22 , LTS_STATE_i_965 , 4, 'k', LTS_STATE_i_22 , LTS_STATE_i_939 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_966 , 2, 'l', LTS_STATE_i_22 , LTS_STATE_i_967 , 2, 'n', LTS_STATE_i_22 , LTS_STATE_i_26 , 6, 'r', LTS_STATE_i_969 , LTS_STATE_i_968 , 2, 'b', LTS_STATE_i_19 , LTS_STATE_i_970 , 6, 's', LTS_STATE_i_22 , LTS_STATE_i_19 , 2, 'y', LTS_STATE_i_26 , LTS_STATE_i_971 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_972 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_973 , 5, 'i', LTS_STATE_i_975 , LTS_STATE_i_974 , 6, 'a', LTS_STATE_i_977 , LTS_STATE_i_976 , 5, 'n', LTS_STATE_i_979 , LTS_STATE_i_978 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_980 , 5, 'i', LTS_STATE_i_982 , LTS_STATE_i_981 , 6, 'r', LTS_STATE_i_984 , LTS_STATE_i_983 , 2, 'r', LTS_STATE_i_22 , LTS_STATE_i_27 , 2, 'g', LTS_STATE_i_58 , LTS_STATE_i_985 , 4, 'n', LTS_STATE_i_26 , LTS_STATE_i_59 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_27 , 6, 'm', LTS_STATE_i_58 , LTS_STATE_i_986 , 6, 'e', LTS_STATE_i_58 , LTS_STATE_i_987 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_988 , 6, 'n', LTS_STATE_i_990 , LTS_STATE_i_989 , 2, 's', LTS_STATE_i_36 , LTS_STATE_i_991 , 2, 's', LTS_STATE_i_59 , LTS_STATE_i_992 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_27 , 4, 'k', LTS_STATE_i_393 , LTS_STATE_i_993 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_994 , 3, 'c', LTS_STATE_i_27 , LTS_STATE_i_995 , 5, 'c', LTS_STATE_i_996 , LTS_STATE_i_27 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_997 , 6, 'l', LTS_STATE_i_58 , LTS_STATE_i_998 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_999 , 4, 'n', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_939 , LTS_STATE_i_1000 , 3, 'm', LTS_STATE_i_22 , LTS_STATE_i_59 , 6, 'l', LTS_STATE_i_1002 , LTS_STATE_i_1001 , 6, 's', LTS_STATE_i_22 , LTS_STATE_i_1003 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_19 , 6, 'i', LTS_STATE_i_58 , LTS_STATE_i_22 , 5, 'z', LTS_STATE_i_22 , LTS_STATE_i_1004 , 3, 'm', LTS_STATE_i_26 , LTS_STATE_i_1005 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_58 , 3, 'm', LTS_STATE_i_58 , LTS_STATE_i_1006 , 6, 'n', LTS_STATE_i_1007 , LTS_STATE_i_58 , 2, 'q', LTS_STATE_i_27 , LTS_STATE_i_1008 , 6, 'p', LTS_STATE_i_27 , LTS_STATE_i_1009 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_1010 , 6, 'r', LTS_STATE_i_22 , LTS_STATE_i_1011 , 6, 'r', LTS_STATE_i_58 , LTS_STATE_i_1012 , 6, 'z', LTS_STATE_i_26 , LTS_STATE_i_1013 , 4, 'c', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 'm', LTS_STATE_i_22 , LTS_STATE_i_1014 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1015 , 3, 'l', LTS_STATE_i_1017 , LTS_STATE_i_1016 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1018 , 3, 'd', LTS_STATE_i_19 , LTS_STATE_i_1019 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1020 , 4, 'd', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_867 , 2, 'e', LTS_STATE_i_83 , LTS_STATE_i_22 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_1021 , 6, 'n', LTS_STATE_i_1023 , LTS_STATE_i_1022 , 2, '#', LTS_STATE_i_27 , LTS_STATE_i_1024 , 2, '0', LTS_STATE_i_1025 , LTS_STATE_i_19 , 5, 'c', LTS_STATE_i_26 , LTS_STATE_i_1026 , 2, 'i', LTS_STATE_i_19 , LTS_STATE_i_1027 , 2, 'a', LTS_STATE_i_58 , LTS_STATE_i_1028 , 4, 'x', LTS_STATE_i_58 , LTS_STATE_i_1029 , 6, '#', LTS_STATE_i_26 , LTS_STATE_i_1030 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_1031 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_1032 , 5, 'r', LTS_STATE_i_59 , LTS_STATE_i_1033 , 6, 'o', LTS_STATE_i_1035 , LTS_STATE_i_1034 , 2, 'n', LTS_STATE_i_58 , LTS_STATE_i_1036 , 5, 'u', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'u', LTS_STATE_i_1038 , LTS_STATE_i_1037 , 4, 's', LTS_STATE_i_1040 , LTS_STATE_i_1039 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_1041 , 6, 't', LTS_STATE_i_59 , LTS_STATE_i_858 , 3, 'd', LTS_STATE_i_58 , LTS_STATE_i_1042 , 6, 'm', LTS_STATE_i_27 , LTS_STATE_i_58 , 2, 'o', LTS_STATE_i_58 , LTS_STATE_i_1043 , 2, 'l', LTS_STATE_i_1045 , LTS_STATE_i_1044 , 2, 'a', LTS_STATE_i_1047 , LTS_STATE_i_1046 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_1048 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1049 , 3, 'd', LTS_STATE_i_1051 , LTS_STATE_i_1050 , 6, 'e', LTS_STATE_i_1053 , LTS_STATE_i_1052 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1054 , 6, 'e', LTS_STATE_i_27 , LTS_STATE_i_19 , 5, 'l', LTS_STATE_i_19 , LTS_STATE_i_27 , 4, 'q', LTS_STATE_i_452 , LTS_STATE_i_1055 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_1056 , 3, 'p', LTS_STATE_i_22 , LTS_STATE_i_1057 , 3, 'f', LTS_STATE_i_1059 , LTS_STATE_i_1058 , 3, 'v', LTS_STATE_i_22 , LTS_STATE_i_1060 , 4, 'h', LTS_STATE_i_59 , LTS_STATE_i_1061 , 4, 'd', LTS_STATE_i_22 , LTS_STATE_i_1062 , 3, 'r', LTS_STATE_i_58 , LTS_STATE_i_724 , 2, 'e', LTS_STATE_i_58 , LTS_STATE_i_1063 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_58 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1064 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_1065 , 3, 'l', LTS_STATE_i_58 , LTS_STATE_i_59 , 3, 'd', LTS_STATE_i_58 , LTS_STATE_i_1066 , 3, 'p', LTS_STATE_i_58 , LTS_STATE_i_19 , 6, 'm', LTS_STATE_i_1068 , LTS_STATE_i_1067 , 2, 'e', LTS_STATE_i_22 , LTS_STATE_i_58 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_1069 , 3, 'u', LTS_STATE_i_36 , LTS_STATE_i_83 , 2, 'l', LTS_STATE_i_27 , LTS_STATE_i_26 , 4, 'd', LTS_STATE_i_22 , LTS_STATE_i_1070 , 3, 'h', LTS_STATE_i_19 , LTS_STATE_i_1071 , 6, 'l', LTS_STATE_i_1073 , LTS_STATE_i_1072 , 2, 'e', LTS_STATE_i_26 , LTS_STATE_i_1074 , 2, '#', LTS_STATE_i_22 , LTS_STATE_i_1075 , 3, 'g', LTS_STATE_i_27 , LTS_STATE_i_1076 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_1077 , 5, 'n', LTS_STATE_i_19 , LTS_STATE_i_1078 , 3, 'p', LTS_STATE_i_26 , LTS_STATE_i_1079 , 2, 'n', LTS_STATE_i_19 , LTS_STATE_i_1080 , 3, 't', LTS_STATE_i_58 , LTS_STATE_i_1081 , 4, 'n', LTS_STATE_i_1083 , LTS_STATE_i_1082 , 6, 'e', LTS_STATE_i_1085 , LTS_STATE_i_1084 , 3, 'u', LTS_STATE_i_27 , LTS_STATE_i_1086 , 3, 'l', LTS_STATE_i_26 , LTS_STATE_i_27 , 5, 's', LTS_STATE_i_1088 , LTS_STATE_i_1087 , 6, 'a', LTS_STATE_i_112 , LTS_STATE_i_1089 , 3, 's', LTS_STATE_i_19 , LTS_STATE_i_27 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_1090 , 4, 'v', LTS_STATE_i_1092 , LTS_STATE_i_1091 , 2, 'g', LTS_STATE_i_22 , LTS_STATE_i_1093 , 6, 'u', LTS_STATE_i_59 , LTS_STATE_i_1094 , 2, 'p', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 'm', LTS_STATE_i_26 , LTS_STATE_i_59 , 6, 'e', LTS_STATE_i_58 , LTS_STATE_i_1095 , 2, 'i', LTS_STATE_i_58 , LTS_STATE_i_1096 , 4, 'y', LTS_STATE_i_59 , LTS_STATE_i_1097 , 3, 'l', LTS_STATE_i_59 , LTS_STATE_i_19 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_1098 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_19 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_22 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_1099 , 4, 'z', LTS_STATE_i_1101 , LTS_STATE_i_1100 , 4, 'f', LTS_STATE_i_1102 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_1103 , LTS_STATE_i_27 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_1104 , 6, 'i', LTS_STATE_i_1106 , LTS_STATE_i_1105 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1107 , 6, 'l', LTS_STATE_i_27 , LTS_STATE_i_1108 , 3, 'k', LTS_STATE_i_1110 , LTS_STATE_i_1109 , 3, 'c', LTS_STATE_i_27 , LTS_STATE_i_1111 , 6, 'n', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 'v', LTS_STATE_i_22 , LTS_STATE_i_1112 , 4, 'l', LTS_STATE_i_19 , LTS_STATE_i_27 , 5, 'i', LTS_STATE_i_26 , LTS_STATE_i_1113 , 6, 's', LTS_STATE_i_58 , LTS_STATE_i_1114 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_1115 , 6, 't', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'p', LTS_STATE_i_58 , LTS_STATE_i_27 , 6, 'e', LTS_STATE_i_59 , LTS_STATE_i_1116 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1117 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_1118 , 2, 'p', LTS_STATE_i_22 , LTS_STATE_i_1119 , 2, 'a', LTS_STATE_i_19 , LTS_STATE_i_1120 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_1121 , 3, 'f', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_1122 , 6, 'd', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_27 , 6, 'o', LTS_STATE_i_19 , LTS_STATE_i_22 , 2, 'n', LTS_STATE_i_26 , LTS_STATE_i_1123 , 2, 's', LTS_STATE_i_1124 , LTS_STATE_i_19 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_1125 , 3, 'u', LTS_STATE_i_1127 , LTS_STATE_i_1126 , 5, 'k', LTS_STATE_i_27 , LTS_STATE_i_1128 , 6, 'z', LTS_STATE_i_59 , LTS_STATE_i_1129 , 4, 'v', LTS_STATE_i_58 , LTS_STATE_i_1130 , 4, 'd', LTS_STATE_i_27 , LTS_STATE_i_1131 , 5, 'm', LTS_STATE_i_27 , LTS_STATE_i_1132 , 6, '#', LTS_STATE_i_27 , LTS_STATE_i_58 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1133 , 2, 'i', LTS_STATE_i_58 , LTS_STATE_i_1134 , 2, 'c', LTS_STATE_i_22 , LTS_STATE_i_1135 , 3, 'g', LTS_STATE_i_27 , LTS_STATE_i_22 , 4, 's', LTS_STATE_i_36 , LTS_STATE_i_59 , 4, 'm', LTS_STATE_i_1137 , LTS_STATE_i_1136 , 6, 'i', LTS_STATE_i_58 , LTS_STATE_i_1138 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_1139 , 2, 'c', LTS_STATE_i_1141 , LTS_STATE_i_1140 , 2, 'n', LTS_STATE_i_59 , LTS_STATE_i_1142 , 3, 'g', LTS_STATE_i_59 , LTS_STATE_i_1143 , 5, 'h', LTS_STATE_i_1145 , LTS_STATE_i_1144 , 3, 'p', LTS_STATE_i_19 , LTS_STATE_i_27 , 6, 'u', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1146 , 6, 'a', LTS_STATE_i_83 , LTS_STATE_i_1147 , 4, 'b', LTS_STATE_i_22 , LTS_STATE_i_27 , 6, 'r', LTS_STATE_i_27 , LTS_STATE_i_1148 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_1149 , 6, 'n', LTS_STATE_i_27 , LTS_STATE_i_1150 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 't', LTS_STATE_i_1152 , LTS_STATE_i_1151 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_27 , 5, 'o', LTS_STATE_i_59 , LTS_STATE_i_1153 , 2, 'o', LTS_STATE_i_58 , LTS_STATE_i_27 , 2, 'k', LTS_STATE_i_27 , LTS_STATE_i_1154 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1155 , 4, 'c', LTS_STATE_i_59 , LTS_STATE_i_22 , 2, 's', LTS_STATE_i_22 , LTS_STATE_i_1156 , 4, 'n', LTS_STATE_i_22 , LTS_STATE_i_1157 , 3, 'p', LTS_STATE_i_19 , LTS_STATE_i_1158 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_1159 , 3, 'u', LTS_STATE_i_22 , LTS_STATE_i_1160 , 2, 'm', LTS_STATE_i_26 , LTS_STATE_i_1161 , 3, 'h', LTS_STATE_i_19 , LTS_STATE_i_22 , 3, 'v', LTS_STATE_i_58 , LTS_STATE_i_1162 , 5, 'm', LTS_STATE_i_1164 , LTS_STATE_i_1163 , 2, 'q', LTS_STATE_i_1166 , LTS_STATE_i_1165 , 6, 'k', LTS_STATE_i_27 , LTS_STATE_i_1167 , 6, 'o', LTS_STATE_i_1169 , LTS_STATE_i_1168 , 4, 'f', LTS_STATE_i_59 , LTS_STATE_i_1170 , 2, 'a', LTS_STATE_i_27 , LTS_STATE_i_1171 , 6, 'b', LTS_STATE_i_59 , LTS_STATE_i_1172 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_1173 , 2, 'l', LTS_STATE_i_58 , LTS_STATE_i_1174 , 4, 'f', LTS_STATE_i_19 , LTS_STATE_i_1175 , 3, 'u', LTS_STATE_i_1177 , LTS_STATE_i_1176 , 6, 't', LTS_STATE_i_19 , LTS_STATE_i_59 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_58 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_1178 , 3, 'l', LTS_STATE_i_59 , LTS_STATE_i_1179 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_1180 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1181 , 5, 'y', LTS_STATE_i_501 , LTS_STATE_i_1182 , 3, 'n', LTS_STATE_i_19 , LTS_STATE_i_1183 , 3, 't', LTS_STATE_i_22 , LTS_STATE_i_1184 , 4, 't', LTS_STATE_i_22 , LTS_STATE_i_1185 , 6, 'c', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'k', LTS_STATE_i_27 , LTS_STATE_i_1186 , 6, 't', LTS_STATE_i_27 , LTS_STATE_i_1187 , 4, 'j', LTS_STATE_i_22 , LTS_STATE_i_1188 , 3, 't', LTS_STATE_i_22 , LTS_STATE_i_19 , 6, 'n', LTS_STATE_i_22 , LTS_STATE_i_1189 , 2, 'c', LTS_STATE_i_27 , LTS_STATE_i_1190 , 4, 'n', LTS_STATE_i_1192 , LTS_STATE_i_1191 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_1193 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_1194 , 3, 'r', LTS_STATE_i_26 , LTS_STATE_i_1152 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_1195 , 2, 'c', LTS_STATE_i_26 , LTS_STATE_i_1196 , 3, 'h', LTS_STATE_i_26 , LTS_STATE_i_1197 , 2, 'r', LTS_STATE_i_58 , LTS_STATE_i_1198 , 3, 'h', LTS_STATE_i_1200 , LTS_STATE_i_1199 , 6, 'a', LTS_STATE_i_1201 , LTS_STATE_i_27 , 4, 't', LTS_STATE_i_1203 , LTS_STATE_i_1202 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_1204 , 2, 'u', LTS_STATE_i_1206 , LTS_STATE_i_1205 , 6, 't', LTS_STATE_i_1208 , LTS_STATE_i_1207 , 4, 't', LTS_STATE_i_27 , LTS_STATE_i_1209 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_1210 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_1211 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_1212 , 3, 'l', LTS_STATE_i_22 , LTS_STATE_i_27 , 2, 'h', LTS_STATE_i_58 , LTS_STATE_i_1213 , 2, 'w', LTS_STATE_i_22 , LTS_STATE_i_1214 , 3, 'h', LTS_STATE_i_1216 , LTS_STATE_i_1215 , 4, 'n', LTS_STATE_i_59 , LTS_STATE_i_36 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_1217 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1218 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1219 , 4, 'p', LTS_STATE_i_59 , LTS_STATE_i_1220 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_1221 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1222 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_1223 , 4, 'b', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_1224 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_1225 , 3, 'w', LTS_STATE_i_22 , LTS_STATE_i_1226 , 5, 'a', LTS_STATE_i_22 , LTS_STATE_i_1227 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_393 , 2, 'i', LTS_STATE_i_1047 , LTS_STATE_i_1228 , 6, 'l', LTS_STATE_i_1230 , LTS_STATE_i_1229 , 4, 'c', LTS_STATE_i_59 , LTS_STATE_i_1231 , 3, 'h', LTS_STATE_i_59 , LTS_STATE_i_1117 , 3, 'c', LTS_STATE_i_27 , LTS_STATE_i_1232 , 2, 'r', LTS_STATE_i_26 , LTS_STATE_i_1233 , 2, 'h', LTS_STATE_i_26 , LTS_STATE_i_1234 , 2, 'p', LTS_STATE_i_58 , LTS_STATE_i_1235 , 4, 'q', LTS_STATE_i_1237 , LTS_STATE_i_1236 , 5, 'u', LTS_STATE_i_59 , LTS_STATE_i_1238 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 'o', LTS_STATE_i_19 , LTS_STATE_i_1239 , 2, 'c', LTS_STATE_i_59 , LTS_STATE_i_36 , 4, 'p', LTS_STATE_i_27 , LTS_STATE_i_1240 , 3, 'u', LTS_STATE_i_1242 , LTS_STATE_i_1241 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_1243 , 6, 'a', LTS_STATE_i_1245 , LTS_STATE_i_1244 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_1246 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1247 , 3, 'c', LTS_STATE_i_27 , LTS_STATE_i_1248 , 6, '#', LTS_STATE_i_22 , LTS_STATE_i_1249 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_1250 , 3, 's', LTS_STATE_i_58 , LTS_STATE_i_1251 , 4, 's', LTS_STATE_i_22 , LTS_STATE_i_1252 , 2, 't', LTS_STATE_i_22 , LTS_STATE_i_1253 , 4, 'z', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'r', LTS_STATE_i_1254 , LTS_STATE_i_58 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_1255 , 2, 'p', LTS_STATE_i_59 , LTS_STATE_i_1256 , 2, 'i', LTS_STATE_i_22 , LTS_STATE_i_1257 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_1258 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_1259 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_1106 , 6, 'b', LTS_STATE_i_27 , LTS_STATE_i_1260 , 4, 'n', LTS_STATE_i_19 , LTS_STATE_i_1261 , 3, 's', LTS_STATE_i_22 , LTS_STATE_i_1262 , 6, 'a', LTS_STATE_i_22 , LTS_STATE_i_1263 , 3, 'u', LTS_STATE_i_1265 , LTS_STATE_i_1264 , 6, 't', LTS_STATE_i_59 , LTS_STATE_i_1266 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_19 , 3, 'u', LTS_STATE_i_22 , LTS_STATE_i_1267 , 4, 'n', LTS_STATE_i_1269 , LTS_STATE_i_1268 , 3, 's', LTS_STATE_i_26 , LTS_STATE_i_1270 , 6, 'd', LTS_STATE_i_1272 , LTS_STATE_i_1271 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_58 , 3, 'g', LTS_STATE_i_1274 , LTS_STATE_i_1273 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_26 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1275 , 5, '#', LTS_STATE_i_59 , LTS_STATE_i_1276 , 5, 'l', LTS_STATE_i_27 , LTS_STATE_i_1277 , 5, 'c', LTS_STATE_i_1279 , LTS_STATE_i_1278 , 2, 'q', LTS_STATE_i_27 , LTS_STATE_i_1280 , 5, '#', LTS_STATE_i_1281 , LTS_STATE_i_59 , 4, 'v', LTS_STATE_i_1283 , LTS_STATE_i_1282 , 4, 'f', LTS_STATE_i_59 , LTS_STATE_i_1284 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_1285 , 2, 'n', LTS_STATE_i_19 , LTS_STATE_i_1286 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_806 , 6, 's', LTS_STATE_i_22 , LTS_STATE_i_1287 , 5, 'u', LTS_STATE_i_26 , LTS_STATE_i_27 , 3, 't', LTS_STATE_i_58 , LTS_STATE_i_1288 , 3, 'f', LTS_STATE_i_22 , LTS_STATE_i_1289 , 2, 'o', LTS_STATE_i_1291 , LTS_STATE_i_1290 , 2, 'u', LTS_STATE_i_58 , LTS_STATE_i_27 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1292 , 2, 'u', LTS_STATE_i_59 , LTS_STATE_i_1293 , 4, 't', LTS_STATE_i_22 , LTS_STATE_i_59 , 5, 'v', LTS_STATE_i_27 , LTS_STATE_i_1294 , 6, 'd', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1295 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1296 , 6, 'n', LTS_STATE_i_59 , LTS_STATE_i_1297 , 4, 'f', LTS_STATE_i_22 , LTS_STATE_i_1298 , 2, 'p', LTS_STATE_i_22 , LTS_STATE_i_1299 , 2, 'g', LTS_STATE_i_22 , LTS_STATE_i_19 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 'b', LTS_STATE_i_1301 , LTS_STATE_i_1300 , 3, 'h', LTS_STATE_i_22 , LTS_STATE_i_1302 , 6, 't', LTS_STATE_i_1304 , LTS_STATE_i_1303 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_1305 , 3, 'r', LTS_STATE_i_26 , LTS_STATE_i_1306 , 2, 'l', LTS_STATE_i_26 , LTS_STATE_i_1307 , 6, 'i', LTS_STATE_i_1309 , LTS_STATE_i_1308 , 2, 'c', LTS_STATE_i_27 , LTS_STATE_i_1310 , 2, 'w', LTS_STATE_i_27 , LTS_STATE_i_1311 , 2, 'g', LTS_STATE_i_27 , LTS_STATE_i_1312 , 5, '#', LTS_STATE_i_27 , LTS_STATE_i_1313 , 2, 'a', LTS_STATE_i_1315 , LTS_STATE_i_1314 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_1316 , 5, 's', LTS_STATE_i_59 , LTS_STATE_i_1317 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_1318 , 4, 'b', LTS_STATE_i_59 , LTS_STATE_i_1319 , 3, 't', LTS_STATE_i_58 , LTS_STATE_i_1320 , 3, 'b', LTS_STATE_i_26 , LTS_STATE_i_1321 , 2, 'a', LTS_STATE_i_27 , LTS_STATE_i_1322 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_1323 , 3, 'm', LTS_STATE_i_22 , LTS_STATE_i_1324 , 2, 'd', LTS_STATE_i_58 , LTS_STATE_i_1325 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1326 , 4, 'b', LTS_STATE_i_59 , LTS_STATE_i_1327 , 4, 'l', LTS_STATE_i_22 , LTS_STATE_i_59 , 3, 'r', LTS_STATE_i_1329 , LTS_STATE_i_1328 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_1330 , 3, 'm', LTS_STATE_i_1331 , LTS_STATE_i_27 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_1332 , 6, 'f', LTS_STATE_i_27 , LTS_STATE_i_1333 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_59 , 4, 't', LTS_STATE_i_1335 , LTS_STATE_i_1334 , 3, 'm', LTS_STATE_i_19 , LTS_STATE_i_1336 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_1337 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 'd', LTS_STATE_i_1339 , LTS_STATE_i_1338 , 3, 'm', LTS_STATE_i_22 , LTS_STATE_i_1112 , 3, 'n', LTS_STATE_i_22 , LTS_STATE_i_27 , 3, 'p', LTS_STATE_i_22 , LTS_STATE_i_1340 , 6, 's', LTS_STATE_i_26 , LTS_STATE_i_19 , 2, 'd', LTS_STATE_i_26 , LTS_STATE_i_1341 , 2, 'i', LTS_STATE_i_1343 , LTS_STATE_i_1342 , 4, 'z', LTS_STATE_i_26 , LTS_STATE_i_1344 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_1345 , 4, 's', LTS_STATE_i_1346 , LTS_STATE_i_27 , 5, 's', LTS_STATE_i_59 , LTS_STATE_i_741 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 'p', LTS_STATE_i_27 , LTS_STATE_i_1347 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_1348 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_1349 , 5, '#', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1350 , 4, 'f', LTS_STATE_i_1352 , LTS_STATE_i_1351 , 6, 'l', LTS_STATE_i_27 , LTS_STATE_i_1353 , 3, 'u', LTS_STATE_i_26 , LTS_STATE_i_1354 , 4, 'v', LTS_STATE_i_27 , LTS_STATE_i_1355 , 2, 'o', LTS_STATE_i_27 , LTS_STATE_i_1356 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_1357 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_58 , 2, 'i', LTS_STATE_i_59 , LTS_STATE_i_1358 , 4, 'p', LTS_STATE_i_27 , LTS_STATE_i_1359 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_1360 , 6, 'r', LTS_STATE_i_59 , LTS_STATE_i_1361 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_1362 , 4, 't', LTS_STATE_i_1363 , LTS_STATE_i_27 , 6, 'i', LTS_STATE_i_22 , LTS_STATE_i_27 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 'l', LTS_STATE_i_22 , LTS_STATE_i_26 , 5, 'h', LTS_STATE_i_26 , LTS_STATE_i_22 , 4, 'k', LTS_STATE_i_22 , LTS_STATE_i_1364 , 4, 'f', LTS_STATE_i_1366 , LTS_STATE_i_1365 , 4, 'c', LTS_STATE_i_1367 , LTS_STATE_i_27 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'e', LTS_STATE_i_26 , LTS_STATE_i_1368 , 2, 'g', LTS_STATE_i_26 , LTS_STATE_i_1369 , 2, 'a', LTS_STATE_i_1371 , LTS_STATE_i_1370 , 6, 'a', LTS_STATE_i_1373 , LTS_STATE_i_1372 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_1374 , 2, 'r', LTS_STATE_i_1375 , LTS_STATE_i_59 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_1376 , 3, 'x', LTS_STATE_i_59 , LTS_STATE_i_1377 , 6, 'o', LTS_STATE_i_59 , LTS_STATE_i_1378 , 6, 'i', LTS_STATE_i_27 , LTS_STATE_i_1379 , 3, 'p', LTS_STATE_i_1380 , LTS_STATE_i_27 , 6, 'v', LTS_STATE_i_1382 , LTS_STATE_i_1381 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1383 , 3, 'd', LTS_STATE_i_58 , LTS_STATE_i_59 , 2, 'i', LTS_STATE_i_27 , LTS_STATE_i_1384 , 2, 'q', LTS_STATE_i_59 , LTS_STATE_i_1385 , 2, 'e', LTS_STATE_i_26 , LTS_STATE_i_1386 , 6, 'i', LTS_STATE_i_22 , LTS_STATE_i_1387 , 2, 'l', LTS_STATE_i_59 , LTS_STATE_i_1388 , 6, 'l', LTS_STATE_i_59 , LTS_STATE_i_1389 , 2, 'u', LTS_STATE_i_19 , LTS_STATE_i_1390 , 6, 'c', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 'n', LTS_STATE_i_59 , LTS_STATE_i_1391 , 6, 'u', LTS_STATE_i_19 , LTS_STATE_i_27 , 2, 'n', LTS_STATE_i_59 , LTS_STATE_i_1392 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1393 , 2, 'o', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_22 , 2, 't', LTS_STATE_i_22 , LTS_STATE_i_1394 , 2, 't', LTS_STATE_i_26 , LTS_STATE_i_1395 , 6, 'e', LTS_STATE_i_1397 , LTS_STATE_i_1396 , 5, 't', LTS_STATE_i_1399 , LTS_STATE_i_1398 , 5, 'c', LTS_STATE_i_27 , LTS_STATE_i_1400 , 4, 't', LTS_STATE_i_58 , LTS_STATE_i_1401 , 3, 'c', LTS_STATE_i_1403 , LTS_STATE_i_1402 , 5, 'l', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'c', LTS_STATE_i_27 , LTS_STATE_i_1040 , 6, 'o', LTS_STATE_i_1405 , LTS_STATE_i_1404 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_1406 , 6, 'h', LTS_STATE_i_27 , LTS_STATE_i_1407 , 255, 8, 0,0 , 0,0 , 6, 's', LTS_STATE_i_1409 , LTS_STATE_i_1408 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_22 , 6, 'c', LTS_STATE_i_1410 , LTS_STATE_i_59 , 3, 'd', LTS_STATE_i_26 , LTS_STATE_i_27 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1411 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_26 , 3, 'l', LTS_STATE_i_1413 , LTS_STATE_i_1412 , 3, 'd', LTS_STATE_i_59 , LTS_STATE_i_1414 , 4, 'n', LTS_STATE_i_1416 , LTS_STATE_i_1415 , 6, 'v', LTS_STATE_i_59 , LTS_STATE_i_1417 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1418 , 4, 't', LTS_STATE_i_1420 , LTS_STATE_i_1419 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_1421 , 2, 'p', LTS_STATE_i_26 , LTS_STATE_i_1422 , 2, 'f', LTS_STATE_i_19 , LTS_STATE_i_26 , 5, 'z', LTS_STATE_i_1424 , LTS_STATE_i_1423 , 4, 'b', LTS_STATE_i_1426 , LTS_STATE_i_1425 , 4, 's', LTS_STATE_i_1428 , LTS_STATE_i_1427 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_1429 , 5, 't', LTS_STATE_i_1431 , LTS_STATE_i_1430 , 4, 'd', LTS_STATE_i_27 , LTS_STATE_i_1110 , 2, 'l', LTS_STATE_i_1403 , LTS_STATE_i_1432 , 4, 'p', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 'g', LTS_STATE_i_27 , LTS_STATE_i_1433 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_1434 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1435 , 6, 't', LTS_STATE_i_27 , LTS_STATE_i_1436 , 4, 't', LTS_STATE_i_1438 , LTS_STATE_i_1437 , 4, 't', LTS_STATE_i_1440 , LTS_STATE_i_1439 , 3, 'c', LTS_STATE_i_1442 , LTS_STATE_i_1441 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_1443 , 2, 'g', LTS_STATE_i_22 , LTS_STATE_i_1444 , 2, 'b', LTS_STATE_i_22 , LTS_STATE_i_27 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_1445 , 6, 'm', LTS_STATE_i_27 , LTS_STATE_i_1446 , 6, 'i', LTS_STATE_i_59 , LTS_STATE_i_1447 , 6, 'd', LTS_STATE_i_27 , LTS_STATE_i_1448 , 3, 'l', LTS_STATE_i_59 , LTS_STATE_i_1047 , 6, 'a', LTS_STATE_i_59 , LTS_STATE_i_1449 , 6, 'c', LTS_STATE_i_59 , LTS_STATE_i_1450 , 4, 'p', LTS_STATE_i_59 , LTS_STATE_i_1451 , 2, 'n', LTS_STATE_i_26 , LTS_STATE_i_22 , 5, 'u', LTS_STATE_i_1453 , LTS_STATE_i_1452 , 6, 'o', LTS_STATE_i_26 , LTS_STATE_i_27 , 3, 't', LTS_STATE_i_1455 , LTS_STATE_i_1454 , 5, 'l', LTS_STATE_i_59 , LTS_STATE_i_27 , 5, '#', LTS_STATE_i_1457 , LTS_STATE_i_1456 , 5, '#', LTS_STATE_i_1459 , LTS_STATE_i_1458 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_1460 , 4, 's', LTS_STATE_i_1462 , LTS_STATE_i_1461 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1463 , 4, 't', LTS_STATE_i_1465 , LTS_STATE_i_1464 , 2, 'e', LTS_STATE_i_1467 , LTS_STATE_i_1466 , 5, 's', LTS_STATE_i_1141 , LTS_STATE_i_27 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_867 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_1468 , 4, 'h', LTS_STATE_i_19 , LTS_STATE_i_1469 , 2, 'e', LTS_STATE_i_27 , LTS_STATE_i_1361 , 4, 'n', LTS_STATE_i_1471 , LTS_STATE_i_1470 , 2, 'e', LTS_STATE_i_26 , LTS_STATE_i_22 , 2, 'g', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'a', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 'p', LTS_STATE_i_27 , LTS_STATE_i_1472 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_1473 , 4, 'k', LTS_STATE_i_22 , LTS_STATE_i_1474 , 2, 'a', LTS_STATE_i_59 , LTS_STATE_i_1475 , 6, 'v', LTS_STATE_i_59 , LTS_STATE_i_1201 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_1476 , 2, 'o', LTS_STATE_i_26 , LTS_STATE_i_1477 , 2, 's', LTS_STATE_i_22 , LTS_STATE_i_59 , 2, 'r', LTS_STATE_i_22 , LTS_STATE_i_1478 , 2, 'o', LTS_STATE_i_1480 , LTS_STATE_i_1479 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_1481 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_1482 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_1483 , 4, 'b', LTS_STATE_i_59 , LTS_STATE_i_1484 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1485 , 3, 'r', LTS_STATE_i_1487 , LTS_STATE_i_1486 , 3, 'x', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_1488 , 6, 'e', LTS_STATE_i_59 , LTS_STATE_i_1489 , 3, 'n', LTS_STATE_i_19 , LTS_STATE_i_59 , 3, 'v', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1490 , 5, 'r', LTS_STATE_i_26 , LTS_STATE_i_27 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1491 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1492 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'r', LTS_STATE_i_27 , LTS_STATE_i_1493 , 4, 'l', LTS_STATE_i_59 , LTS_STATE_i_1494 , 2, 'd', LTS_STATE_i_27 , LTS_STATE_i_1495 , 3, 'l', LTS_STATE_i_59 , LTS_STATE_i_1496 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1497 , 3, 'l', LTS_STATE_i_22 , LTS_STATE_i_1498 , 3, 'p', LTS_STATE_i_59 , LTS_STATE_i_1499 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_1500 , 4, 's', LTS_STATE_i_27 , LTS_STATE_i_1501 , 2, 'l', LTS_STATE_i_59 , LTS_STATE_i_1502 , 6, 'h', LTS_STATE_i_1504 , LTS_STATE_i_1503 , 5, 't', LTS_STATE_i_1506 , LTS_STATE_i_1505 , 4, 'f', LTS_STATE_i_59 , LTS_STATE_i_1507 , 5, 'l', LTS_STATE_i_1509 , LTS_STATE_i_1508 , 4, 't', LTS_STATE_i_22 , LTS_STATE_i_1510 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1511 , 4, 'l', LTS_STATE_i_59 , LTS_STATE_i_1512 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_1513 , 5, 's', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'r', LTS_STATE_i_1514 , LTS_STATE_i_59 , 4, 'b', LTS_STATE_i_59 , LTS_STATE_i_1515 , 4, 's', LTS_STATE_i_1516 , LTS_STATE_i_27 , 3, 'k', LTS_STATE_i_1518 , LTS_STATE_i_1517 , 6, 'u', LTS_STATE_i_27 , LTS_STATE_i_1519 , 4, 'd', LTS_STATE_i_27 , LTS_STATE_i_1520 , 4, 'm', LTS_STATE_i_59 , LTS_STATE_i_19 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_769 , 2, 'e', LTS_STATE_i_1073 , LTS_STATE_i_27 , 6, 'r', LTS_STATE_i_27 , LTS_STATE_i_1521 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_1522 , 6, 'n', LTS_STATE_i_59 , LTS_STATE_i_1523 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_1524 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_1525 , 3, 'l', LTS_STATE_i_22 , LTS_STATE_i_1526 , 5, 'r', LTS_STATE_i_1528 , LTS_STATE_i_1527 , 5, 'c', LTS_STATE_i_27 , LTS_STATE_i_1487 , 3, 's', LTS_STATE_i_59 , LTS_STATE_i_1529 , 4, 's', LTS_STATE_i_59 , LTS_STATE_i_27 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_1530 , 5, 'r', LTS_STATE_i_59 , LTS_STATE_i_1531 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_1532 , 4, 'l', LTS_STATE_i_27 , LTS_STATE_i_1533 , 6, 'd', LTS_STATE_i_59 , LTS_STATE_i_1534 , 4, 't', LTS_STATE_i_59 , LTS_STATE_i_26 , 6, 'a', LTS_STATE_i_27 , LTS_STATE_i_58 , 6, 'o', LTS_STATE_i_27 , LTS_STATE_i_59 , 5, 's', LTS_STATE_i_59 , LTS_STATE_i_1535 , 2, 'c', LTS_STATE_i_27 , LTS_STATE_i_1536 , 5, '#', LTS_STATE_i_1538 , LTS_STATE_i_1537 , 2, 'c', LTS_STATE_i_1317 , LTS_STATE_i_27 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_1539 , 6, 'l', LTS_STATE_i_1541 , LTS_STATE_i_1540 , 6, 'e', LTS_STATE_i_27 , LTS_STATE_i_22 , 3, 'n', LTS_STATE_i_22 , LTS_STATE_i_1542 , 3, 't', LTS_STATE_i_19 , LTS_STATE_i_1543 , 2, 's', LTS_STATE_i_59 , LTS_STATE_i_1544 , 3, 'r', LTS_STATE_i_1546 , LTS_STATE_i_1545 , 4, 'n', LTS_STATE_i_27 , LTS_STATE_i_22 , 2, 'e', LTS_STATE_i_1548 , LTS_STATE_i_1547 , 6, 'o', LTS_STATE_i_1549 , LTS_STATE_i_59 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_1550 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_1551 , 2, 'l', LTS_STATE_i_59 , LTS_STATE_i_1552 , 3, 'r', LTS_STATE_i_964 , LTS_STATE_i_1553 , 5, 'l', LTS_STATE_i_59 , LTS_STATE_i_19 , 3, 'c', LTS_STATE_i_59 , LTS_STATE_i_1554 , 6, '#', LTS_STATE_i_27 , LTS_STATE_i_1555 , 5, 'k', LTS_STATE_i_27 , LTS_STATE_i_853 , 5, 'f', LTS_STATE_i_59 , LTS_STATE_i_1556 , 3, 't', LTS_STATE_i_1558 , LTS_STATE_i_1557 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_1559 , 6, 'b', LTS_STATE_i_27 , LTS_STATE_i_1560 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_19 , 4, 'l', LTS_STATE_i_22 , LTS_STATE_i_1561 , 3, 'r', LTS_STATE_i_59 , LTS_STATE_i_1562 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'l', LTS_STATE_i_59 , LTS_STATE_i_1563 , 4, 'c', LTS_STATE_i_59 , LTS_STATE_i_1564 , 4, 'd', LTS_STATE_i_1566 , LTS_STATE_i_1565 , 3, 'l', LTS_STATE_i_1568 , LTS_STATE_i_1567 , 4, 'p', LTS_STATE_i_27 , LTS_STATE_i_59 , 5, 'c', LTS_STATE_i_59 , LTS_STATE_i_1569 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'u', LTS_STATE_i_59 , LTS_STATE_i_1570 , 4, 'p', LTS_STATE_i_59 , LTS_STATE_i_83 , 4, 't', LTS_STATE_i_1572 , LTS_STATE_i_1571 , 5, 'p', LTS_STATE_i_27 , LTS_STATE_i_59 , 6, 'e', LTS_STATE_i_27 , LTS_STATE_i_1573 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_1574 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_1575 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1576 , 3, 'h', LTS_STATE_i_27 , LTS_STATE_i_1577 , 3, 'c', LTS_STATE_i_22 , LTS_STATE_i_1578 , 6, 'w', LTS_STATE_i_27 , LTS_STATE_i_19 , 3, 'h', LTS_STATE_i_59 , LTS_STATE_i_1579 , 6, 't', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 's', LTS_STATE_i_1581 , LTS_STATE_i_1580 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_1582 , 6, 'r', LTS_STATE_i_59 , LTS_STATE_i_1583 , 4, 's', LTS_STATE_i_1584 , LTS_STATE_i_27 , 3, 'f', LTS_STATE_i_27 , LTS_STATE_i_1585 , 4, 'm', LTS_STATE_i_27 , LTS_STATE_i_1586 , 3, 'x', LTS_STATE_i_59 , LTS_STATE_i_1587 , 5, 'c', LTS_STATE_i_27 , LTS_STATE_i_1588 , 5, 's', LTS_STATE_i_27 , LTS_STATE_i_1589 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_1590 , 2, 's', LTS_STATE_i_27 , LTS_STATE_i_1468 , 6, 'e', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 'l', LTS_STATE_i_1361 , LTS_STATE_i_1591 , 3, 'r', LTS_STATE_i_22 , LTS_STATE_i_1592 , 2, 'e', LTS_STATE_i_59 , LTS_STATE_i_1117 , 3, 's', LTS_STATE_i_1594 , LTS_STATE_i_1593 , 3, 'r', LTS_STATE_i_1596 , LTS_STATE_i_1595 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_1597 , 5, '#', LTS_STATE_i_1599 , LTS_STATE_i_1598 , 6, '#', LTS_STATE_i_59 , LTS_STATE_i_1600 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_1601 , 2, 'o', LTS_STATE_i_1603 , LTS_STATE_i_1602 , 6, '#', LTS_STATE_i_1426 , LTS_STATE_i_1604 , 5, 'u', LTS_STATE_i_27 , LTS_STATE_i_1605 , 5, 'n', LTS_STATE_i_27 , LTS_STATE_i_1606 , 2, 'i', LTS_STATE_i_853 , LTS_STATE_i_1607 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1608 , 4, 'd', LTS_STATE_i_59 , LTS_STATE_i_22 , 2, 'r', LTS_STATE_i_1610 , LTS_STATE_i_1609 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_59 , 5, '#', LTS_STATE_i_1612 , LTS_STATE_i_1611 , 2, 'h', LTS_STATE_i_27 , LTS_STATE_i_1613 , 2, 'r', LTS_STATE_i_59 , LTS_STATE_i_1614 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_1615 , 4, 'l', LTS_STATE_i_59 , LTS_STATE_i_1616 , 5, '#', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'l', LTS_STATE_i_1506 , LTS_STATE_i_1617 , 2, 'r', LTS_STATE_i_1339 , LTS_STATE_i_1618 , 5, 't', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_1619 , 5, 'z', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_1620 , 2, 'y', LTS_STATE_i_59 , LTS_STATE_i_1621 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1622 , 2, 'c', LTS_STATE_i_27 , LTS_STATE_i_1623 , 3, 'r', LTS_STATE_i_1603 , LTS_STATE_i_1624 , 3, 't', LTS_STATE_i_1626 , LTS_STATE_i_1625 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_1627 , 5, 'c', LTS_STATE_i_26 , LTS_STATE_i_27 , 2, 'u', LTS_STATE_i_59 , LTS_STATE_i_1628 , 3, 'd', LTS_STATE_i_1514 , LTS_STATE_i_1629 , 3, 's', LTS_STATE_i_59 , LTS_STATE_i_1103 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_1630 , 3, 'n', LTS_STATE_i_1506 , LTS_STATE_i_27 , 6, 'l', LTS_STATE_i_27 , LTS_STATE_i_1110 , 3, 'c', LTS_STATE_i_27 , LTS_STATE_i_1631 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_1632 , 6, 'c', LTS_STATE_i_27 , LTS_STATE_i_1633 , 2, 'u', LTS_STATE_i_1635 , LTS_STATE_i_1634 , 3, 't', LTS_STATE_i_26 , LTS_STATE_i_1636 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1637 , 6, '#', LTS_STATE_i_59 , LTS_STATE_i_1638 , 2, 'l', LTS_STATE_i_27 , LTS_STATE_i_1639 , 2, 'g', LTS_STATE_i_27 , LTS_STATE_i_1551 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1640 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_1641 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1642 , 2, 'l', LTS_STATE_i_27 , LTS_STATE_i_1643 , 3, 'm', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'l', LTS_STATE_i_1403 , LTS_STATE_i_1644 , 5, '#', LTS_STATE_i_1646 , LTS_STATE_i_1645 , 3, 'n', LTS_STATE_i_59 , LTS_STATE_i_1647 , 6, 'o', LTS_STATE_i_1649 , LTS_STATE_i_1648 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_19 , 2, 'y', LTS_STATE_i_59 , LTS_STATE_i_1650 , 5, 't', LTS_STATE_i_1652 , LTS_STATE_i_1651 , 4, 't', LTS_STATE_i_27 , LTS_STATE_i_1653 , 6, 'a', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'b', LTS_STATE_i_1655 , LTS_STATE_i_1654 , 4, 'l', LTS_STATE_i_1657 , LTS_STATE_i_1656 , 6, '#', LTS_STATE_i_59 , LTS_STATE_i_27 , 4, 't', LTS_STATE_i_27 , LTS_STATE_i_59 , 4, 't', LTS_STATE_i_1658 , LTS_STATE_i_27 , 3, 'w', LTS_STATE_i_27 , LTS_STATE_i_1659 , 5, 'c', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'r', LTS_STATE_i_27 , LTS_STATE_i_1660 , 3, 'r', LTS_STATE_i_1375 , LTS_STATE_i_1661 , 3, 't', LTS_STATE_i_59 , LTS_STATE_i_1662 , 3, 'b', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_1663 , 2, 'o', LTS_STATE_i_59 , LTS_STATE_i_1664 , 3, 't', LTS_STATE_i_1665 , LTS_STATE_i_27 , 3, 'c', LTS_STATE_i_1667 , LTS_STATE_i_1666 , 3, 'm', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_1668 , 3, 'd', LTS_STATE_i_27 , LTS_STATE_i_1669 , 6, 'a', LTS_STATE_i_59 , LTS_STATE_i_1670 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_1671 , 2, 'n', LTS_STATE_i_1672 , LTS_STATE_i_27 , 2, 'b', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 'n', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'k', LTS_STATE_i_27 , LTS_STATE_i_1673 , 2, 's', LTS_STATE_i_59 , LTS_STATE_i_1375 , 3, 'k', LTS_STATE_i_27 , LTS_STATE_i_1674 , 3, 't', LTS_STATE_i_1676 , LTS_STATE_i_1675 , 3, 'v', LTS_STATE_i_59 , LTS_STATE_i_27 , 3, 'x', LTS_STATE_i_27 , LTS_STATE_i_1677 , 3, 'g', LTS_STATE_i_27 , LTS_STATE_i_59 , 2, 'b', LTS_STATE_i_59 , LTS_STATE_i_1678 , 3, 'p', LTS_STATE_i_27 , LTS_STATE_i_1679 , 2, 'u', LTS_STATE_i_27 , LTS_STATE_i_1680 , 2, 'n', LTS_STATE_i_27 , LTS_STATE_i_1681 , 4, 's', LTS_STATE_i_853 , LTS_STATE_i_27 , 5, 'l', LTS_STATE_i_1683 , LTS_STATE_i_1682 , 6, 's', LTS_STATE_i_59 , LTS_STATE_i_1684 , 3, 'n', LTS_STATE_i_27 , LTS_STATE_i_1685 , 2, 't', LTS_STATE_i_27 , LTS_STATE_i_59 , 3, 't', LTS_STATE_i_27 , LTS_STATE_i_1686 , 3, 'b', LTS_STATE_i_27 , LTS_STATE_i_1687 , 3, 'l', LTS_STATE_i_27 , LTS_STATE_i_1688 , 3, 's', LTS_STATE_i_27 , LTS_STATE_i_1141 , 5, 't', LTS_STATE_i_59 , LTS_STATE_i_27 , 2, 's', LTS_STATE_i_1689 , LTS_STATE_i_27 , 3, 'f', LTS_STATE_i_59 , LTS_STATE_i_1690 , 3, 't', LTS_STATE_i_1642 , LTS_STATE_i_27 , 2, 'n', LTS_STATE_i_1691 , LTS_STATE_i_885 , 6, 'r', LTS_STATE_i_59 , LTS_STATE_i_27 , /** letter j **/ 3, '#', LTS_STATE_j_2 , LTS_STATE_j_1 , 4, 'a', LTS_STATE_j_4 , LTS_STATE_j_3 , 255, 28, 0,0 , 0,0 , 3, 'n', LTS_STATE_j_2 , LTS_STATE_j_6 , 3, 'o', LTS_STATE_j_8 , LTS_STATE_j_7 , 3, 'd', LTS_STATE_j_2 , LTS_STATE_j_9 , 3, 'a', LTS_STATE_j_2 , LTS_STATE_j_10 , 255, 41, 0,0 , 0,0 , 4, 'i', LTS_STATE_j_2 , LTS_STATE_j_11 , 3, 'e', LTS_STATE_j_8 , LTS_STATE_j_12 , 4, 'o', LTS_STATE_j_14 , LTS_STATE_j_13 , 3, 'u', LTS_STATE_j_8 , LTS_STATE_j_2 , 4, 'e', LTS_STATE_j_2 , LTS_STATE_j_15 , 3, 's', LTS_STATE_j_17 , LTS_STATE_j_16 , 4, 'u', LTS_STATE_j_2 , LTS_STATE_j_18 , 3, 'b', LTS_STATE_j_8 , LTS_STATE_j_2 , 255, 0, 0,0 , 0,0 , 3, 'o', LTS_STATE_j_17 , LTS_STATE_j_19 , 4, 'k', LTS_STATE_j_17 , LTS_STATE_j_20 , 4, 'd', LTS_STATE_j_17 , LTS_STATE_j_21 , 3, 'e', LTS_STATE_j_17 , LTS_STATE_j_2 , /** letter k **/ 4, 'n', LTS_STATE_k_2 , LTS_STATE_k_1 , 4, 'k', LTS_STATE_k_4 , LTS_STATE_k_3 , 1, '0', LTS_STATE_k_4 , LTS_STATE_k_5 , 255, 22, 0,0 , 0,0 , 255, 0, 0,0 , 0,0 , 1, 'n', LTS_STATE_k_4 , LTS_STATE_k_3 , /** letter l **/ 4, 'l', LTS_STATE_l_2 , LTS_STATE_l_1 , 4, 'e', LTS_STATE_l_4 , LTS_STATE_l_3 , 5, '#', LTS_STATE_l_6 , LTS_STATE_l_5 , 6, 'g', LTS_STATE_l_8 , LTS_STATE_l_7 , 3, 'b', LTS_STATE_l_10 , LTS_STATE_l_9 , 6, '#', LTS_STATE_l_6 , LTS_STATE_l_11 , 255, 0, 0,0 , 0,0 , 4, 'k', LTS_STATE_l_14 , LTS_STATE_l_13 , 4, 'i', LTS_STATE_l_16 , LTS_STATE_l_15 , 5, '#', LTS_STATE_l_18 , LTS_STATE_l_17 , 5, '#', LTS_STATE_l_20 , LTS_STATE_l_19 , 2, 't', LTS_STATE_l_6 , LTS_STATE_l_21 , 3, 'l', LTS_STATE_l_23 , LTS_STATE_l_22 , 3, 'a', LTS_STATE_l_25 , LTS_STATE_l_24 , 255, 42, 0,0 , 0,0 , 3, 'l', LTS_STATE_l_15 , LTS_STATE_l_26 , 3, 't', LTS_STATE_l_28 , LTS_STATE_l_27 , 3, 'l', LTS_STATE_l_15 , LTS_STATE_l_29 , 2, '#', LTS_STATE_l_15 , LTS_STATE_l_30 , 255, 43, 0,0 , 0,0 , 6, 'k', LTS_STATE_l_6 , LTS_STATE_l_31 , 4, 'm', LTS_STATE_l_33 , LTS_STATE_l_32 , 6, '0', LTS_STATE_l_15 , LTS_STATE_l_34 , 3, 'o', LTS_STATE_l_35 , LTS_STATE_l_15 , 2, 'w', LTS_STATE_l_6 , LTS_STATE_l_36 , 3, 'b', LTS_STATE_l_20 , LTS_STATE_l_37 , 6, '#', LTS_STATE_l_39 , LTS_STATE_l_38 , 5, 'y', LTS_STATE_l_15 , LTS_STATE_l_40 , 3, 'a', LTS_STATE_l_15 , LTS_STATE_l_41 , 5, 's', LTS_STATE_l_20 , LTS_STATE_l_42 , 3, 'a', LTS_STATE_l_6 , LTS_STATE_l_43 , 4, '#', LTS_STATE_l_45 , LTS_STATE_l_44 , 3, 'a', LTS_STATE_l_47 , LTS_STATE_l_46 , 4, 'u', LTS_STATE_l_48 , LTS_STATE_l_15 , 2, 'f', LTS_STATE_l_6 , LTS_STATE_l_49 , 2, 't', LTS_STATE_l_6 , LTS_STATE_l_50 , 3, 'g', LTS_STATE_l_20 , LTS_STATE_l_51 , 3, 'd', LTS_STATE_l_53 , LTS_STATE_l_52 , 5, 'y', LTS_STATE_l_15 , LTS_STATE_l_54 , 6, 's', LTS_STATE_l_15 , LTS_STATE_l_55 , 3, 'i', LTS_STATE_l_15 , LTS_STATE_l_56 , 5, 'd', LTS_STATE_l_20 , LTS_STATE_l_57 , 6, 'l', LTS_STATE_l_58 , LTS_STATE_l_6 , 3, 'u', LTS_STATE_l_60 , LTS_STATE_l_59 , 3, 'd', LTS_STATE_l_20 , LTS_STATE_l_61 , 3, 'o', LTS_STATE_l_62 , LTS_STATE_l_15 , 5, '#', LTS_STATE_l_6 , LTS_STATE_l_63 , 2, 'e', LTS_STATE_l_64 , LTS_STATE_l_15 , 5, '#', LTS_STATE_l_6 , LTS_STATE_l_15 , 5, '#', LTS_STATE_l_6 , LTS_STATE_l_65 , 3, 't', LTS_STATE_l_67 , LTS_STATE_l_66 , 3, 'g', LTS_STATE_l_69 , LTS_STATE_l_68 , 6, 's', LTS_STATE_l_15 , LTS_STATE_l_70 , 3, 'l', LTS_STATE_l_15 , LTS_STATE_l_71 , 5, 'r', LTS_STATE_l_73 , LTS_STATE_l_72 , 3, 'o', LTS_STATE_l_15 , LTS_STATE_l_74 , 5, 'y', LTS_STATE_l_15 , LTS_STATE_l_75 , 2, 'c', LTS_STATE_l_15 , LTS_STATE_l_6 , 4, 'f', LTS_STATE_l_77 , LTS_STATE_l_76 , 5, '#', LTS_STATE_l_78 , LTS_STATE_l_15 , 3, 't', LTS_STATE_l_20 , LTS_STATE_l_79 , 2, 'c', LTS_STATE_l_6 , LTS_STATE_l_15 , 5, 'a', LTS_STATE_l_15 , LTS_STATE_l_80 , 5, 'm', LTS_STATE_l_15 , LTS_STATE_l_81 , 5, 'a', LTS_STATE_l_15 , LTS_STATE_l_82 , 2, 'z', LTS_STATE_l_20 , LTS_STATE_l_83 , 2, 'r', LTS_STATE_l_15 , LTS_STATE_l_84 , 3, 'p', LTS_STATE_l_86 , LTS_STATE_l_85 , 2, '#', LTS_STATE_l_15 , LTS_STATE_l_87 , 2, 'd', LTS_STATE_l_20 , LTS_STATE_l_88 , 3, 'i', LTS_STATE_l_15 , LTS_STATE_l_89 , 6, 'g', LTS_STATE_l_15 , LTS_STATE_l_90 , 2, 'i', LTS_STATE_l_20 , LTS_STATE_l_91 , 3, 'e', LTS_STATE_l_15 , LTS_STATE_l_92 , 2, 'a', LTS_STATE_l_20 , LTS_STATE_l_93 , 4, 'v', LTS_STATE_l_95 , LTS_STATE_l_94 , 2, 'h', LTS_STATE_l_96 , LTS_STATE_l_15 , 4, 't', LTS_STATE_l_97 , LTS_STATE_l_15 , 3, 'g', LTS_STATE_l_20 , LTS_STATE_l_98 , 2, 'c', LTS_STATE_l_6 , LTS_STATE_l_99 , 5, 'l', LTS_STATE_l_100 , LTS_STATE_l_15 , 5, 'o', LTS_STATE_l_15 , LTS_STATE_l_101 , 3, 'p', LTS_STATE_l_20 , LTS_STATE_l_102 , 2, 's', LTS_STATE_l_15 , LTS_STATE_l_20 , 3, 'k', LTS_STATE_l_104 , LTS_STATE_l_103 , 2, 'p', LTS_STATE_l_106 , LTS_STATE_l_105 , 5, 'c', LTS_STATE_l_15 , LTS_STATE_l_107 , 6, 'a', LTS_STATE_l_20 , LTS_STATE_l_108 , 3, 'a', LTS_STATE_l_15 , LTS_STATE_l_109 , 5, 't', LTS_STATE_l_15 , LTS_STATE_l_110 , 2, 's', LTS_STATE_l_15 , LTS_STATE_l_111 , 3, 'y', LTS_STATE_l_15 , LTS_STATE_l_112 , 2, 'u', LTS_STATE_l_20 , LTS_STATE_l_113 , 4, 'n', LTS_STATE_l_62 , LTS_STATE_l_15 , 3, 'a', LTS_STATE_l_114 , LTS_STATE_l_15 , 3, 'a', LTS_STATE_l_6 , LTS_STATE_l_15 , 2, 'a', LTS_STATE_l_6 , LTS_STATE_l_15 , 3, 'a', LTS_STATE_l_15 , LTS_STATE_l_115 , 2, 'b', LTS_STATE_l_6 , LTS_STATE_l_114 , 255, 41, 0,0 , 0,0 , 2, 'f', LTS_STATE_l_6 , LTS_STATE_l_116 , 3, 'd', LTS_STATE_l_118 , LTS_STATE_l_117 , 3, 'z', LTS_STATE_l_20 , LTS_STATE_l_15 , 2, '#', LTS_STATE_l_15 , LTS_STATE_l_119 , 5, 'c', LTS_STATE_l_20 , LTS_STATE_l_15 , 5, 'm', LTS_STATE_l_15 , LTS_STATE_l_20 , 6, 's', LTS_STATE_l_15 , LTS_STATE_l_120 , 2, 'n', LTS_STATE_l_20 , LTS_STATE_l_15 , 3, 'e', LTS_STATE_l_15 , LTS_STATE_l_121 , 2, 'n', LTS_STATE_l_20 , LTS_STATE_l_122 , 2, 'u', LTS_STATE_l_20 , LTS_STATE_l_15 , 3, 'u', LTS_STATE_l_15 , LTS_STATE_l_123 , 6, 's', LTS_STATE_l_15 , LTS_STATE_l_124 , 2, 'h', LTS_STATE_l_6 , LTS_STATE_l_15 , 3, 'e', LTS_STATE_l_15 , LTS_STATE_l_125 , 2, 'h', LTS_STATE_l_6 , LTS_STATE_l_126 , 3, 'f', LTS_STATE_l_20 , LTS_STATE_l_127 , 2, 'd', LTS_STATE_l_20 , LTS_STATE_l_15 , 6, 's', LTS_STATE_l_15 , LTS_STATE_l_128 , 6, 'o', LTS_STATE_l_20 , LTS_STATE_l_129 , 3, 'o', LTS_STATE_l_15 , LTS_STATE_l_130 , 5, 's', LTS_STATE_l_20 , LTS_STATE_l_131 , 3, 'r', LTS_STATE_l_133 , LTS_STATE_l_132 , 5, 't', LTS_STATE_l_15 , LTS_STATE_l_134 , 3, 'i', LTS_STATE_l_15 , LTS_STATE_l_135 , 2, 'b', LTS_STATE_l_6 , LTS_STATE_l_15 , 3, 's', LTS_STATE_l_15 , LTS_STATE_l_136 , 5, 'b', LTS_STATE_l_20 , LTS_STATE_l_15 , 6, 'a', LTS_STATE_l_20 , LTS_STATE_l_137 , 5, 's', LTS_STATE_l_139 , LTS_STATE_l_138 , 5, 'd', LTS_STATE_l_20 , LTS_STATE_l_140 , 3, 'w', LTS_STATE_l_15 , LTS_STATE_l_141 , 2, 'a', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'm', LTS_STATE_l_15 , LTS_STATE_l_142 , 2, 'c', LTS_STATE_l_144 , LTS_STATE_l_143 , 3, 'c', LTS_STATE_l_145 , LTS_STATE_l_15 , 6, 'e', LTS_STATE_l_20 , LTS_STATE_l_146 , 5, 'd', LTS_STATE_l_148 , LTS_STATE_l_147 , 3, 'y', LTS_STATE_l_15 , LTS_STATE_l_149 , 5, 'm', LTS_STATE_l_20 , LTS_STATE_l_150 , 3, 's', LTS_STATE_l_151 , LTS_STATE_l_20 , 5, 'm', LTS_STATE_l_15 , LTS_STATE_l_152 , 3, 'u', LTS_STATE_l_15 , LTS_STATE_l_153 , 3, 'h', LTS_STATE_l_20 , LTS_STATE_l_15 , 2, '#', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'n', LTS_STATE_l_15 , LTS_STATE_l_20 , 5, 'r', LTS_STATE_l_154 , LTS_STATE_l_15 , 3, 'u', LTS_STATE_l_15 , LTS_STATE_l_155 , 3, 'u', LTS_STATE_l_15 , LTS_STATE_l_156 , 5, 'b', LTS_STATE_l_20 , LTS_STATE_l_157 , 2, 'i', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'b', LTS_STATE_l_15 , LTS_STATE_l_158 , 3, 'o', LTS_STATE_l_15 , LTS_STATE_l_159 , 3, 's', LTS_STATE_l_84 , LTS_STATE_l_160 , 3, 'w', LTS_STATE_l_15 , LTS_STATE_l_161 , 3, 'r', LTS_STATE_l_15 , LTS_STATE_l_162 , 6, 'e', LTS_STATE_l_20 , LTS_STATE_l_163 , 5, 'r', LTS_STATE_l_20 , LTS_STATE_l_15 , 3, 'h', LTS_STATE_l_15 , LTS_STATE_l_164 , 3, 'g', LTS_STATE_l_166 , LTS_STATE_l_165 , 3, 'r', LTS_STATE_l_15 , LTS_STATE_l_167 , 3, 'w', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 't', LTS_STATE_l_20 , LTS_STATE_l_15 , 3, 'r', LTS_STATE_l_15 , LTS_STATE_l_168 , 3, 'd', LTS_STATE_l_170 , LTS_STATE_l_169 , 2, 'a', LTS_STATE_l_15 , LTS_STATE_l_171 , 2, 'n', LTS_STATE_l_20 , LTS_STATE_l_172 , 3, 'y', LTS_STATE_l_15 , LTS_STATE_l_162 , 2, 'c', LTS_STATE_l_144 , LTS_STATE_l_173 , 2, 'n', LTS_STATE_l_15 , LTS_STATE_l_174 , 2, 'e', LTS_STATE_l_15 , LTS_STATE_l_175 , 3, 'd', LTS_STATE_l_20 , LTS_STATE_l_176 , 3, 'f', LTS_STATE_l_178 , LTS_STATE_l_177 , 2, 'd', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'n', LTS_STATE_l_20 , LTS_STATE_l_179 , 3, 'k', LTS_STATE_l_20 , LTS_STATE_l_180 , 3, 'p', LTS_STATE_l_181 , LTS_STATE_l_15 , 2, 'f', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'i', LTS_STATE_l_20 , LTS_STATE_l_15 , 3, 'g', LTS_STATE_l_20 , LTS_STATE_l_182 , 2, 'p', LTS_STATE_l_15 , LTS_STATE_l_20 , 2, 'f', LTS_STATE_l_20 , LTS_STATE_l_183 , 2, 'z', LTS_STATE_l_20 , LTS_STATE_l_184 , 3, 'p', LTS_STATE_l_20 , LTS_STATE_l_185 , 3, 'c', LTS_STATE_l_20 , LTS_STATE_l_15 , /** letter m **/ 4, 'm', LTS_STATE_m_2 , LTS_STATE_m_1 , 4, 'c', LTS_STATE_m_4 , LTS_STATE_m_3 , 255, 0, 0,0 , 0,0 , 3, 's', LTS_STATE_m_7 , LTS_STATE_m_6 , 2, '0', LTS_STATE_m_9 , LTS_STATE_m_8 , 4, 'l', LTS_STATE_m_8 , LTS_STATE_m_10 , 4, '#', LTS_STATE_m_12 , LTS_STATE_m_11 , 255, 44, 0,0 , 0,0 , 5, 'e', LTS_STATE_m_14 , LTS_STATE_m_13 , 3, 'h', LTS_STATE_m_15 , LTS_STATE_m_8 , 4, 's', LTS_STATE_m_12 , LTS_STATE_m_16 , 255, 45, 0,0 , 0,0 , 5, 'i', LTS_STATE_m_18 , LTS_STATE_m_17 , 6, 'l', LTS_STATE_m_18 , LTS_STATE_m_19 , 2, 't', LTS_STATE_m_20 , LTS_STATE_m_8 , 5, 'r', LTS_STATE_m_21 , LTS_STATE_m_8 , 255, 46, 0,0 , 0,0 , 255, 47, 0,0 , 0,0 , 6, 'n', LTS_STATE_m_18 , LTS_STATE_m_17 , 6, '0', LTS_STATE_m_12 , LTS_STATE_m_8 , 4, 'e', LTS_STATE_m_22 , LTS_STATE_m_8 , 2, 'e', LTS_STATE_m_8 , LTS_STATE_m_12 , /** letter n **/ 4, 'g', LTS_STATE_n_2 , LTS_STATE_n_1 , 4, 'n', LTS_STATE_n_4 , LTS_STATE_n_3 , 5, '#', LTS_STATE_n_6 , LTS_STATE_n_5 , 4, 'k', LTS_STATE_n_8 , LTS_STATE_n_7 , 2, 'm', LTS_STATE_n_10 , LTS_STATE_n_9 , 5, 'e', LTS_STATE_n_12 , LTS_STATE_n_11 , 255, 48, 0,0 , 0,0 , 4, 'c', LTS_STATE_n_15 , LTS_STATE_n_14 , 6, 'm', LTS_STATE_n_17 , LTS_STATE_n_16 , 6, 's', LTS_STATE_n_10 , LTS_STATE_n_18 , 255, 0, 0,0 , 0,0 , 5, 'i', LTS_STATE_n_20 , LTS_STATE_n_19 , 6, 'r', LTS_STATE_n_22 , LTS_STATE_n_21 , 4, 'q', LTS_STATE_n_24 , LTS_STATE_n_23 , 5, 't', LTS_STATE_n_6 , LTS_STATE_n_25 , 5, 'n', LTS_STATE_n_27 , LTS_STATE_n_26 , 255, 49, 0,0 , 0,0 , 5, 'i', LTS_STATE_n_10 , LTS_STATE_n_28 , 5, 'r', LTS_STATE_n_30 , LTS_STATE_n_29 , 2, '#', LTS_STATE_n_17 , LTS_STATE_n_31 , 6, '#', LTS_STATE_n_17 , LTS_STATE_n_32 , 2, 's', LTS_STATE_n_17 , LTS_STATE_n_33 , 4, 'x', LTS_STATE_n_6 , LTS_STATE_n_17 , 2, '#', LTS_STATE_n_17 , LTS_STATE_n_34 , 5, 'k', LTS_STATE_n_6 , LTS_STATE_n_35 , 6, 'y', LTS_STATE_n_6 , LTS_STATE_n_36 , 2, '#', LTS_STATE_n_17 , LTS_STATE_n_6 , 2, 'y', LTS_STATE_n_10 , LTS_STATE_n_37 , 6, 'g', LTS_STATE_n_17 , LTS_STATE_n_38 , 6, 'a', LTS_STATE_n_17 , LTS_STATE_n_39 , 6, 'b', LTS_STATE_n_17 , LTS_STATE_n_40 , 6, 's', LTS_STATE_n_17 , LTS_STATE_n_41 , 2, 'r', LTS_STATE_n_6 , LTS_STATE_n_42 , 6, 'e', LTS_STATE_n_6 , LTS_STATE_n_17 , 5, 'e', LTS_STATE_n_17 , LTS_STATE_n_43 , 5, 'i', LTS_STATE_n_6 , LTS_STATE_n_44 , 2, '#', LTS_STATE_n_10 , LTS_STATE_n_45 , 5, 'y', LTS_STATE_n_17 , LTS_STATE_n_6 , 6, 'o', LTS_STATE_n_17 , LTS_STATE_n_6 , 6, 'a', LTS_STATE_n_17 , LTS_STATE_n_46 , 2, 'l', LTS_STATE_n_48 , LTS_STATE_n_47 , 2, 'h', LTS_STATE_n_6 , LTS_STATE_n_49 , 5, '#', LTS_STATE_n_6 , LTS_STATE_n_50 , 6, 'p', LTS_STATE_n_17 , LTS_STATE_n_6 , 2, 'i', LTS_STATE_n_10 , LTS_STATE_n_51 , 2, 'm', LTS_STATE_n_6 , LTS_STATE_n_52 , 6, 'l', LTS_STATE_n_54 , LTS_STATE_n_53 , 6, 'n', LTS_STATE_n_6 , LTS_STATE_n_55 , 2, 'n', LTS_STATE_n_6 , LTS_STATE_n_56 , 5, 'i', LTS_STATE_n_17 , LTS_STATE_n_57 , 2, 'b', LTS_STATE_n_58 , LTS_STATE_n_10 , 2, 'l', LTS_STATE_n_6 , LTS_STATE_n_59 , 6, 'o', LTS_STATE_n_17 , LTS_STATE_n_60 , 2, 'v', LTS_STATE_n_17 , LTS_STATE_n_6 , 6, 'l', LTS_STATE_n_6 , LTS_STATE_n_17 , 2, 'f', LTS_STATE_n_6 , LTS_STATE_n_61 , 5, 'y', LTS_STATE_n_17 , LTS_STATE_n_62 , 6, '#', LTS_STATE_n_63 , LTS_STATE_n_10 , 2, 'b', LTS_STATE_n_6 , LTS_STATE_n_64 , 6, 'a', LTS_STATE_n_17 , LTS_STATE_n_65 , 2, 'w', LTS_STATE_n_6 , LTS_STATE_n_66 , 5, 'h', LTS_STATE_n_68 , LTS_STATE_n_67 , 5, 'e', LTS_STATE_n_17 , LTS_STATE_n_10 , 2, 'v', LTS_STATE_n_6 , LTS_STATE_n_69 , 2, 't', LTS_STATE_n_17 , LTS_STATE_n_70 , 2, 'g', LTS_STATE_n_17 , LTS_STATE_n_6 , 6, '#', LTS_STATE_n_72 , LTS_STATE_n_71 , 6, 'e', LTS_STATE_n_17 , LTS_STATE_n_73 , 6, 'n', LTS_STATE_n_74 , LTS_STATE_n_17 , 2, 'r', LTS_STATE_n_17 , LTS_STATE_n_75 , 6, 'l', LTS_STATE_n_77 , LTS_STATE_n_76 , 5, 'a', LTS_STATE_n_6 , LTS_STATE_n_78 , 2, 's', LTS_STATE_n_6 , LTS_STATE_n_17 , 2, 'r', LTS_STATE_n_6 , LTS_STATE_n_17 , 6, 'm', LTS_STATE_n_6 , LTS_STATE_n_79 , 2, 'd', LTS_STATE_n_6 , LTS_STATE_n_80 , 5, 'a', LTS_STATE_n_17 , LTS_STATE_n_6 , 2, 'i', LTS_STATE_n_17 , LTS_STATE_n_81 , 6, 'd', LTS_STATE_n_17 , LTS_STATE_n_82 , 6, 's', LTS_STATE_n_17 , LTS_STATE_n_83 , 2, 'r', LTS_STATE_n_17 , LTS_STATE_n_6 , 2, '#', LTS_STATE_n_17 , LTS_STATE_n_84 , 2, 'r', LTS_STATE_n_85 , LTS_STATE_n_17 , 6, 'n', LTS_STATE_n_6 , LTS_STATE_n_17 , 6, 'i', LTS_STATE_n_17 , LTS_STATE_n_86 , 5, 'o', LTS_STATE_n_6 , LTS_STATE_n_17 , /** letter o **/ 4, 'r', LTS_STATE_o_2 , LTS_STATE_o_1 , 4, '#', LTS_STATE_o_4 , LTS_STATE_o_3 , 1, '0', LTS_STATE_o_6 , LTS_STATE_o_5 , 3, 'o', LTS_STATE_o_8 , LTS_STATE_o_7 , 3, 'o', LTS_STATE_o_10 , LTS_STATE_o_9 , 1, '#', LTS_STATE_o_12 , LTS_STATE_o_11 , 3, 'w', LTS_STATE_o_14 , LTS_STATE_o_13 , 4, 'o', LTS_STATE_o_16 , LTS_STATE_o_15 , 4, 'd', LTS_STATE_o_18 , LTS_STATE_o_17 , 3, 'a', LTS_STATE_o_20 , LTS_STATE_o_19 , 255, 33, 0,0 , 0,0 , 5, '#', LTS_STATE_o_23 , LTS_STATE_o_22 , 3, 'o', LTS_STATE_o_25 , LTS_STATE_o_24 , 3, 'c', LTS_STATE_o_27 , LTS_STATE_o_26 , 255, 0, 0,0 , 0,0 , 4, 'u', LTS_STATE_o_29 , LTS_STATE_o_28 , 3, 'c', LTS_STATE_o_30 , LTS_STATE_o_14 , 4, 'k', LTS_STATE_o_32 , LTS_STATE_o_31 , 2, 'l', LTS_STATE_o_34 , LTS_STATE_o_33 , 3, 'g', LTS_STATE_o_36 , LTS_STATE_o_35 , 255, 4, 0,0 , 0,0 , 3, 'w', LTS_STATE_o_38 , LTS_STATE_o_37 , 3, 'c', LTS_STATE_o_40 , LTS_STATE_o_39 , 2, 's', LTS_STATE_o_40 , LTS_STATE_o_41 , 2, 'd', LTS_STATE_o_40 , LTS_STATE_o_42 , 5, 'r', LTS_STATE_o_44 , LTS_STATE_o_43 , 5, 'r', LTS_STATE_o_45 , LTS_STATE_o_40 , 4, 'n', LTS_STATE_o_47 , LTS_STATE_o_46 , 5, 's', LTS_STATE_o_49 , LTS_STATE_o_48 , 5, 'r', LTS_STATE_o_36 , LTS_STATE_o_14 , 2, 'f', LTS_STATE_o_51 , LTS_STATE_o_50 , 1, 's', LTS_STATE_o_53 , LTS_STATE_o_52 , 2, 'f', LTS_STATE_o_10 , LTS_STATE_o_54 , 255, 50, 0,0 , 0,0 , 3, 'd', LTS_STATE_o_36 , LTS_STATE_o_55 , 255, 11, 0,0 , 0,0 , 5, 's', LTS_STATE_o_57 , LTS_STATE_o_56 , 2, 'a', LTS_STATE_o_14 , LTS_STATE_o_58 , 3, 'o', LTS_STATE_o_60 , LTS_STATE_o_59 , 255, 7, 0,0 , 0,0 , 2, 'f', LTS_STATE_o_62 , LTS_STATE_o_61 , 2, 'c', LTS_STATE_o_40 , LTS_STATE_o_60 , 5, 'e', LTS_STATE_o_64 , LTS_STATE_o_63 , 6, 'o', LTS_STATE_o_66 , LTS_STATE_o_65 , 6, 'i', LTS_STATE_o_40 , LTS_STATE_o_67 , 4, 'w', LTS_STATE_o_69 , LTS_STATE_o_68 , 5, '#', LTS_STATE_o_71 , LTS_STATE_o_70 , 5, 'r', LTS_STATE_o_73 , LTS_STATE_o_72 , 6, 'e', LTS_STATE_o_75 , LTS_STATE_o_74 , 2, 'w', LTS_STATE_o_77 , LTS_STATE_o_76 , 4, 't', LTS_STATE_o_60 , LTS_STATE_o_10 , 1, 'b', LTS_STATE_o_78 , LTS_STATE_o_60 , 5, '#', LTS_STATE_o_60 , LTS_STATE_o_10 , 2, 'w', LTS_STATE_o_60 , LTS_STATE_o_79 , 3, 'n', LTS_STATE_o_36 , LTS_STATE_o_80 , 5, 'e', LTS_STATE_o_82 , LTS_STATE_o_81 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_83 , 2, 's', LTS_STATE_o_84 , LTS_STATE_o_14 , 3, 't', LTS_STATE_o_14 , LTS_STATE_o_85 , 255, 51, 0,0 , 0,0 , 3, 'm', LTS_STATE_o_14 , LTS_STATE_o_86 , 3, 'i', LTS_STATE_o_87 , LTS_STATE_o_40 , 5, 'a', LTS_STATE_o_89 , LTS_STATE_o_88 , 3, 'n', LTS_STATE_o_40 , LTS_STATE_o_90 , 6, 'y', LTS_STATE_o_40 , LTS_STATE_o_91 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_40 , 6, 'o', LTS_STATE_o_14 , LTS_STATE_o_93 , 4, 'i', LTS_STATE_o_95 , LTS_STATE_o_94 , 6, 'k', LTS_STATE_o_40 , LTS_STATE_o_96 , 3, 'i', LTS_STATE_o_98 , LTS_STATE_o_97 , 3, 'i', LTS_STATE_o_100 , LTS_STATE_o_99 , 5, 'g', LTS_STATE_o_102 , LTS_STATE_o_101 , 3, 'h', LTS_STATE_o_104 , LTS_STATE_o_103 , 1, '0', LTS_STATE_o_106 , LTS_STATE_o_105 , 3, 'h', LTS_STATE_o_20 , LTS_STATE_o_107 , 2, 'c', LTS_STATE_o_10 , LTS_STATE_o_108 , 4, 'l', LTS_STATE_o_60 , LTS_STATE_o_10 , 6, '#', LTS_STATE_o_109 , LTS_STATE_o_60 , 2, 'g', LTS_STATE_o_60 , LTS_STATE_o_110 , 2, 'l', LTS_STATE_o_36 , LTS_STATE_o_111 , 5, 'f', LTS_STATE_o_113 , LTS_STATE_o_112 , 3, 'm', LTS_STATE_o_115 , LTS_STATE_o_114 , 6, 'h', LTS_STATE_o_14 , LTS_STATE_o_116 , 5, 't', LTS_STATE_o_14 , LTS_STATE_o_40 , 2, 'a', LTS_STATE_o_117 , LTS_STATE_o_14 , 2, 'p', LTS_STATE_o_40 , LTS_STATE_o_118 , 255, 14, 0,0 , 0,0 , 5, 'o', LTS_STATE_o_120 , LTS_STATE_o_119 , 6, 'i', LTS_STATE_o_14 , LTS_STATE_o_121 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_122 , 6, 'e', LTS_STATE_o_123 , LTS_STATE_o_40 , 255, 2, 0,0 , 0,0 , 6, 'a', LTS_STATE_o_14 , LTS_STATE_o_124 , 4, 'y', LTS_STATE_o_126 , LTS_STATE_o_125 , 5, 's', LTS_STATE_o_128 , LTS_STATE_o_127 , 5, '#', LTS_STATE_o_130 , LTS_STATE_o_129 , 5, 'e', LTS_STATE_o_132 , LTS_STATE_o_131 , 2, 't', LTS_STATE_o_100 , LTS_STATE_o_133 , 3, 's', LTS_STATE_o_135 , LTS_STATE_o_134 , 255, 5, 0,0 , 0,0 , 5, 't', LTS_STATE_o_137 , LTS_STATE_o_136 , 2, 'o', LTS_STATE_o_36 , LTS_STATE_o_138 , 3, 't', LTS_STATE_o_60 , LTS_STATE_o_139 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_140 , 1, '#', LTS_STATE_o_141 , LTS_STATE_o_100 , 6, 's', LTS_STATE_o_14 , LTS_STATE_o_142 , 1, '#', LTS_STATE_o_20 , LTS_STATE_o_143 , 1, '#', LTS_STATE_o_10 , LTS_STATE_o_144 , 255, 52, 0,0 , 0,0 , 2, 'h', LTS_STATE_o_60 , LTS_STATE_o_53 , 3, 't', LTS_STATE_o_145 , LTS_STATE_o_36 , 5, 't', LTS_STATE_o_147 , LTS_STATE_o_146 , 3, 'd', LTS_STATE_o_87 , LTS_STATE_o_14 , 6, 'd', LTS_STATE_o_149 , LTS_STATE_o_148 , 6, '#', LTS_STATE_o_151 , LTS_STATE_o_150 , 6, 't', LTS_STATE_o_152 , LTS_STATE_o_40 , 3, 'd', LTS_STATE_o_40 , LTS_STATE_o_14 , 5, 'o', LTS_STATE_o_14 , LTS_STATE_o_153 , 6, 'g', LTS_STATE_o_155 , LTS_STATE_o_154 , 3, 'b', LTS_STATE_o_14 , LTS_STATE_o_156 , 3, 'm', LTS_STATE_o_158 , LTS_STATE_o_157 , 6, 'a', LTS_STATE_o_40 , LTS_STATE_o_159 , 3, 'f', LTS_STATE_o_40 , LTS_STATE_o_160 , 6, 'u', LTS_STATE_o_14 , LTS_STATE_o_40 , 5, 'e', LTS_STATE_o_162 , LTS_STATE_o_161 , 5, 'o', LTS_STATE_o_164 , LTS_STATE_o_163 , 6, 'g', LTS_STATE_o_166 , LTS_STATE_o_165 , 2, '#', LTS_STATE_o_168 , LTS_STATE_o_167 , 5, 'n', LTS_STATE_o_170 , LTS_STATE_o_169 , 1, '#', LTS_STATE_o_172 , LTS_STATE_o_171 , 5, 'g', LTS_STATE_o_174 , LTS_STATE_o_173 , 6, '#', LTS_STATE_o_176 , LTS_STATE_o_175 , 5, 'e', LTS_STATE_o_178 , LTS_STATE_o_177 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_179 , 1, 'a', LTS_STATE_o_180 , LTS_STATE_o_100 , 5, 'n', LTS_STATE_o_182 , LTS_STATE_o_181 , 2, '0', LTS_STATE_o_20 , LTS_STATE_o_183 , 2, '#', LTS_STATE_o_185 , LTS_STATE_o_184 , 6, 't', LTS_STATE_o_187 , LTS_STATE_o_186 , 255, 9, 0,0 , 0,0 , 2, 't', LTS_STATE_o_20 , LTS_STATE_o_14 , 3, 'c', LTS_STATE_o_14 , LTS_STATE_o_188 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_189 , 5, 'h', LTS_STATE_o_190 , LTS_STATE_o_10 , 1, 'r', LTS_STATE_o_36 , LTS_STATE_o_191 , 5, 'm', LTS_STATE_o_193 , LTS_STATE_o_192 , 3, 'f', LTS_STATE_o_195 , LTS_STATE_o_194 , 6, 't', LTS_STATE_o_14 , LTS_STATE_o_196 , 2, 'a', LTS_STATE_o_14 , LTS_STATE_o_197 , 6, 'd', LTS_STATE_o_14 , LTS_STATE_o_87 , 1, 'r', LTS_STATE_o_87 , LTS_STATE_o_198 , 2, 'n', LTS_STATE_o_40 , LTS_STATE_o_87 , 3, 'h', LTS_STATE_o_40 , LTS_STATE_o_199 , 6, 'o', LTS_STATE_o_201 , LTS_STATE_o_200 , 2, '#', LTS_STATE_o_40 , LTS_STATE_o_14 , 3, 'd', LTS_STATE_o_40 , LTS_STATE_o_202 , 3, 'd', LTS_STATE_o_87 , LTS_STATE_o_203 , 6, 'n', LTS_STATE_o_87 , LTS_STATE_o_204 , 6, 'h', LTS_STATE_o_40 , LTS_STATE_o_205 , 3, 't', LTS_STATE_o_40 , LTS_STATE_o_206 , 2, '#', LTS_STATE_o_208 , LTS_STATE_o_207 , 4, 'v', LTS_STATE_o_210 , LTS_STATE_o_209 , 6, 'm', LTS_STATE_o_36 , LTS_STATE_o_211 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_212 , 5, 'r', LTS_STATE_o_214 , LTS_STATE_o_213 , 3, 'd', LTS_STATE_o_10 , LTS_STATE_o_215 , 6, '#', LTS_STATE_o_217 , LTS_STATE_o_216 , 3, 'l', LTS_STATE_o_218 , LTS_STATE_o_212 , 2, '#', LTS_STATE_o_220 , LTS_STATE_o_219 , 3, 'd', LTS_STATE_o_20 , LTS_STATE_o_221 , 3, 'k', LTS_STATE_o_223 , LTS_STATE_o_222 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_224 , 3, 'c', LTS_STATE_o_226 , LTS_STATE_o_225 , 3, 'c', LTS_STATE_o_228 , LTS_STATE_o_227 , 1, '0', LTS_STATE_o_230 , LTS_STATE_o_229 , 3, 'g', LTS_STATE_o_40 , LTS_STATE_o_231 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_232 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_233 , 2, 'g', LTS_STATE_o_100 , LTS_STATE_o_234 , 2, 'i', LTS_STATE_o_235 , LTS_STATE_o_100 , 5, 'l', LTS_STATE_o_237 , LTS_STATE_o_236 , 3, 'y', LTS_STATE_o_14 , LTS_STATE_o_238 , 6, '#', LTS_STATE_o_20 , LTS_STATE_o_239 , 1, '#', LTS_STATE_o_241 , LTS_STATE_o_240 , 3, 'd', LTS_STATE_o_243 , LTS_STATE_o_242 , 6, '#', LTS_STATE_o_245 , LTS_STATE_o_244 , 3, 'c', LTS_STATE_o_40 , LTS_STATE_o_87 , 3, 'h', LTS_STATE_o_20 , LTS_STATE_o_246 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_14 , 4, 't', LTS_STATE_o_10 , LTS_STATE_o_14 , 1, 'h', LTS_STATE_o_215 , LTS_STATE_o_36 , 3, 'f', LTS_STATE_o_248 , LTS_STATE_o_247 , 6, 'a', LTS_STATE_o_249 , LTS_STATE_o_40 , 6, 'u', LTS_STATE_o_14 , LTS_STATE_o_250 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_251 , 6, 'l', LTS_STATE_o_87 , LTS_STATE_o_252 , 2, 'o', LTS_STATE_o_14 , LTS_STATE_o_253 , 2, 'r', LTS_STATE_o_40 , LTS_STATE_o_87 , 5, 'g', LTS_STATE_o_40 , LTS_STATE_o_254 , 5, 't', LTS_STATE_o_256 , LTS_STATE_o_255 , 3, 'f', LTS_STATE_o_258 , LTS_STATE_o_257 , 6, 'n', LTS_STATE_o_14 , LTS_STATE_o_259 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_260 , 6, 'l', LTS_STATE_o_40 , LTS_STATE_o_14 , 6, 'y', LTS_STATE_o_40 , LTS_STATE_o_261 , 3, 'b', LTS_STATE_o_87 , LTS_STATE_o_40 , 5, 'f', LTS_STATE_o_263 , LTS_STATE_o_262 , 4, 'm', LTS_STATE_o_265 , LTS_STATE_o_264 , 6, '#', LTS_STATE_o_267 , LTS_STATE_o_266 , 2, '0', LTS_STATE_o_269 , LTS_STATE_o_268 , 1, '0', LTS_STATE_o_212 , LTS_STATE_o_270 , 255, 34, 0,0 , 0,0 , 5, 'a', LTS_STATE_o_272 , LTS_STATE_o_271 , 1, '0', LTS_STATE_o_212 , LTS_STATE_o_217 , 255, 10, 0,0 , 0,0 , 3, 'l', LTS_STATE_o_212 , LTS_STATE_o_273 , 255, 53, 0,0 , 0,0 , 255, 54, 0,0 , 0,0 , 1, '#', LTS_STATE_o_275 , LTS_STATE_o_274 , 6, 'l', LTS_STATE_o_277 , LTS_STATE_o_276 , 3, 't', LTS_STATE_o_20 , LTS_STATE_o_278 , 3, 'n', LTS_STATE_o_36 , LTS_STATE_o_279 , 1, 'a', LTS_STATE_o_36 , LTS_STATE_o_140 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_20 , 1, '0', LTS_STATE_o_281 , LTS_STATE_o_280 , 6, '#', LTS_STATE_o_283 , LTS_STATE_o_282 , 1, '0', LTS_STATE_o_285 , LTS_STATE_o_284 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_286 , 1, '#', LTS_STATE_o_288 , LTS_STATE_o_287 , 6, 'y', LTS_STATE_o_290 , LTS_STATE_o_289 , 3, 'd', LTS_STATE_o_291 , LTS_STATE_o_215 , 1, '#', LTS_STATE_o_100 , LTS_STATE_o_292 , 6, 't', LTS_STATE_o_36 , LTS_STATE_o_100 , 2, 'n', LTS_STATE_o_294 , LTS_STATE_o_293 , 255, 15, 0,0 , 0,0 , 5, 'd', LTS_STATE_o_296 , LTS_STATE_o_295 , 2, 'o', LTS_STATE_o_100 , LTS_STATE_o_297 , 1, 'l', LTS_STATE_o_14 , LTS_STATE_o_298 , 3, 'm', LTS_STATE_o_300 , LTS_STATE_o_299 , 2, 'r', LTS_STATE_o_302 , LTS_STATE_o_301 , 2, 't', LTS_STATE_o_40 , LTS_STATE_o_303 , 3, 'c', LTS_STATE_o_40 , LTS_STATE_o_304 , 6, 'h', LTS_STATE_o_215 , LTS_STATE_o_14 , 3, 'j', LTS_STATE_o_14 , LTS_STATE_o_305 , 2, 'e', LTS_STATE_o_109 , LTS_STATE_o_306 , 6, 't', LTS_STATE_o_20 , LTS_STATE_o_14 , 5, 'a', LTS_STATE_o_308 , LTS_STATE_o_307 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_309 , 1, 'a', LTS_STATE_o_40 , LTS_STATE_o_310 , 1, 'r', LTS_STATE_o_40 , LTS_STATE_o_311 , 2, 'm', LTS_STATE_o_14 , LTS_STATE_o_40 , 2, 'l', LTS_STATE_o_40 , LTS_STATE_o_312 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_14 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_313 , 3, 'f', LTS_STATE_o_315 , LTS_STATE_o_314 , 6, 'r', LTS_STATE_o_87 , LTS_STATE_o_316 , 3, 't', LTS_STATE_o_87 , LTS_STATE_o_40 , 5, 'g', LTS_STATE_o_87 , LTS_STATE_o_40 , 3, 'm', LTS_STATE_o_14 , LTS_STATE_o_40 , 2, '#', LTS_STATE_o_318 , LTS_STATE_o_317 , 3, 's', LTS_STATE_o_40 , LTS_STATE_o_319 , 4, 'a', LTS_STATE_o_321 , LTS_STATE_o_320 , 4, 'f', LTS_STATE_o_323 , LTS_STATE_o_322 , 4, 'e', LTS_STATE_o_325 , LTS_STATE_o_324 , 3, 'c', LTS_STATE_o_327 , LTS_STATE_o_326 , 1, '0', LTS_STATE_o_329 , LTS_STATE_o_328 , 4, 'm', LTS_STATE_o_330 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_332 , LTS_STATE_o_331 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_34 , 3, 'u', LTS_STATE_o_212 , LTS_STATE_o_333 , 5, 'c', LTS_STATE_o_335 , LTS_STATE_o_334 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_36 , 3, 'a', LTS_STATE_o_20 , LTS_STATE_o_336 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_337 , 2, 's', LTS_STATE_o_215 , LTS_STATE_o_338 , 3, 'h', LTS_STATE_o_20 , LTS_STATE_o_339 , 5, 'a', LTS_STATE_o_140 , LTS_STATE_o_340 , 1, '#', LTS_STATE_o_342 , LTS_STATE_o_341 , 3, 'h', LTS_STATE_o_344 , LTS_STATE_o_343 , 6, 'c', LTS_STATE_o_346 , LTS_STATE_o_345 , 3, 'n', LTS_STATE_o_348 , LTS_STATE_o_347 , 5, 'a', LTS_STATE_o_92 , LTS_STATE_o_349 , 5, 'i', LTS_STATE_o_215 , LTS_STATE_o_92 , 1, '#', LTS_STATE_o_351 , LTS_STATE_o_350 , 6, 'o', LTS_STATE_o_353 , LTS_STATE_o_352 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 's', LTS_STATE_o_355 , LTS_STATE_o_354 , 2, 'l', LTS_STATE_o_14 , LTS_STATE_o_356 , 2, '#', LTS_STATE_o_358 , LTS_STATE_o_357 , 3, 'h', LTS_STATE_o_34 , LTS_STATE_o_359 , 2, 'r', LTS_STATE_o_215 , LTS_STATE_o_34 , 2, 's', LTS_STATE_o_100 , LTS_STATE_o_360 , 3, 'm', LTS_STATE_o_100 , LTS_STATE_o_361 , 3, 'd', LTS_STATE_o_100 , LTS_STATE_o_362 , 5, 'c', LTS_STATE_o_364 , LTS_STATE_o_363 , 3, 'b', LTS_STATE_o_14 , LTS_STATE_o_365 , 6, 'd', LTS_STATE_o_215 , LTS_STATE_o_366 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_367 , 6, 's', LTS_STATE_o_20 , LTS_STATE_o_368 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_100 , 2, 't', LTS_STATE_o_40 , LTS_STATE_o_369 , 1, 'u', LTS_STATE_o_36 , LTS_STATE_o_140 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_370 , 3, 'r', LTS_STATE_o_14 , LTS_STATE_o_371 , 6, 'a', LTS_STATE_o_14 , LTS_STATE_o_372 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_373 , 6, 'z', LTS_STATE_o_14 , LTS_STATE_o_374 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_375 , 5, 'c', LTS_STATE_o_40 , LTS_STATE_o_376 , 2, 'r', LTS_STATE_o_40 , LTS_STATE_o_377 , 2, 'p', LTS_STATE_o_40 , LTS_STATE_o_378 , 3, 'f', LTS_STATE_o_40 , LTS_STATE_o_379 , 5, 't', LTS_STATE_o_40 , LTS_STATE_o_380 , 6, 'z', LTS_STATE_o_14 , LTS_STATE_o_381 , 5, 'g', LTS_STATE_o_383 , LTS_STATE_o_382 , 6, 'e', LTS_STATE_o_384 , LTS_STATE_o_40 , 6, 't', LTS_STATE_o_40 , LTS_STATE_o_385 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_386 , 3, 'k', LTS_STATE_o_40 , LTS_STATE_o_387 , 5, '#', LTS_STATE_o_389 , LTS_STATE_o_388 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_390 , 3, 'k', LTS_STATE_o_87 , LTS_STATE_o_391 , 6, '#', LTS_STATE_o_393 , LTS_STATE_o_392 , 4, 'a', LTS_STATE_o_395 , LTS_STATE_o_394 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_396 , 5, 'a', LTS_STATE_o_398 , LTS_STATE_o_397 , 5, 'f', LTS_STATE_o_34 , LTS_STATE_o_399 , 4, 'm', LTS_STATE_o_401 , LTS_STATE_o_400 , 4, 'm', LTS_STATE_o_403 , LTS_STATE_o_402 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_404 , 3, 'm', LTS_STATE_o_10 , LTS_STATE_o_405 , 2, 'p', LTS_STATE_o_407 , LTS_STATE_o_406 , 2, 'e', LTS_STATE_o_409 , LTS_STATE_o_408 , 6, 'c', LTS_STATE_o_215 , LTS_STATE_o_410 , 6, 'e', LTS_STATE_o_212 , LTS_STATE_o_411 , 1, 'o', LTS_STATE_o_100 , LTS_STATE_o_412 , 6, 'c', LTS_STATE_o_100 , LTS_STATE_o_413 , 3, 'n', LTS_STATE_o_215 , LTS_STATE_o_414 , 3, 'c', LTS_STATE_o_20 , LTS_STATE_o_415 , 5, 'e', LTS_STATE_o_92 , LTS_STATE_o_20 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_416 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_215 , 3, 'd', LTS_STATE_o_36 , LTS_STATE_o_417 , 2, 'c', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 'i', LTS_STATE_o_419 , LTS_STATE_o_418 , 5, 'i', LTS_STATE_o_92 , LTS_STATE_o_36 , 5, 't', LTS_STATE_o_421 , LTS_STATE_o_420 , 5, 't', LTS_STATE_o_235 , LTS_STATE_o_422 , 1, '0', LTS_STATE_o_424 , LTS_STATE_o_423 , 6, '#', LTS_STATE_o_426 , LTS_STATE_o_425 , 2, 's', LTS_STATE_o_34 , LTS_STATE_o_40 , 6, 'a', LTS_STATE_o_92 , LTS_STATE_o_427 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_235 , 6, 'l', LTS_STATE_o_36 , LTS_STATE_o_428 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_215 , 2, 'e', LTS_STATE_o_92 , LTS_STATE_o_215 , 255, 55, 0,0 , 0,0 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_429 , 3, 'm', LTS_STATE_o_34 , LTS_STATE_o_215 , 6, '#', LTS_STATE_o_430 , LTS_STATE_o_100 , 1, '#', LTS_STATE_o_92 , LTS_STATE_o_431 , 1, 'i', LTS_STATE_o_100 , LTS_STATE_o_432 , 6, 't', LTS_STATE_o_434 , LTS_STATE_o_433 , 3, 't', LTS_STATE_o_14 , LTS_STATE_o_435 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_436 , 6, 't', LTS_STATE_o_215 , LTS_STATE_o_437 , 2, '#', LTS_STATE_o_20 , LTS_STATE_o_438 , 1, '#', LTS_STATE_o_20 , LTS_STATE_o_439 , 3, 'l', LTS_STATE_o_140 , LTS_STATE_o_440 , 2, 's', LTS_STATE_o_14 , LTS_STATE_o_20 , 3, 't', LTS_STATE_o_14 , LTS_STATE_o_441 , 6, 'i', LTS_STATE_o_14 , LTS_STATE_o_442 , 2, 'a', LTS_STATE_o_40 , LTS_STATE_o_14 , 3, 'u', LTS_STATE_o_60 , LTS_STATE_o_443 , 1, 'a', LTS_STATE_o_445 , LTS_STATE_o_444 , 6, 'a', LTS_STATE_o_40 , LTS_STATE_o_446 , 3, 'f', LTS_STATE_o_14 , LTS_STATE_o_40 , 3, 't', LTS_STATE_o_40 , LTS_STATE_o_447 , 3, 'c', LTS_STATE_o_40 , LTS_STATE_o_448 , 5, 'n', LTS_STATE_o_40 , LTS_STATE_o_449 , 6, 'n', LTS_STATE_o_40 , LTS_STATE_o_450 , 5, 'b', LTS_STATE_o_383 , LTS_STATE_o_40 , 6, 'i', LTS_STATE_o_14 , LTS_STATE_o_40 , 2, '#', LTS_STATE_o_40 , LTS_STATE_o_87 , 6, 'n', LTS_STATE_o_87 , LTS_STATE_o_40 , 3, 'f', LTS_STATE_o_40 , LTS_STATE_o_451 , 6, 't', LTS_STATE_o_87 , LTS_STATE_o_452 , 5, 'a', LTS_STATE_o_454 , LTS_STATE_o_453 , 4, 's', LTS_STATE_o_456 , LTS_STATE_o_455 , 2, 'b', LTS_STATE_o_458 , LTS_STATE_o_457 , 3, 'w', LTS_STATE_o_109 , LTS_STATE_o_459 , 6, 's', LTS_STATE_o_40 , LTS_STATE_o_460 , 3, 'l', LTS_STATE_o_87 , LTS_STATE_o_461 , 5, 'a', LTS_STATE_o_463 , LTS_STATE_o_462 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_464 , 6, 'r', LTS_STATE_o_40 , LTS_STATE_o_465 , 5, 'o', LTS_STATE_o_467 , LTS_STATE_o_466 , 3, 'w', LTS_STATE_o_60 , LTS_STATE_o_468 , 5, 'p', LTS_STATE_o_470 , LTS_STATE_o_469 , 4, 'k', LTS_STATE_o_215 , LTS_STATE_o_471 , 3, 'w', LTS_STATE_o_473 , LTS_STATE_o_472 , 4, 's', LTS_STATE_o_475 , LTS_STATE_o_474 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_476 , 3, 'c', LTS_STATE_o_34 , LTS_STATE_o_215 , 3, 'n', LTS_STATE_o_478 , LTS_STATE_o_477 , 1, '#', LTS_STATE_o_215 , LTS_STATE_o_479 , 1, '#', LTS_STATE_o_480 , LTS_STATE_o_10 , 5, '#', LTS_STATE_o_481 , LTS_STATE_o_212 , 5, '#', LTS_STATE_o_482 , LTS_STATE_o_218 , 1, 'h', LTS_STATE_o_36 , LTS_STATE_o_483 , 6, 'h', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'e', LTS_STATE_o_217 , LTS_STATE_o_36 , 2, 'k', LTS_STATE_o_485 , LTS_STATE_o_484 , 2, 'p', LTS_STATE_o_20 , LTS_STATE_o_486 , 3, 'd', LTS_STATE_o_20 , LTS_STATE_o_487 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_488 , 2, 'g', LTS_STATE_o_215 , LTS_STATE_o_489 , 2, 'f', LTS_STATE_o_491 , LTS_STATE_o_490 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_492 , 5, 'a', LTS_STATE_o_494 , LTS_STATE_o_493 , 3, 'm', LTS_STATE_o_496 , LTS_STATE_o_495 , 5, 'a', LTS_STATE_o_92 , LTS_STATE_o_497 , 2, 'e', LTS_STATE_o_499 , LTS_STATE_o_498 , 6, 'e', LTS_STATE_o_501 , LTS_STATE_o_500 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_502 , 3, 'r', LTS_STATE_o_40 , LTS_STATE_o_503 , 6, 'i', LTS_STATE_o_36 , LTS_STATE_o_504 , 3, 'p', LTS_STATE_o_215 , LTS_STATE_o_505 , 3, 'd', LTS_STATE_o_92 , LTS_STATE_o_506 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_215 , 2, 'r', LTS_STATE_o_508 , LTS_STATE_o_507 , 1, 'o', LTS_STATE_o_100 , LTS_STATE_o_509 , 5, 'f', LTS_STATE_o_511 , LTS_STATE_o_510 , 5, 'e', LTS_STATE_o_14 , LTS_STATE_o_20 , 6, 'h', LTS_STATE_o_20 , LTS_STATE_o_512 , 3, 'l', LTS_STATE_o_20 , LTS_STATE_o_513 , 3, 'f', LTS_STATE_o_20 , LTS_STATE_o_514 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_515 , 6, 'e', LTS_STATE_o_513 , LTS_STATE_o_516 , 2, 'b', LTS_STATE_o_140 , LTS_STATE_o_517 , 6, 'h', LTS_STATE_o_519 , LTS_STATE_o_518 , 3, 'b', LTS_STATE_o_521 , LTS_STATE_o_520 , 5, 'o', LTS_STATE_o_523 , LTS_STATE_o_522 , 6, 't', LTS_STATE_o_14 , LTS_STATE_o_524 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_40 , 5, 'g', LTS_STATE_o_14 , LTS_STATE_o_525 , 1, 'e', LTS_STATE_o_526 , LTS_STATE_o_40 , 2, 'n', LTS_STATE_o_14 , LTS_STATE_o_527 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_528 , 3, 'k', LTS_STATE_o_40 , LTS_STATE_o_529 , 3, 'b', LTS_STATE_o_40 , LTS_STATE_o_530 , 3, 'm', LTS_STATE_o_532 , LTS_STATE_o_531 , 4, 'e', LTS_STATE_o_534 , LTS_STATE_o_533 , 6, '#', LTS_STATE_o_536 , LTS_STATE_o_535 , 4, 'e', LTS_STATE_o_538 , LTS_STATE_o_537 , 1, 'o', LTS_STATE_o_540 , LTS_STATE_o_539 , 3, 'r', LTS_STATE_o_542 , LTS_STATE_o_541 , 5, 'd', LTS_STATE_o_40 , LTS_STATE_o_215 , 4, 'l', LTS_STATE_o_544 , LTS_STATE_o_543 , 1, '#', LTS_STATE_o_546 , LTS_STATE_o_545 , 1, '#', LTS_STATE_o_40 , LTS_STATE_o_547 , 4, 'l', LTS_STATE_o_549 , LTS_STATE_o_548 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_550 , 6, 'u', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 'w', LTS_STATE_o_92 , LTS_STATE_o_215 , 5, 'i', LTS_STATE_o_92 , LTS_STATE_o_551 , 6, 'l', LTS_STATE_o_100 , LTS_STATE_o_552 , 6, 'l', LTS_STATE_o_100 , LTS_STATE_o_553 , 5, 'm', LTS_STATE_o_555 , LTS_STATE_o_554 , 6, 'a', LTS_STATE_o_100 , LTS_STATE_o_556 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_557 , 6, 't', LTS_STATE_o_559 , LTS_STATE_o_558 , 255, 12, 0,0 , 0,0 , 6, 'r', LTS_STATE_o_561 , LTS_STATE_o_560 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_562 , 3, 's', LTS_STATE_o_34 , LTS_STATE_o_563 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_564 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_565 , 2, 'g', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_10 , 1, 'r', LTS_STATE_o_218 , LTS_STATE_o_566 , 3, 'r', LTS_STATE_o_218 , LTS_STATE_o_212 , 5, 'e', LTS_STATE_o_217 , LTS_STATE_o_567 , 3, 'p', LTS_STATE_o_20 , LTS_STATE_o_568 , 1, 'c', LTS_STATE_o_92 , LTS_STATE_o_215 , 5, 'd', LTS_STATE_o_20 , LTS_STATE_o_569 , 3, 'p', LTS_STATE_o_20 , LTS_STATE_o_570 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_215 , 2, 'd', LTS_STATE_o_572 , LTS_STATE_o_571 , 1, '#', LTS_STATE_o_574 , LTS_STATE_o_573 , 5, 't', LTS_STATE_o_575 , LTS_STATE_o_92 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_576 , 5, 'i', LTS_STATE_o_578 , LTS_STATE_o_577 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_579 , 6, 'i', LTS_STATE_o_235 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_580 , 5, 'v', LTS_STATE_o_235 , LTS_STATE_o_581 , 5, 'i', LTS_STATE_o_215 , LTS_STATE_o_582 , 1, '#', LTS_STATE_o_92 , LTS_STATE_o_100 , 5, 'n', LTS_STATE_o_584 , LTS_STATE_o_583 , 5, 'c', LTS_STATE_o_100 , LTS_STATE_o_585 , 3, 'r', LTS_STATE_o_40 , LTS_STATE_o_92 , 1, 'a', LTS_STATE_o_40 , LTS_STATE_o_586 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_587 , 6, 'y', LTS_STATE_o_589 , LTS_STATE_o_588 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_215 , 2, 'a', LTS_STATE_o_591 , LTS_STATE_o_590 , 1, 'a', LTS_STATE_o_592 , LTS_STATE_o_100 , 1, 'a', LTS_STATE_o_100 , LTS_STATE_o_593 , 1, '0', LTS_STATE_o_594 , LTS_STATE_o_14 , 6, 'f', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'e', LTS_STATE_o_14 , LTS_STATE_o_215 , 1, '0', LTS_STATE_o_20 , LTS_STATE_o_14 , 3, 'c', LTS_STATE_o_20 , LTS_STATE_o_595 , 1, 'e', LTS_STATE_o_20 , LTS_STATE_o_596 , 3, 's', LTS_STATE_o_20 , LTS_STATE_o_597 , 1, 't', LTS_STATE_o_14 , LTS_STATE_o_598 , 6, 'e', LTS_STATE_o_20 , LTS_STATE_o_14 , 3, 'l', LTS_STATE_o_20 , LTS_STATE_o_599 , 1, '#', LTS_STATE_o_14 , LTS_STATE_o_600 , 6, 'n', LTS_STATE_o_602 , LTS_STATE_o_601 , 6, 'a', LTS_STATE_o_604 , LTS_STATE_o_603 , 6, 'u', LTS_STATE_o_14 , LTS_STATE_o_605 , 3, 'm', LTS_STATE_o_606 , LTS_STATE_o_14 , 6, 's', LTS_STATE_o_14 , LTS_STATE_o_40 , 2, 'x', LTS_STATE_o_40 , LTS_STATE_o_607 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_608 , 2, 'a', LTS_STATE_o_610 , LTS_STATE_o_609 , 6, 'a', LTS_STATE_o_257 , LTS_STATE_o_611 , 6, 'n', LTS_STATE_o_87 , LTS_STATE_o_612 , 6, 'n', LTS_STATE_o_614 , LTS_STATE_o_613 , 6, 'l', LTS_STATE_o_14 , LTS_STATE_o_87 , 4, 's', LTS_STATE_o_616 , LTS_STATE_o_615 , 3, 'h', LTS_STATE_o_618 , LTS_STATE_o_617 , 6, 't', LTS_STATE_o_620 , LTS_STATE_o_619 , 3, 'e', LTS_STATE_o_92 , LTS_STATE_o_621 , 4, 'm', LTS_STATE_o_623 , LTS_STATE_o_622 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_624 , 1, '#', LTS_STATE_o_36 , LTS_STATE_o_625 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_36 , 5, 'd', LTS_STATE_o_215 , LTS_STATE_o_626 , 6, 'h', LTS_STATE_o_215 , LTS_STATE_o_627 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_215 , LTS_STATE_o_36 , 1, '0', LTS_STATE_o_629 , LTS_STATE_o_628 , 2, 'r', LTS_STATE_o_40 , LTS_STATE_o_630 , 3, 'h', LTS_STATE_o_632 , LTS_STATE_o_631 , 5, 'i', LTS_STATE_o_634 , LTS_STATE_o_633 , 5, 'l', LTS_STATE_o_636 , LTS_STATE_o_635 , 3, 'k', LTS_STATE_o_638 , LTS_STATE_o_637 , 5, 'b', LTS_STATE_o_639 , LTS_STATE_o_92 , 3, 'k', LTS_STATE_o_36 , LTS_STATE_o_640 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_641 , 5, 'b', LTS_STATE_o_643 , LTS_STATE_o_642 , 6, 'o', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'i', LTS_STATE_o_100 , LTS_STATE_o_644 , 6, 'd', LTS_STATE_o_646 , LTS_STATE_o_645 , 6, 's', LTS_STATE_o_404 , LTS_STATE_o_647 , 1, '#', LTS_STATE_o_648 , LTS_STATE_o_92 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_649 , 2, '#', LTS_STATE_o_650 , LTS_STATE_o_92 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_651 , 3, 'c', LTS_STATE_o_653 , LTS_STATE_o_652 , 3, 's', LTS_STATE_o_215 , LTS_STATE_o_654 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_36 , 2, 'n', LTS_STATE_o_218 , LTS_STATE_o_655 , 6, 'e', LTS_STATE_o_212 , LTS_STATE_o_656 , 2, 'r', LTS_STATE_o_658 , LTS_STATE_o_657 , 3, 'l', LTS_STATE_o_660 , LTS_STATE_o_659 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_661 , 2, 'f', LTS_STATE_o_215 , LTS_STATE_o_662 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_36 , 5, 'a', LTS_STATE_o_664 , LTS_STATE_o_663 , 5, 'o', LTS_STATE_o_666 , LTS_STATE_o_665 , 6, 'e', LTS_STATE_o_34 , LTS_STATE_o_667 , 6, 'z', LTS_STATE_o_669 , LTS_STATE_o_668 , 5, 'y', LTS_STATE_o_215 , LTS_STATE_o_670 , 6, 'n', LTS_STATE_o_672 , LTS_STATE_o_671 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_673 , 6, 'a', LTS_STATE_o_36 , LTS_STATE_o_92 , 5, 'r', LTS_STATE_o_235 , LTS_STATE_o_674 , 2, 'b', LTS_STATE_o_92 , LTS_STATE_o_675 , 5, 'r', LTS_STATE_o_92 , LTS_STATE_o_676 , 6, 'i', LTS_STATE_o_100 , LTS_STATE_o_92 , 5, 'v', LTS_STATE_o_100 , LTS_STATE_o_677 , 2, 'e', LTS_STATE_o_40 , LTS_STATE_o_678 , 6, 'u', LTS_STATE_o_34 , LTS_STATE_o_679 , 1, 'a', LTS_STATE_o_233 , LTS_STATE_o_100 , 1, 'm', LTS_STATE_o_215 , LTS_STATE_o_100 , 1, 'd', LTS_STATE_o_100 , LTS_STATE_o_680 , 1, 'e', LTS_STATE_o_100 , LTS_STATE_o_681 , 3, 'd', LTS_STATE_o_40 , LTS_STATE_o_100 , 3, 'n', LTS_STATE_o_100 , LTS_STATE_o_235 , 5, 'e', LTS_STATE_o_92 , LTS_STATE_o_682 , 3, 's', LTS_STATE_o_14 , LTS_STATE_o_683 , 1, 'a', LTS_STATE_o_20 , LTS_STATE_o_684 , 3, 'b', LTS_STATE_o_14 , LTS_STATE_o_685 , 3, 'd', LTS_STATE_o_14 , LTS_STATE_o_20 , 3, 'b', LTS_STATE_o_20 , LTS_STATE_o_40 , 1, 'r', LTS_STATE_o_87 , LTS_STATE_o_686 , 1, '0', LTS_STATE_o_687 , LTS_STATE_o_40 , 1, '0', LTS_STATE_o_40 , LTS_STATE_o_60 , 5, 'p', LTS_STATE_o_689 , LTS_STATE_o_688 , 5, 'i', LTS_STATE_o_40 , LTS_STATE_o_690 , 3, 'b', LTS_STATE_o_14 , LTS_STATE_o_691 , 1, 'm', LTS_STATE_o_14 , LTS_STATE_o_692 , 3, 'p', LTS_STATE_o_40 , LTS_STATE_o_87 , 2, 's', LTS_STATE_o_40 , LTS_STATE_o_693 , 3, 'n', LTS_STATE_o_40 , LTS_STATE_o_694 , 5, 'e', LTS_STATE_o_40 , LTS_STATE_o_14 , 3, 'm', LTS_STATE_o_696 , LTS_STATE_o_695 , 3, 'h', LTS_STATE_o_87 , LTS_STATE_o_40 , 6, 'c', LTS_STATE_o_87 , LTS_STATE_o_697 , 3, 'l', LTS_STATE_o_87 , LTS_STATE_o_40 , 4, 'l', LTS_STATE_o_699 , LTS_STATE_o_698 , 5, 'i', LTS_STATE_o_701 , LTS_STATE_o_700 , 1, '#', LTS_STATE_o_703 , LTS_STATE_o_702 , 2, 's', LTS_STATE_o_10 , LTS_STATE_o_704 , 3, 'w', LTS_STATE_o_60 , LTS_STATE_o_705 , 1, 'h', LTS_STATE_o_14 , LTS_STATE_o_706 , 3, 's', LTS_STATE_o_215 , LTS_STATE_o_707 , 1, '#', LTS_STATE_o_709 , LTS_STATE_o_708 , 3, 'c', LTS_STATE_o_710 , LTS_STATE_o_499 , 1, 'i', LTS_STATE_o_215 , LTS_STATE_o_711 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_712 , 1, '#', LTS_STATE_o_215 , LTS_STATE_o_713 , 1, 'e', LTS_STATE_o_36 , LTS_STATE_o_344 , 1, 'i', LTS_STATE_o_100 , LTS_STATE_o_40 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_584 , 2, 's', LTS_STATE_o_92 , LTS_STATE_o_714 , 2, 'c', LTS_STATE_o_40 , LTS_STATE_o_715 , 2, 't', LTS_STATE_o_40 , LTS_STATE_o_716 , 5, 'o', LTS_STATE_o_718 , LTS_STATE_o_717 , 4, 'v', LTS_STATE_o_720 , LTS_STATE_o_719 , 5, 'o', LTS_STATE_o_722 , LTS_STATE_o_721 , 3, 'c', LTS_STATE_o_724 , LTS_STATE_o_723 , 3, 'l', LTS_STATE_o_726 , LTS_STATE_o_725 , 6, 'k', LTS_STATE_o_215 , LTS_STATE_o_727 , 6, 'a', LTS_STATE_o_729 , LTS_STATE_o_728 , 6, 'g', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_730 , 6, 'n', LTS_STATE_o_100 , LTS_STATE_o_731 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_732 , 6, 's', LTS_STATE_o_734 , LTS_STATE_o_733 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_735 , 3, 'r', LTS_STATE_o_737 , LTS_STATE_o_736 , 2, 'g', LTS_STATE_o_100 , LTS_STATE_o_92 , 4, 'd', LTS_STATE_o_739 , LTS_STATE_o_738 , 3, 'm', LTS_STATE_o_741 , LTS_STATE_o_740 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_215 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_742 , 6, 'd', LTS_STATE_o_100 , LTS_STATE_o_34 , 3, 'c', LTS_STATE_o_744 , LTS_STATE_o_743 , 1, 'e', LTS_STATE_o_212 , LTS_STATE_o_745 , 5, 'd', LTS_STATE_o_746 , LTS_STATE_o_212 , 2, 'l', LTS_STATE_o_748 , LTS_STATE_o_747 , 3, 'r', LTS_STATE_o_36 , LTS_STATE_o_215 , 2, 'b', LTS_STATE_o_20 , LTS_STATE_o_749 , 6, 'r', LTS_STATE_o_20 , LTS_STATE_o_215 , 3, 'n', LTS_STATE_o_20 , LTS_STATE_o_750 , 2, 'k', LTS_STATE_o_140 , LTS_STATE_o_751 , 5, 't', LTS_STATE_o_753 , LTS_STATE_o_752 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_754 , 2, 'l', LTS_STATE_o_14 , LTS_STATE_o_755 , 2, 'p', LTS_STATE_o_100 , LTS_STATE_o_756 , 6, 'a', LTS_STATE_o_100 , LTS_STATE_o_34 , 6, 'o', LTS_STATE_o_215 , LTS_STATE_o_757 , 3, 'r', LTS_STATE_o_14 , LTS_STATE_o_100 , 3, 'w', LTS_STATE_o_759 , LTS_STATE_o_758 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_760 , 3, 'b', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'g', LTS_STATE_o_92 , LTS_STATE_o_761 , 5, 'b', LTS_STATE_o_92 , LTS_STATE_o_762 , 5, 't', LTS_STATE_o_764 , LTS_STATE_o_763 , 5, 'd', LTS_STATE_o_766 , LTS_STATE_o_765 , 5, 't', LTS_STATE_o_100 , LTS_STATE_o_767 , 3, 's', LTS_STATE_o_40 , LTS_STATE_o_87 , 3, 'm', LTS_STATE_o_34 , LTS_STATE_o_40 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_768 , 3, 'n', LTS_STATE_o_100 , LTS_STATE_o_769 , 3, 'b', LTS_STATE_o_14 , LTS_STATE_o_770 , 6, 's', LTS_STATE_o_20 , LTS_STATE_o_14 , 1, '#', LTS_STATE_o_20 , LTS_STATE_o_771 , 3, 'c', LTS_STATE_o_14 , LTS_STATE_o_772 , 6, 'e', LTS_STATE_o_14 , LTS_STATE_o_40 , 6, 'g', LTS_STATE_o_109 , LTS_STATE_o_14 , 5, 'd', LTS_STATE_o_774 , LTS_STATE_o_773 , 2, 't', LTS_STATE_o_87 , LTS_STATE_o_775 , 5, 'g', LTS_STATE_o_40 , LTS_STATE_o_776 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_777 , 2, 'e', LTS_STATE_o_40 , LTS_STATE_o_14 , 2, 'a', LTS_STATE_o_40 , LTS_STATE_o_253 , 2, 'd', LTS_STATE_o_40 , LTS_STATE_o_14 , 6, 'e', LTS_STATE_o_779 , LTS_STATE_o_778 , 5, 'i', LTS_STATE_o_780 , LTS_STATE_o_40 , 3, 'f', LTS_STATE_o_40 , LTS_STATE_o_781 , 1, '#', LTS_STATE_o_783 , LTS_STATE_o_782 , 6, 'g', LTS_STATE_o_785 , LTS_STATE_o_784 , 5, 'k', LTS_STATE_o_787 , LTS_STATE_o_786 , 6, 't', LTS_STATE_o_789 , LTS_STATE_o_788 , 1, '0', LTS_STATE_o_215 , LTS_STATE_o_790 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_791 , 1, 's', LTS_STATE_o_215 , LTS_STATE_o_792 , 1, '#', LTS_STATE_o_794 , LTS_STATE_o_793 , 3, 'n', LTS_STATE_o_100 , LTS_STATE_o_795 , 4, 'l', LTS_STATE_o_796 , LTS_STATE_o_215 , 4, 'v', LTS_STATE_o_798 , LTS_STATE_o_797 , 4, 'l', LTS_STATE_o_100 , LTS_STATE_o_92 , 1, 'n', LTS_STATE_o_92 , LTS_STATE_o_799 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_36 , 3, 'i', LTS_STATE_o_801 , LTS_STATE_o_800 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_802 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 't', LTS_STATE_o_87 , LTS_STATE_o_803 , 1, 'e', LTS_STATE_o_40 , LTS_STATE_o_87 , 4, 'h', LTS_STATE_o_805 , LTS_STATE_o_804 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_806 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_807 , 3, 'm', LTS_STATE_o_10 , LTS_STATE_o_808 , 5, 'i', LTS_STATE_o_810 , LTS_STATE_o_809 , 6, 'r', LTS_STATE_o_34 , LTS_STATE_o_811 , 3, 'r', LTS_STATE_o_813 , LTS_STATE_o_812 , 6, 'a', LTS_STATE_o_100 , LTS_STATE_o_814 , 3, 'b', LTS_STATE_o_816 , LTS_STATE_o_815 , 4, 'c', LTS_STATE_o_215 , LTS_STATE_o_817 , 6, 'l', LTS_STATE_o_100 , LTS_STATE_o_818 , 3, 'd', LTS_STATE_o_100 , LTS_STATE_o_819 , 3, 'b', LTS_STATE_o_235 , LTS_STATE_o_92 , 3, 't', LTS_STATE_o_821 , LTS_STATE_o_820 , 6, 't', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 'o', LTS_STATE_o_100 , LTS_STATE_o_822 , 6, 'r', LTS_STATE_o_824 , LTS_STATE_o_823 , 4, 'c', LTS_STATE_o_92 , LTS_STATE_o_825 , 2, 'i', LTS_STATE_o_100 , LTS_STATE_o_826 , 2, 'g', LTS_STATE_o_92 , LTS_STATE_o_827 , 1, '#', LTS_STATE_o_215 , LTS_STATE_o_36 , 6, 'n', LTS_STATE_o_829 , LTS_STATE_o_828 , 6, 'l', LTS_STATE_o_831 , LTS_STATE_o_830 , 3, 't', LTS_STATE_o_92 , LTS_STATE_o_832 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 'd', LTS_STATE_o_833 , LTS_STATE_o_215 , 1, '0', LTS_STATE_o_835 , LTS_STATE_o_834 , 6, 'r', LTS_STATE_o_34 , LTS_STATE_o_836 , 2, 'l', LTS_STATE_o_837 , LTS_STATE_o_212 , 3, 'v', LTS_STATE_o_212 , LTS_STATE_o_838 , 3, 'd', LTS_STATE_o_840 , LTS_STATE_o_839 , 3, 'l', LTS_STATE_o_841 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_842 , LTS_STATE_o_20 , 5, 'a', LTS_STATE_o_844 , LTS_STATE_o_843 , 2, 't', LTS_STATE_o_846 , LTS_STATE_o_845 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_847 , 6, 'e', LTS_STATE_o_506 , LTS_STATE_o_848 , 2, 'c', LTS_STATE_o_92 , LTS_STATE_o_849 , 2, 'i', LTS_STATE_o_14 , LTS_STATE_o_850 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'u', LTS_STATE_o_215 , LTS_STATE_o_851 , 6, 'p', LTS_STATE_o_100 , LTS_STATE_o_852 , 6, 'e', LTS_STATE_o_34 , LTS_STATE_o_92 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_853 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_854 , 6, 'u', LTS_STATE_o_235 , LTS_STATE_o_855 , 2, 'c', LTS_STATE_o_92 , LTS_STATE_o_856 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_857 , 5, 'q', LTS_STATE_o_92 , LTS_STATE_o_858 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_859 , 5, 'f', LTS_STATE_o_100 , LTS_STATE_o_860 , 2, 't', LTS_STATE_o_862 , LTS_STATE_o_861 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_863 , 5, 'k', LTS_STATE_o_20 , LTS_STATE_o_864 , 6, 'c', LTS_STATE_o_20 , LTS_STATE_o_865 , 3, 'r', LTS_STATE_o_14 , LTS_STATE_o_866 , 3, 't', LTS_STATE_o_868 , LTS_STATE_o_867 , 6, 'e', LTS_STATE_o_40 , LTS_STATE_o_869 , 3, 'c', LTS_STATE_o_40 , LTS_STATE_o_870 , 1, 'r', LTS_STATE_o_40 , LTS_STATE_o_777 , 2, 'o', LTS_STATE_o_14 , LTS_STATE_o_40 , 6, 'l', LTS_STATE_o_871 , LTS_STATE_o_40 , 5, 'd', LTS_STATE_o_40 , LTS_STATE_o_872 , 6, 's', LTS_STATE_o_40 , LTS_STATE_o_87 , 6, 'l', LTS_STATE_o_87 , LTS_STATE_o_40 , 6, '#', LTS_STATE_o_874 , LTS_STATE_o_873 , 5, 'o', LTS_STATE_o_876 , LTS_STATE_o_875 , 5, 'd', LTS_STATE_o_878 , LTS_STATE_o_877 , 1, '0', LTS_STATE_o_92 , LTS_STATE_o_879 , 1, '0', LTS_STATE_o_881 , LTS_STATE_o_880 , 6, 'i', LTS_STATE_o_20 , LTS_STATE_o_882 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_883 , 3, 'p', LTS_STATE_o_884 , LTS_STATE_o_92 , 2, 'h', LTS_STATE_o_215 , LTS_STATE_o_885 , 5, 'b', LTS_STATE_o_215 , LTS_STATE_o_886 , 5, 'n', LTS_STATE_o_100 , LTS_STATE_o_36 , 1, '0', LTS_STATE_o_888 , LTS_STATE_o_887 , 4, 'p', LTS_STATE_o_890 , LTS_STATE_o_889 , 1, 'a', LTS_STATE_o_100 , LTS_STATE_o_891 , 1, 'r', LTS_STATE_o_215 , LTS_STATE_o_892 , 4, 'l', LTS_STATE_o_894 , LTS_STATE_o_893 , 2, 'o', LTS_STATE_o_92 , LTS_STATE_o_235 , 1, 'r', LTS_STATE_o_92 , LTS_STATE_o_895 , 3, 'g', LTS_STATE_o_36 , LTS_STATE_o_896 , 2, 'r', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 'k', LTS_STATE_o_215 , LTS_STATE_o_897 , 1, 'o', LTS_STATE_o_87 , LTS_STATE_o_898 , 4, 's', LTS_STATE_o_900 , LTS_STATE_o_899 , 5, 'r', LTS_STATE_o_40 , LTS_STATE_o_901 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_902 , 6, 't', LTS_STATE_o_92 , LTS_STATE_o_903 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_904 , 5, 'y', LTS_STATE_o_906 , LTS_STATE_o_905 , 6, 'n', LTS_STATE_o_908 , LTS_STATE_o_907 , 3, 'c', LTS_STATE_o_833 , LTS_STATE_o_909 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_910 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_911 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_912 , 4, 's', LTS_STATE_o_914 , LTS_STATE_o_913 , 4, 'l', LTS_STATE_o_215 , LTS_STATE_o_915 , 6, 't', LTS_STATE_o_36 , LTS_STATE_o_916 , 4, 'l', LTS_STATE_o_100 , LTS_STATE_o_917 , 3, 't', LTS_STATE_o_10 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_36 , LTS_STATE_o_918 , 6, 's', LTS_STATE_o_36 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_919 , 1, '#', LTS_STATE_o_921 , LTS_STATE_o_920 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_922 , 4, 'f', LTS_STATE_o_100 , LTS_STATE_o_923 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_215 , 1, 'h', LTS_STATE_o_92 , LTS_STATE_o_924 , 4, 'b', LTS_STATE_o_926 , LTS_STATE_o_925 , 4, 'z', LTS_STATE_o_40 , LTS_STATE_o_927 , 6, 's', LTS_STATE_o_506 , LTS_STATE_o_928 , 2, '#', LTS_STATE_o_92 , LTS_STATE_o_36 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_929 , 6, 'n', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'r', LTS_STATE_o_931 , LTS_STATE_o_930 , 3, 'b', LTS_STATE_o_215 , LTS_STATE_o_932 , 6, 'n', LTS_STATE_o_34 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_212 , LTS_STATE_o_218 , 2, 'e', LTS_STATE_o_212 , LTS_STATE_o_933 , 1, 't', LTS_STATE_o_215 , LTS_STATE_o_934 , 5, 's', LTS_STATE_o_36 , LTS_STATE_o_935 , 1, 'a', LTS_STATE_o_936 , LTS_STATE_o_36 , 5, 'l', LTS_STATE_o_20 , LTS_STATE_o_937 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_938 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_20 , 2, 'o', LTS_STATE_o_36 , LTS_STATE_o_939 , 3, 'l', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 's', LTS_STATE_o_941 , LTS_STATE_o_940 , 1, 'r', LTS_STATE_o_943 , LTS_STATE_o_942 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_944 , 5, 'y', LTS_STATE_o_215 , LTS_STATE_o_945 , 6, 'n', LTS_STATE_o_947 , LTS_STATE_o_946 , 2, '#', LTS_STATE_o_949 , LTS_STATE_o_948 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_950 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_951 , 6, 'i', LTS_STATE_o_235 , LTS_STATE_o_952 , 5, 'v', LTS_STATE_o_100 , LTS_STATE_o_953 , 1, 'u', LTS_STATE_o_100 , LTS_STATE_o_954 , 5, 'j', LTS_STATE_o_92 , LTS_STATE_o_955 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_584 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_956 , 2, 'e', LTS_STATE_o_958 , LTS_STATE_o_957 , 3, 'r', LTS_STATE_o_959 , LTS_STATE_o_100 , 1, 'm', LTS_STATE_o_100 , LTS_STATE_o_960 , 5, 'p', LTS_STATE_o_14 , LTS_STATE_o_961 , 2, 'n', LTS_STATE_o_20 , LTS_STATE_o_962 , 6, 'h', LTS_STATE_o_14 , LTS_STATE_o_20 , 6, 'c', LTS_STATE_o_40 , LTS_STATE_o_963 , 2, 'a', LTS_STATE_o_40 , LTS_STATE_o_964 , 3, 'c', LTS_STATE_o_965 , LTS_STATE_o_40 , 3, 'm', LTS_STATE_o_40 , LTS_STATE_o_14 , 5, 'i', LTS_STATE_o_14 , LTS_STATE_o_40 , 5, 'g', LTS_STATE_o_40 , LTS_STATE_o_966 , 5, 't', LTS_STATE_o_968 , LTS_STATE_o_967 , 5, 'o', LTS_STATE_o_215 , LTS_STATE_o_969 , 2, 's', LTS_STATE_o_971 , LTS_STATE_o_970 , 4, 't', LTS_STATE_o_215 , LTS_STATE_o_972 , 6, 'r', LTS_STATE_o_34 , LTS_STATE_o_973 , 3, 'n', LTS_STATE_o_975 , LTS_STATE_o_974 , 2, 'p', LTS_STATE_o_92 , LTS_STATE_o_976 , 5, 's', LTS_STATE_o_978 , LTS_STATE_o_977 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_979 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_980 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_981 , 2, 'e', LTS_STATE_o_92 , LTS_STATE_o_982 , 1, 'o', LTS_STATE_o_215 , LTS_STATE_o_983 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_984 , 4, 'v', LTS_STATE_o_986 , LTS_STATE_o_985 , 4, 'h', LTS_STATE_o_235 , LTS_STATE_o_987 , 6, 'n', LTS_STATE_o_989 , LTS_STATE_o_988 , 2, 'p', LTS_STATE_o_92 , LTS_STATE_o_14 , 2, 'e', LTS_STATE_o_991 , LTS_STATE_o_990 , 2, 'n', LTS_STATE_o_992 , LTS_STATE_o_215 , 4, 'x', LTS_STATE_o_994 , LTS_STATE_o_993 , 2, 't', LTS_STATE_o_235 , LTS_STATE_o_995 , 2, 'i', LTS_STATE_o_235 , LTS_STATE_o_996 , 2, 't', LTS_STATE_o_36 , LTS_STATE_o_997 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_998 , 2, 't', LTS_STATE_o_87 , LTS_STATE_o_999 , 4, 'f', LTS_STATE_o_1001 , LTS_STATE_o_1000 , 5, 's', LTS_STATE_o_1003 , LTS_STATE_o_1002 , 3, 'j', LTS_STATE_o_92 , LTS_STATE_o_1004 , 3, 'm', LTS_STATE_o_215 , LTS_STATE_o_1005 , 4, 't', LTS_STATE_o_215 , LTS_STATE_o_1006 , 3, 'l', LTS_STATE_o_34 , LTS_STATE_o_1007 , 3, 'w', LTS_STATE_o_1009 , LTS_STATE_o_1008 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'c', LTS_STATE_o_1011 , LTS_STATE_o_1010 , 3, 'm', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'm', LTS_STATE_o_100 , LTS_STATE_o_1012 , 3, 't', LTS_STATE_o_1014 , LTS_STATE_o_1013 , 6, 'i', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'o', LTS_STATE_o_100 , LTS_STATE_o_1015 , 3, 'c', LTS_STATE_o_1017 , LTS_STATE_o_1016 , 6, 'l', LTS_STATE_o_215 , LTS_STATE_o_36 , 4, 'h', LTS_STATE_o_92 , LTS_STATE_o_1018 , 4, 'v', LTS_STATE_o_34 , LTS_STATE_o_36 , 4, 'v', LTS_STATE_o_100 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_36 , LTS_STATE_o_1019 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_1020 , 3, 'm', LTS_STATE_o_1022 , LTS_STATE_o_1021 , 4, 's', LTS_STATE_o_92 , LTS_STATE_o_1023 , 2, 'n', LTS_STATE_o_92 , LTS_STATE_o_1024 , 2, 'a', LTS_STATE_o_100 , LTS_STATE_o_1025 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_1026 , 6, 'y', LTS_STATE_o_215 , LTS_STATE_o_1027 , 2, '#', LTS_STATE_o_215 , LTS_STATE_o_36 , 4, 't', LTS_STATE_o_215 , LTS_STATE_o_1028 , 3, 'r', LTS_STATE_o_1030 , LTS_STATE_o_1029 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_1031 , 2, 'n', LTS_STATE_o_34 , LTS_STATE_o_1032 , 3, 'l', LTS_STATE_o_34 , LTS_STATE_o_1033 , 2, 'a', LTS_STATE_o_212 , LTS_STATE_o_1034 , 2, 'n', LTS_STATE_o_1036 , LTS_STATE_o_1035 , 2, 'a', LTS_STATE_o_36 , LTS_STATE_o_20 , 5, 'e', LTS_STATE_o_36 , LTS_STATE_o_1037 , 2, 'g', LTS_STATE_o_215 , LTS_STATE_o_1038 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_1039 , 3, 's', LTS_STATE_o_36 , LTS_STATE_o_1040 , 3, 'm', LTS_STATE_o_1042 , LTS_STATE_o_1041 , 6, '#', LTS_STATE_o_1044 , LTS_STATE_o_1043 , 6, 'o', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'e', LTS_STATE_o_235 , LTS_STATE_o_92 , 2, 'i', LTS_STATE_o_36 , LTS_STATE_o_1045 , 5, 'a', LTS_STATE_o_1047 , LTS_STATE_o_1046 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_1048 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_1049 , 6, 'o', LTS_STATE_o_235 , LTS_STATE_o_1050 , 3, 'h', LTS_STATE_o_92 , LTS_STATE_o_1051 , 6, 'g', LTS_STATE_o_92 , LTS_STATE_o_1052 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_1053 , 5, 'p', LTS_STATE_o_1055 , LTS_STATE_o_1054 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_1056 , 2, 's', LTS_STATE_o_100 , LTS_STATE_o_92 , 5, 'l', LTS_STATE_o_92 , LTS_STATE_o_1057 , 5, 'n', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'u', LTS_STATE_o_1059 , LTS_STATE_o_1058 , 1, 'r', LTS_STATE_o_235 , LTS_STATE_o_1060 , 1, 'e', LTS_STATE_o_235 , LTS_STATE_o_996 , 1, 'r', LTS_STATE_o_92 , LTS_STATE_o_1061 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_1062 , 3, 'm', LTS_STATE_o_20 , LTS_STATE_o_1063 , 6, 'i', LTS_STATE_o_40 , LTS_STATE_o_1064 , 2, 'c', LTS_STATE_o_14 , LTS_STATE_o_1065 , 2, 'c', LTS_STATE_o_40 , LTS_STATE_o_1066 , 5, 's', LTS_STATE_o_40 , LTS_STATE_o_1067 , 4, 'm', LTS_STATE_o_1069 , LTS_STATE_o_1068 , 1, '0', LTS_STATE_o_1071 , LTS_STATE_o_1070 , 5, 'i', LTS_STATE_o_215 , LTS_STATE_o_1072 , 5, 'k', LTS_STATE_o_92 , LTS_STATE_o_1073 , 5, 'i', LTS_STATE_o_215 , LTS_STATE_o_1074 , 4, 'p', LTS_STATE_o_1076 , LTS_STATE_o_1075 , 6, '#', LTS_STATE_o_1078 , LTS_STATE_o_1077 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1079 , 6, '#', LTS_STATE_o_36 , LTS_STATE_o_100 , 3, 'e', LTS_STATE_o_1081 , LTS_STATE_o_1080 , 1, '#', LTS_STATE_o_1083 , LTS_STATE_o_1082 , 2, 'c', LTS_STATE_o_40 , LTS_STATE_o_1084 , 5, 'h', LTS_STATE_o_92 , LTS_STATE_o_1085 , 1, '#', LTS_STATE_o_40 , LTS_STATE_o_215 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_1086 , 2, 'm', LTS_STATE_o_92 , LTS_STATE_o_100 , 5, 's', LTS_STATE_o_36 , LTS_STATE_o_1087 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1088 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_1089 , 6, 'l', LTS_STATE_o_10 , LTS_STATE_o_36 , 4, 'c', LTS_STATE_o_36 , LTS_STATE_o_1090 , 2, 't', LTS_STATE_o_92 , LTS_STATE_o_1091 , 3, 'i', LTS_STATE_o_36 , LTS_STATE_o_215 , 2, 'h', LTS_STATE_o_36 , LTS_STATE_o_1092 , 4, 'c', LTS_STATE_o_215 , LTS_STATE_o_92 , 1, 'e', LTS_STATE_o_215 , LTS_STATE_o_36 , 4, 'h', LTS_STATE_o_36 , LTS_STATE_o_1093 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_235 , 1, 'e', LTS_STATE_o_235 , LTS_STATE_o_1094 , 1, 'a', LTS_STATE_o_100 , LTS_STATE_o_235 , 2, 'm', LTS_STATE_o_215 , LTS_STATE_o_36 , 2, 'e', LTS_STATE_o_36 , LTS_STATE_o_1095 , 3, 'r', LTS_STATE_o_87 , LTS_STATE_o_1096 , 4, 'j', LTS_STATE_o_212 , LTS_STATE_o_1097 , 3, 's', LTS_STATE_o_40 , LTS_STATE_o_1098 , 3, 'k', LTS_STATE_o_1100 , LTS_STATE_o_1099 , 3, 'p', LTS_STATE_o_1102 , LTS_STATE_o_1101 , 5, 'n', LTS_STATE_o_1103 , LTS_STATE_o_215 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1104 , 6, 'c', LTS_STATE_o_1106 , LTS_STATE_o_1105 , 6, 'n', LTS_STATE_o_36 , LTS_STATE_o_1107 , 5, 'u', LTS_STATE_o_1109 , LTS_STATE_o_1108 , 5, 'f', LTS_STATE_o_60 , LTS_STATE_o_215 , 6, 't', LTS_STATE_o_1111 , LTS_STATE_o_1110 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 'k', LTS_STATE_o_100 , LTS_STATE_o_1112 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_1113 , 6, 'b', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_1114 , 3, 'k', LTS_STATE_o_36 , LTS_STATE_o_1115 , 6, 'l', LTS_STATE_o_100 , LTS_STATE_o_92 , 4, 'g', LTS_STATE_o_100 , LTS_STATE_o_1116 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_1117 , 6, 'c', LTS_STATE_o_1119 , LTS_STATE_o_1118 , 4, 'g', LTS_STATE_o_40 , LTS_STATE_o_1120 , 1, '#', LTS_STATE_o_1122 , LTS_STATE_o_1121 , 1, '#', LTS_STATE_o_36 , LTS_STATE_o_1123 , 6, 't', LTS_STATE_o_1125 , LTS_STATE_o_1124 , 4, 'p', LTS_STATE_o_215 , LTS_STATE_o_1126 , 2, '#', LTS_STATE_o_1127 , LTS_STATE_o_92 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1128 , 1, '#', LTS_STATE_o_34 , LTS_STATE_o_215 , 6, 'r', LTS_STATE_o_34 , LTS_STATE_o_1129 , 3, 'l', LTS_STATE_o_212 , LTS_STATE_o_218 , 6, 'a', LTS_STATE_o_20 , LTS_STATE_o_1130 , 6, 'r', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 'a', LTS_STATE_o_1131 , LTS_STATE_o_36 , 2, 'c', LTS_STATE_o_215 , LTS_STATE_o_20 , 3, 'b', LTS_STATE_o_1133 , LTS_STATE_o_1132 , 2, 'u', LTS_STATE_o_36 , LTS_STATE_o_1134 , 5, 'y', LTS_STATE_o_100 , LTS_STATE_o_1135 , 5, 'y', LTS_STATE_o_1136 , LTS_STATE_o_100 , 3, 'm', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1137 , 1, 'a', LTS_STATE_o_1138 , LTS_STATE_o_100 , 2, 'b', LTS_STATE_o_92 , LTS_STATE_o_1139 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_92 , 2, 'a', LTS_STATE_o_100 , LTS_STATE_o_1140 , 1, '#', LTS_STATE_o_215 , LTS_STATE_o_1141 , 5, 'o', LTS_STATE_o_36 , LTS_STATE_o_92 , 5, 'n', LTS_STATE_o_1143 , LTS_STATE_o_1142 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_1127 , 6, 't', LTS_STATE_o_1144 , LTS_STATE_o_92 , 5, 's', LTS_STATE_o_1146 , LTS_STATE_o_1145 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_235 , 5, 'd', LTS_STATE_o_1015 , LTS_STATE_o_1147 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_1148 , 3, 'c', LTS_STATE_o_1150 , LTS_STATE_o_1149 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_235 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1151 , 3, 'g', LTS_STATE_o_100 , LTS_STATE_o_1152 , 3, 'l', LTS_STATE_o_14 , LTS_STATE_o_1153 , 2, 'o', LTS_STATE_o_20 , LTS_STATE_o_1154 , 3, 'e', LTS_STATE_o_14 , LTS_STATE_o_1155 , 1, 'm', LTS_STATE_o_14 , LTS_STATE_o_1156 , 1, 'r', LTS_STATE_o_40 , LTS_STATE_o_87 , 5, 'k', LTS_STATE_o_40 , LTS_STATE_o_1157 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_1158 , 3, 'c', LTS_STATE_o_1160 , LTS_STATE_o_1159 , 6, 'e', LTS_STATE_o_1162 , LTS_STATE_o_1161 , 4, 'b', LTS_STATE_o_100 , LTS_STATE_o_1163 , 5, 'y', LTS_STATE_o_1165 , LTS_STATE_o_1164 , 5, 'p', LTS_STATE_o_92 , LTS_STATE_o_1166 , 5, 'h', LTS_STATE_o_1167 , LTS_STATE_o_92 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_1168 , 6, 'l', LTS_STATE_o_36 , LTS_STATE_o_1169 , 5, 'v', LTS_STATE_o_92 , LTS_STATE_o_1170 , 3, 'a', LTS_STATE_o_20 , LTS_STATE_o_1171 , 1, 'a', LTS_STATE_o_215 , LTS_STATE_o_1172 , 2, 'a', LTS_STATE_o_92 , LTS_STATE_o_1173 , 2, 'h', LTS_STATE_o_100 , LTS_STATE_o_1174 , 6, '#', LTS_STATE_o_1176 , LTS_STATE_o_1175 , 2, 'f', LTS_STATE_o_40 , LTS_STATE_o_1177 , 2, 'g', LTS_STATE_o_1179 , LTS_STATE_o_1178 , 5, 'c', LTS_STATE_o_1180 , LTS_STATE_o_92 , 1, 'm', LTS_STATE_o_36 , LTS_STATE_o_1181 , 3, 'r', LTS_STATE_o_36 , LTS_STATE_o_1182 , 2, 's', LTS_STATE_o_215 , LTS_STATE_o_36 , 6, 'l', LTS_STATE_o_1184 , LTS_STATE_o_1183 , 4, 'k', LTS_STATE_o_36 , LTS_STATE_o_1185 , 6, 'b', LTS_STATE_o_92 , LTS_STATE_o_1186 , 2, 's', LTS_STATE_o_36 , LTS_STATE_o_1187 , 4, 'z', LTS_STATE_o_36 , LTS_STATE_o_1188 , 1, 't', LTS_STATE_o_92 , LTS_STATE_o_1189 , 5, 't', LTS_STATE_o_215 , LTS_STATE_o_1190 , 3, 'n', LTS_STATE_o_87 , LTS_STATE_o_1191 , 5, 'u', LTS_STATE_o_1193 , LTS_STATE_o_1192 , 5, 'f', LTS_STATE_o_1195 , LTS_STATE_o_1194 , 3, 'y', LTS_STATE_o_215 , LTS_STATE_o_1196 , 6, 'i', LTS_STATE_o_92 , LTS_STATE_o_1197 , 6, 'a', LTS_STATE_o_1199 , LTS_STATE_o_1198 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_1200 , 6, 'm', LTS_STATE_o_215 , LTS_STATE_o_1201 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1202 , 3, 'm', LTS_STATE_o_36 , LTS_STATE_o_92 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_215 , 5, 'v', LTS_STATE_o_92 , LTS_STATE_o_1203 , 6, 'n', LTS_STATE_o_92 , LTS_STATE_o_1204 , 3, 'p', LTS_STATE_o_36 , LTS_STATE_o_1205 , 3, 'p', LTS_STATE_o_100 , LTS_STATE_o_1206 , 6, 'g', LTS_STATE_o_92 , LTS_STATE_o_1030 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_1207 , 6, 'n', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 'd', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_1209 , LTS_STATE_o_1208 , 6, 'n', LTS_STATE_o_92 , LTS_STATE_o_36 , 6, 'l', LTS_STATE_o_100 , LTS_STATE_o_1210 , 2, 'b', LTS_STATE_o_36 , LTS_STATE_o_100 , 3, 'c', LTS_STATE_o_100 , LTS_STATE_o_1211 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_215 , 4, 'l', LTS_STATE_o_215 , LTS_STATE_o_1212 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1213 , 4, 't', LTS_STATE_o_1215 , LTS_STATE_o_1214 , 4, 'l', LTS_STATE_o_36 , LTS_STATE_o_100 , 2, '#', LTS_STATE_o_1216 , LTS_STATE_o_92 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_215 , 2, 'e', LTS_STATE_o_34 , LTS_STATE_o_1217 , 3, 'd', LTS_STATE_o_34 , LTS_STATE_o_215 , 2, 'f', LTS_STATE_o_20 , LTS_STATE_o_1218 , 6, 'n', LTS_STATE_o_20 , LTS_STATE_o_36 , 3, 's', LTS_STATE_o_215 , LTS_STATE_o_1219 , 6, 'r', LTS_STATE_o_20 , LTS_STATE_o_1220 , 2, 'r', LTS_STATE_o_36 , LTS_STATE_o_1221 , 6, '#', LTS_STATE_o_1223 , LTS_STATE_o_1222 , 2, 'i', LTS_STATE_o_215 , LTS_STATE_o_100 , 3, 'm', LTS_STATE_o_100 , LTS_STATE_o_1224 , 3, 'r', LTS_STATE_o_36 , LTS_STATE_o_100 , 2, 's', LTS_STATE_o_92 , LTS_STATE_o_1225 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1226 , 3, 't', LTS_STATE_o_215 , LTS_STATE_o_100 , 5, 'k', LTS_STATE_o_1167 , LTS_STATE_o_1227 , 3, 't', LTS_STATE_o_34 , LTS_STATE_o_92 , 3, 'd', LTS_STATE_o_36 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_235 , LTS_STATE_o_92 , 6, 't', LTS_STATE_o_235 , LTS_STATE_o_92 , 1, '#', LTS_STATE_o_92 , LTS_STATE_o_1228 , 6, 'r', LTS_STATE_o_1230 , LTS_STATE_o_1229 , 2, 'l', LTS_STATE_o_100 , LTS_STATE_o_1231 , 2, 'i', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 'd', LTS_STATE_o_100 , LTS_STATE_o_1232 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'l', LTS_STATE_o_14 , LTS_STATE_o_1233 , 3, 'b', LTS_STATE_o_20 , LTS_STATE_o_1234 , 5, 'y', LTS_STATE_o_1236 , LTS_STATE_o_1235 , 2, 'r', LTS_STATE_o_40 , LTS_STATE_o_1237 , 5, 'l', LTS_STATE_o_40 , LTS_STATE_o_1238 , 2, 'p', LTS_STATE_o_1240 , LTS_STATE_o_1239 , 5, 'o', LTS_STATE_o_100 , LTS_STATE_o_1241 , 2, 'c', LTS_STATE_o_1243 , LTS_STATE_o_1242 , 4, 'c', LTS_STATE_o_92 , LTS_STATE_o_1244 , 1, 'a', LTS_STATE_o_100 , LTS_STATE_o_1245 , 4, 't', LTS_STATE_o_92 , LTS_STATE_o_1246 , 4, 'c', LTS_STATE_o_1248 , LTS_STATE_o_1247 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_1249 , 3, 'e', LTS_STATE_o_1251 , LTS_STATE_o_1250 , 3, 'm', LTS_STATE_o_34 , LTS_STATE_o_92 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_1252 , 2, 'p', LTS_STATE_o_100 , LTS_STATE_o_92 , 6, 't', LTS_STATE_o_1254 , LTS_STATE_o_1253 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_1255 , 2, 'm', LTS_STATE_o_215 , LTS_STATE_o_1256 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_1257 , 1, 'i', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'g', LTS_STATE_o_92 , LTS_STATE_o_1258 , 5, 'h', LTS_STATE_o_1260 , LTS_STATE_o_1259 , 2, 'p', LTS_STATE_o_1262 , LTS_STATE_o_1261 , 1, '#', LTS_STATE_o_1264 , LTS_STATE_o_1263 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_215 , 6, 'i', LTS_STATE_o_92 , LTS_STATE_o_40 , 3, 'p', LTS_STATE_o_215 , LTS_STATE_o_1265 , 1, 'i', LTS_STATE_o_215 , LTS_STATE_o_36 , 6, 's', LTS_STATE_o_1267 , LTS_STATE_o_1266 , 4, 's', LTS_STATE_o_215 , LTS_STATE_o_1268 , 4, 's', LTS_STATE_o_36 , LTS_STATE_o_1269 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_1270 , 1, '0', LTS_STATE_o_36 , LTS_STATE_o_1271 , 4, 'g', LTS_STATE_o_1273 , LTS_STATE_o_1272 , 3, 'n', LTS_STATE_o_87 , LTS_STATE_o_1274 , 5, '#', LTS_STATE_o_215 , LTS_STATE_o_1275 , 2, 'a', LTS_STATE_o_40 , LTS_STATE_o_1276 , 5, 'h', LTS_STATE_o_1278 , LTS_STATE_o_1277 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_1279 , 3, 'h', LTS_STATE_o_92 , LTS_STATE_o_1280 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_1281 , 3, 'p', LTS_STATE_o_1283 , LTS_STATE_o_1282 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_1284 , 3, 'f', LTS_STATE_o_92 , LTS_STATE_o_1285 , 3, 'c', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, '#', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 'n', LTS_STATE_o_1287 , LTS_STATE_o_1286 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_1288 , 5, 'c', LTS_STATE_o_1290 , LTS_STATE_o_1289 , 6, 'm', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'd', LTS_STATE_o_92 , LTS_STATE_o_1291 , 3, 's', LTS_STATE_o_92 , LTS_STATE_o_36 , 6, 's', LTS_STATE_o_1293 , LTS_STATE_o_1292 , 6, 'c', LTS_STATE_o_36 , LTS_STATE_o_1294 , 2, 'p', LTS_STATE_o_100 , LTS_STATE_o_1295 , 3, 'i', LTS_STATE_o_233 , LTS_STATE_o_1296 , 4, 'p', LTS_STATE_o_1298 , LTS_STATE_o_1297 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1299 , 3, 'n', LTS_STATE_o_100 , LTS_STATE_o_1300 , 4, 'h', LTS_STATE_o_36 , LTS_STATE_o_1301 , 6, 'l', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'c', LTS_STATE_o_215 , LTS_STATE_o_1302 , 3, 'h', LTS_STATE_o_34 , LTS_STATE_o_1303 , 6, 'n', LTS_STATE_o_1305 , LTS_STATE_o_1304 , 3, 't', LTS_STATE_o_660 , LTS_STATE_o_1306 , 5, 's', LTS_STATE_o_20 , LTS_STATE_o_215 , 2, 's', LTS_STATE_o_846 , LTS_STATE_o_36 , 2, 'c', LTS_STATE_o_92 , LTS_STATE_o_1307 , 5, 'o', LTS_STATE_o_215 , LTS_STATE_o_92 , 2, 'r', LTS_STATE_o_100 , LTS_STATE_o_1308 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_1309 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_1310 , 5, 'd', LTS_STATE_o_1312 , LTS_STATE_o_1311 , 5, 's', LTS_STATE_o_1313 , LTS_STATE_o_100 , 6, 'p', LTS_STATE_o_100 , LTS_STATE_o_1314 , 5, 't', LTS_STATE_o_92 , LTS_STATE_o_100 , 2, 'd', LTS_STATE_o_100 , LTS_STATE_o_1315 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1316 , 5, 'v', LTS_STATE_o_14 , LTS_STATE_o_518 , 2, 'm', LTS_STATE_o_20 , LTS_STATE_o_1317 , 6, 'h', LTS_STATE_o_14 , LTS_STATE_o_1318 , 1, 'c', LTS_STATE_o_40 , LTS_STATE_o_14 , 1, 'a', LTS_STATE_o_87 , LTS_STATE_o_1319 , 5, 'n', LTS_STATE_o_40 , LTS_STATE_o_1320 , 6, 'c', LTS_STATE_o_1322 , LTS_STATE_o_1321 , 3, 'e', LTS_STATE_o_14 , LTS_STATE_o_1323 , 5, 'b', LTS_STATE_o_1325 , LTS_STATE_o_1324 , 6, 'n', LTS_STATE_o_34 , LTS_STATE_o_1326 , 6, 'a', LTS_STATE_o_34 , LTS_STATE_o_92 , 2, 'h', LTS_STATE_o_92 , LTS_STATE_o_1327 , 4, 't', LTS_STATE_o_1328 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1329 , 3, 'r', LTS_STATE_o_1331 , LTS_STATE_o_1330 , 3, 'd', LTS_STATE_o_100 , LTS_STATE_o_1332 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1333 , 5, 'i', LTS_STATE_o_1335 , LTS_STATE_o_1334 , 5, 'l', LTS_STATE_o_36 , LTS_STATE_o_100 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_1336 , 5, 't', LTS_STATE_o_215 , LTS_STATE_o_1337 , 5, 's', LTS_STATE_o_215 , LTS_STATE_o_1338 , 3, 'h', LTS_STATE_o_1340 , LTS_STATE_o_1339 , 3, 'p', LTS_STATE_o_36 , LTS_STATE_o_1341 , 2, 'i', LTS_STATE_o_92 , LTS_STATE_o_1342 , 6, 'o', LTS_STATE_o_1344 , LTS_STATE_o_1343 , 5, 'o', LTS_STATE_o_215 , LTS_STATE_o_1345 , 2, 'n', LTS_STATE_o_92 , LTS_STATE_o_34 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_1346 , 5, 'c', LTS_STATE_o_36 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_1347 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_1348 , 6, 'o', LTS_STATE_o_215 , LTS_STATE_o_1349 , 1, 'm', LTS_STATE_o_1351 , LTS_STATE_o_1350 , 4, 'l', LTS_STATE_o_100 , LTS_STATE_o_1352 , 2, 'i', LTS_STATE_o_100 , LTS_STATE_o_1353 , 4, 'p', LTS_STATE_o_36 , LTS_STATE_o_1354 , 3, 't', LTS_STATE_o_215 , LTS_STATE_o_1355 , 4, 'b', LTS_STATE_o_36 , LTS_STATE_o_1356 , 4, 'f', LTS_STATE_o_1358 , LTS_STATE_o_1357 , 3, 'd', LTS_STATE_o_40 , LTS_STATE_o_1359 , 1, 'r', LTS_STATE_o_87 , LTS_STATE_o_1360 , 3, 'c', LTS_STATE_o_215 , LTS_STATE_o_36 , 2, 'i', LTS_STATE_o_40 , LTS_STATE_o_1361 , 5, 'r', LTS_STATE_o_1363 , LTS_STATE_o_1362 , 4, 't', LTS_STATE_o_1365 , LTS_STATE_o_1364 , 3, 'd', LTS_STATE_o_92 , LTS_STATE_o_1366 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 'h', LTS_STATE_o_40 , LTS_STATE_o_1367 , 6, 'h', LTS_STATE_o_40 , LTS_STATE_o_1368 , 6, 'u', LTS_STATE_o_92 , LTS_STATE_o_1369 , 5, 't', LTS_STATE_o_92 , LTS_STATE_o_942 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1370 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_1371 , 4, 'v', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'e', LTS_STATE_o_1373 , LTS_STATE_o_1372 , 5, 'f', LTS_STATE_o_1374 , LTS_STATE_o_215 , 6, 'a', LTS_STATE_o_235 , LTS_STATE_o_215 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_1375 , 6, 'l', LTS_STATE_o_1377 , LTS_STATE_o_1376 , 3, 'p', LTS_STATE_o_100 , LTS_STATE_o_215 , 4, 's', LTS_STATE_o_100 , LTS_STATE_o_1378 , 2, 't', LTS_STATE_o_215 , LTS_STATE_o_1379 , 4, 'g', LTS_STATE_o_100 , LTS_STATE_o_1380 , 3, 'h', LTS_STATE_o_1382 , LTS_STATE_o_1381 , 2, 'p', LTS_STATE_o_92 , LTS_STATE_o_215 , 4, 'd', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'd', LTS_STATE_o_100 , LTS_STATE_o_36 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1383 , 4, 'g', LTS_STATE_o_92 , LTS_STATE_o_1384 , 3, 'l', LTS_STATE_o_34 , LTS_STATE_o_215 , 5, 'l', LTS_STATE_o_20 , LTS_STATE_o_1385 , 2, 'c', LTS_STATE_o_20 , LTS_STATE_o_215 , 3, 'm', LTS_STATE_o_215 , LTS_STATE_o_20 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1386 , 2, 'l', LTS_STATE_o_100 , LTS_STATE_o_1387 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_1388 , 6, 's', LTS_STATE_o_1389 , LTS_STATE_o_92 , 3, 's', LTS_STATE_o_40 , LTS_STATE_o_92 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_1390 , 1, 'i', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 't', LTS_STATE_o_92 , LTS_STATE_o_1391 , 2, 'h', LTS_STATE_o_100 , LTS_STATE_o_1392 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_235 , 1, 'r', LTS_STATE_o_20 , LTS_STATE_o_1393 , 1, 'e', LTS_STATE_o_1395 , LTS_STATE_o_1394 , 1, 'h', LTS_STATE_o_14 , LTS_STATE_o_1396 , 3, 's', LTS_STATE_o_40 , LTS_STATE_o_1397 , 5, 'i', LTS_STATE_o_1399 , LTS_STATE_o_1398 , 4, 'g', LTS_STATE_o_92 , LTS_STATE_o_1400 , 5, 'r', LTS_STATE_o_1402 , LTS_STATE_o_1401 , 1, '0', LTS_STATE_o_1404 , LTS_STATE_o_1403 , 1, 'c', LTS_STATE_o_34 , LTS_STATE_o_1405 , 1, 'e', LTS_STATE_o_1407 , LTS_STATE_o_1406 , 6, 'o', LTS_STATE_o_92 , LTS_STATE_o_1408 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_40 , 6, 'o', LTS_STATE_o_235 , LTS_STATE_o_92 , 4, 't', LTS_STATE_o_1410 , LTS_STATE_o_1409 , 5, 'h', LTS_STATE_o_87 , LTS_STATE_o_1411 , 2, 'l', LTS_STATE_o_1199 , LTS_STATE_o_1412 , 4, 'm', LTS_STATE_o_100 , LTS_STATE_o_1413 , 5, 'u', LTS_STATE_o_1415 , LTS_STATE_o_1414 , 6, 's', LTS_STATE_o_1417 , LTS_STATE_o_1416 , 3, 'r', LTS_STATE_o_1419 , LTS_STATE_o_1418 , 6, 'a', LTS_STATE_o_1421 , LTS_STATE_o_1420 , 3, 'p', LTS_STATE_o_1422 , LTS_STATE_o_100 , 5, 'l', LTS_STATE_o_756 , LTS_STATE_o_1423 , 2, 'c', LTS_STATE_o_92 , LTS_STATE_o_1424 , 6, 't', LTS_STATE_o_36 , LTS_STATE_o_1425 , 3, 't', LTS_STATE_o_92 , LTS_STATE_o_1426 , 5, 'o', LTS_STATE_o_1152 , LTS_STATE_o_1427 , 5, 'c', LTS_STATE_o_100 , LTS_STATE_o_1428 , 5, 't', LTS_STATE_o_1430 , LTS_STATE_o_1429 , 5, 't', LTS_STATE_o_543 , LTS_STATE_o_1431 , 2, 'o', LTS_STATE_o_92 , LTS_STATE_o_1432 , 2, 'b', LTS_STATE_o_92 , LTS_STATE_o_40 , 1, '#', LTS_STATE_o_215 , LTS_STATE_o_1433 , 1, 's', LTS_STATE_o_1435 , LTS_STATE_o_1434 , 2, 'o', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_215 , 1, 'i', LTS_STATE_o_100 , LTS_STATE_o_215 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_1436 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1437 , 4, 'p', LTS_STATE_o_1439 , LTS_STATE_o_1438 , 3, 't', LTS_STATE_o_92 , LTS_STATE_o_1440 , 3, 'h', LTS_STATE_o_100 , LTS_STATE_o_87 , 2, 'a', LTS_STATE_o_87 , LTS_STATE_o_1441 , 3, 'h', LTS_STATE_o_87 , LTS_STATE_o_1199 , 1, 'a', LTS_STATE_o_40 , LTS_STATE_o_87 , 4, 'g', LTS_STATE_o_1443 , LTS_STATE_o_1442 , 3, 'r', LTS_STATE_o_235 , LTS_STATE_o_1444 , 6, 'i', LTS_STATE_o_1446 , LTS_STATE_o_1445 , 3, 'r', LTS_STATE_o_40 , LTS_STATE_o_1447 , 6, 'n', LTS_STATE_o_36 , LTS_STATE_o_1448 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1449 , 3, 'c', LTS_STATE_o_1451 , LTS_STATE_o_1450 , 6, 'i', LTS_STATE_o_40 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_1453 , LTS_STATE_o_1452 , 6, 't', LTS_STATE_o_756 , LTS_STATE_o_1454 , 3, 'r', LTS_STATE_o_1456 , LTS_STATE_o_1455 , 4, 'c', LTS_STATE_o_215 , LTS_STATE_o_1457 , 3, 'g', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'v', LTS_STATE_o_92 , LTS_STATE_o_1458 , 3, 'r', LTS_STATE_o_1460 , LTS_STATE_o_1459 , 4, 't', LTS_STATE_o_215 , LTS_STATE_o_1461 , 2, 'c', LTS_STATE_o_215 , LTS_STATE_o_1462 , 6, 'n', LTS_STATE_o_100 , LTS_STATE_o_36 , 6, 'e', LTS_STATE_o_36 , LTS_STATE_o_1463 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_1464 , 4, 'b', LTS_STATE_o_215 , LTS_STATE_o_92 , 4, 'c', LTS_STATE_o_1466 , LTS_STATE_o_1465 , 3, 'h', LTS_STATE_o_92 , LTS_STATE_o_215 , 1, 'r', LTS_STATE_o_20 , LTS_STATE_o_1467 , 2, 'e', LTS_STATE_o_92 , LTS_STATE_o_1468 , 3, 'h', LTS_STATE_o_92 , LTS_STATE_o_1152 , 5, 'd', LTS_STATE_o_100 , LTS_STATE_o_92 , 1, 'a', LTS_STATE_o_92 , LTS_STATE_o_714 , 6, 'r', LTS_STATE_o_92 , LTS_STATE_o_1469 , 6, 'h', LTS_STATE_o_92 , LTS_STATE_o_1470 , 1, 'e', LTS_STATE_o_1471 , LTS_STATE_o_100 , 1, 'i', LTS_STATE_o_20 , LTS_STATE_o_140 , 6, 'o', LTS_STATE_o_40 , LTS_STATE_o_1472 , 5, 'i', LTS_STATE_o_1474 , LTS_STATE_o_1473 , 1, 'n', LTS_STATE_o_14 , LTS_STATE_o_40 , 5, 'i', LTS_STATE_o_40 , LTS_STATE_o_1475 , 5, 'h', LTS_STATE_o_1477 , LTS_STATE_o_1476 , 4, 'g', LTS_STATE_o_1479 , LTS_STATE_o_1478 , 4, 't', LTS_STATE_o_92 , LTS_STATE_o_1480 , 4, 'v', LTS_STATE_o_235 , LTS_STATE_o_1481 , 1, 'p', LTS_STATE_o_215 , LTS_STATE_o_1482 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_1483 , 5, 'i', LTS_STATE_o_36 , LTS_STATE_o_92 , 2, 'a', LTS_STATE_o_40 , LTS_STATE_o_92 , 5, 'b', LTS_STATE_o_100 , LTS_STATE_o_1484 , 6, 'u', LTS_STATE_o_100 , LTS_STATE_o_34 , 2, 'a', LTS_STATE_o_92 , LTS_STATE_o_215 , 4, 'm', LTS_STATE_o_1486 , LTS_STATE_o_1485 , 2, 'c', LTS_STATE_o_40 , LTS_STATE_o_1487 , 4, 'f', LTS_STATE_o_40 , LTS_STATE_o_1488 , 3, 'n', LTS_STATE_o_100 , LTS_STATE_o_1489 , 4, 'd', LTS_STATE_o_100 , LTS_STATE_o_1490 , 5, 'h', LTS_STATE_o_1492 , LTS_STATE_o_1491 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_1493 , 4, 'h', LTS_STATE_o_36 , LTS_STATE_o_1494 , 4, 'm', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1495 , 2, 'p', LTS_STATE_o_1496 , LTS_STATE_o_215 , 6, 'c', LTS_STATE_o_1498 , LTS_STATE_o_1497 , 5, 'l', LTS_STATE_o_1047 , LTS_STATE_o_215 , 2, 'o', LTS_STATE_o_92 , LTS_STATE_o_1499 , 5, 't', LTS_STATE_o_215 , LTS_STATE_o_1500 , 5, 'm', LTS_STATE_o_215 , LTS_STATE_o_1501 , 6, '#', LTS_STATE_o_1502 , LTS_STATE_o_215 , 1, 'o', LTS_STATE_o_92 , LTS_STATE_o_1503 , 6, 'h', LTS_STATE_o_100 , LTS_STATE_o_1504 , 2, 'c', LTS_STATE_o_100 , LTS_STATE_o_1505 , 255, 16, 0,0 , 0,0 , 2, 'n', LTS_STATE_o_215 , LTS_STATE_o_1506 , 5, 'o', LTS_STATE_o_36 , LTS_STATE_o_1507 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_1508 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1509 , 4, 't', LTS_STATE_o_1511 , LTS_STATE_o_1510 , 4, 't', LTS_STATE_o_100 , LTS_STATE_o_92 , 6, 'h', LTS_STATE_o_92 , LTS_STATE_o_1512 , 4, 'c', LTS_STATE_o_92 , LTS_STATE_o_1513 , 1, '#', LTS_STATE_o_1514 , LTS_STATE_o_100 , 1, 'y', LTS_STATE_o_100 , LTS_STATE_o_36 , 2, 's', LTS_STATE_o_1516 , LTS_STATE_o_1515 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1517 , 5, 'y', LTS_STATE_o_1519 , LTS_STATE_o_1518 , 3, 'd', LTS_STATE_o_1521 , LTS_STATE_o_1520 , 3, 'c', LTS_STATE_o_215 , LTS_STATE_o_1522 , 3, 'k', LTS_STATE_o_92 , LTS_STATE_o_1523 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 'm', LTS_STATE_o_1525 , LTS_STATE_o_1524 , 4, 'b', LTS_STATE_o_1527 , LTS_STATE_o_1526 , 3, 'g', LTS_STATE_o_92 , LTS_STATE_o_1528 , 5, 'q', LTS_STATE_o_92 , LTS_STATE_o_1529 , 6, 'a', LTS_STATE_o_40 , LTS_STATE_o_1530 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_1531 , 6, 'i', LTS_STATE_o_40 , LTS_STATE_o_92 , 3, 'p', LTS_STATE_o_1533 , LTS_STATE_o_1532 , 6, 'f', LTS_STATE_o_1535 , LTS_STATE_o_1534 , 4, 'b', LTS_STATE_o_92 , LTS_STATE_o_1536 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_1127 , 3, 's', LTS_STATE_o_215 , LTS_STATE_o_1537 , 6, 't', LTS_STATE_o_36 , LTS_STATE_o_1538 , 4, 'b', LTS_STATE_o_92 , LTS_STATE_o_215 , 4, 'c', LTS_STATE_o_215 , LTS_STATE_o_100 , 4, 'b', LTS_STATE_o_36 , LTS_STATE_o_1539 , 6, 'n', LTS_STATE_o_1541 , LTS_STATE_o_1540 , 1, '#', LTS_STATE_o_1542 , LTS_STATE_o_215 , 6, 'm', LTS_STATE_o_1544 , LTS_STATE_o_1543 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_40 , 6, 'r', LTS_STATE_o_572 , LTS_STATE_o_1545 , 5, 'o', LTS_STATE_o_1547 , LTS_STATE_o_1546 , 3, 'r', LTS_STATE_o_235 , LTS_STATE_o_92 , 6, 'a', LTS_STATE_o_1549 , LTS_STATE_o_1548 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_100 , 1, 'h', LTS_STATE_o_14 , LTS_STATE_o_1550 , 6, '#', LTS_STATE_o_14 , LTS_STATE_o_40 , 3, 'r', LTS_STATE_o_14 , LTS_STATE_o_40 , 5, 'm', LTS_STATE_o_40 , LTS_STATE_o_257 , 5, 'r', LTS_STATE_o_1552 , LTS_STATE_o_1551 , 4, 't', LTS_STATE_o_1554 , LTS_STATE_o_1553 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_1555 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_215 , 4, 'p', LTS_STATE_o_92 , LTS_STATE_o_1556 , 4, 'd', LTS_STATE_o_100 , LTS_STATE_o_1557 , 1, 'e', LTS_STATE_o_215 , LTS_STATE_o_100 , 2, 'e', LTS_STATE_o_92 , LTS_STATE_o_1558 , 2, 'n', LTS_STATE_o_1560 , LTS_STATE_o_1559 , 4, 'k', LTS_STATE_o_215 , LTS_STATE_o_1561 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_1562 , 3, 'c', LTS_STATE_o_1564 , LTS_STATE_o_1563 , 4, 'p', LTS_STATE_o_92 , LTS_STATE_o_1565 , 2, 'r', LTS_STATE_o_100 , LTS_STATE_o_1566 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_215 , 5, 'r', LTS_STATE_o_1568 , LTS_STATE_o_1567 , 4, 't', LTS_STATE_o_1570 , LTS_STATE_o_1569 , 6, 'c', LTS_STATE_o_100 , LTS_STATE_o_1571 , 4, 'x', LTS_STATE_o_92 , LTS_STATE_o_1572 , 2, 's', LTS_STATE_o_36 , LTS_STATE_o_1573 , 4, 'v', LTS_STATE_o_100 , LTS_STATE_o_36 , 1, '0', LTS_STATE_o_1575 , LTS_STATE_o_1574 , 3, 't', LTS_STATE_o_215 , LTS_STATE_o_92 , 2, 'a', LTS_STATE_o_36 , LTS_STATE_o_100 , 3, 'p', LTS_STATE_o_1576 , LTS_STATE_o_215 , 1, 'e', LTS_STATE_o_36 , LTS_STATE_o_1577 , 3, 'f', LTS_STATE_o_215 , LTS_STATE_o_1578 , 2, 'b', LTS_STATE_o_100 , LTS_STATE_o_1579 , 3, 'r', LTS_STATE_o_1581 , LTS_STATE_o_1580 , 5, 't', LTS_STATE_o_40 , LTS_STATE_o_92 , 3, 'm', LTS_STATE_o_215 , LTS_STATE_o_1582 , 5, 'y', LTS_STATE_o_36 , LTS_STATE_o_40 , 6, '#', LTS_STATE_o_1583 , LTS_STATE_o_911 , 6, 'n', LTS_STATE_o_100 , LTS_STATE_o_756 , 6, 'b', LTS_STATE_o_100 , LTS_STATE_o_1584 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_92 , 4, 'l', LTS_STATE_o_92 , LTS_STATE_o_36 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1585 , 4, 'l', LTS_STATE_o_100 , LTS_STATE_o_36 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_1586 , 3, 'h', LTS_STATE_o_92 , LTS_STATE_o_1587 , 2, 'r', LTS_STATE_o_235 , LTS_STATE_o_92 , 5, 'l', LTS_STATE_o_1589 , LTS_STATE_o_1588 , 4, 'p', LTS_STATE_o_92 , LTS_STATE_o_1590 , 5, 'l', LTS_STATE_o_1591 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_40 , LTS_STATE_o_1592 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1593 , 4, 'c', LTS_STATE_o_1595 , LTS_STATE_o_1594 , 3, 'n', LTS_STATE_o_34 , LTS_STATE_o_1596 , 6, 'e', LTS_STATE_o_34 , LTS_STATE_o_40 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1597 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_36 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_40 , 6, 'o', LTS_STATE_o_1599 , LTS_STATE_o_1598 , 5, 't', LTS_STATE_o_1601 , LTS_STATE_o_1600 , 3, 'b', LTS_STATE_o_40 , LTS_STATE_o_1602 , 3, 'k', LTS_STATE_o_100 , LTS_STATE_o_1603 , 4, 'p', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'l', LTS_STATE_o_1605 , LTS_STATE_o_1604 , 3, 'c', LTS_STATE_o_215 , LTS_STATE_o_92 , 4, 's', LTS_STATE_o_92 , LTS_STATE_o_36 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_1384 , 4, 'd', LTS_STATE_o_1607 , LTS_STATE_o_1606 , 2, 'r', LTS_STATE_o_36 , LTS_STATE_o_1608 , 3, 'l', LTS_STATE_o_215 , LTS_STATE_o_1609 , 2, 'r', LTS_STATE_o_215 , LTS_STATE_o_1047 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_1610 , 3, 'm', LTS_STATE_o_100 , LTS_STATE_o_1611 , 4, 'l', LTS_STATE_o_100 , LTS_STATE_o_215 , 3, 'r', LTS_STATE_o_20 , LTS_STATE_o_1612 , 6, 'a', LTS_STATE_o_1614 , LTS_STATE_o_1613 , 6, 'm', LTS_STATE_o_92 , LTS_STATE_o_286 , 6, 'o', LTS_STATE_o_1616 , LTS_STATE_o_1615 , 5, 't', LTS_STATE_o_100 , LTS_STATE_o_235 , 2, 'a', LTS_STATE_o_14 , LTS_STATE_o_1617 , 4, 'h', LTS_STATE_o_1619 , LTS_STATE_o_1618 , 6, 'a', LTS_STATE_o_1621 , LTS_STATE_o_1620 , 1, '0', LTS_STATE_o_92 , LTS_STATE_o_1622 , 6, 'e', LTS_STATE_o_1624 , LTS_STATE_o_1623 , 4, 't', LTS_STATE_o_1626 , LTS_STATE_o_1625 , 1, 'e', LTS_STATE_o_92 , LTS_STATE_o_1627 , 5, 'o', LTS_STATE_o_100 , LTS_STATE_o_1628 , 5, 'i', LTS_STATE_o_1630 , LTS_STATE_o_1629 , 6, 'a', LTS_STATE_o_92 , LTS_STATE_o_100 , 1, 'o', LTS_STATE_o_100 , LTS_STATE_o_1631 , 4, 'h', LTS_STATE_o_1633 , LTS_STATE_o_1632 , 5, 'b', LTS_STATE_o_100 , LTS_STATE_o_92 , 5, 's', LTS_STATE_o_1634 , LTS_STATE_o_100 , 1, 'a', LTS_STATE_o_92 , LTS_STATE_o_1635 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'b', LTS_STATE_o_100 , LTS_STATE_o_1636 , 4, 'h', LTS_STATE_o_215 , LTS_STATE_o_1637 , 4, 't', LTS_STATE_o_36 , LTS_STATE_o_1638 , 3, 'i', LTS_STATE_o_36 , LTS_STATE_o_1639 , 3, 'r', LTS_STATE_o_1525 , LTS_STATE_o_1640 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1641 , 3, 'i', LTS_STATE_o_100 , LTS_STATE_o_1642 , 4, 'd', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'd', LTS_STATE_o_92 , LTS_STATE_o_1643 , 5, 'l', LTS_STATE_o_92 , LTS_STATE_o_1644 , 5, 'i', LTS_STATE_o_100 , LTS_STATE_o_215 , 1, 'c', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'h', LTS_STATE_o_215 , LTS_STATE_o_1645 , 1, 'e', LTS_STATE_o_92 , LTS_STATE_o_1646 , 3, 'g', LTS_STATE_o_36 , LTS_STATE_o_1647 , 2, 'e', LTS_STATE_o_36 , LTS_STATE_o_1648 , 3, 'p', LTS_STATE_o_215 , LTS_STATE_o_40 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_92 , 4, 's', LTS_STATE_o_100 , LTS_STATE_o_1649 , 6, 'r', LTS_STATE_o_36 , LTS_STATE_o_1650 , 2, 'a', LTS_STATE_o_100 , LTS_STATE_o_1651 , 4, 't', LTS_STATE_o_92 , LTS_STATE_o_100 , 5, 'c', LTS_STATE_o_1653 , LTS_STATE_o_1652 , 4, 'b', LTS_STATE_o_1591 , LTS_STATE_o_92 , 4, 'b', LTS_STATE_o_1654 , LTS_STATE_o_215 , 6, 'e', LTS_STATE_o_215 , LTS_STATE_o_92 , 5, 'g', LTS_STATE_o_40 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_92 , LTS_STATE_o_1655 , 3, 's', LTS_STATE_o_92 , LTS_STATE_o_1656 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1657 , 6, 'e', LTS_STATE_o_1658 , LTS_STATE_o_92 , 4, 'g', LTS_STATE_o_215 , LTS_STATE_o_1659 , 5, 'u', LTS_STATE_o_215 , LTS_STATE_o_1660 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_1661 , 5, 'm', LTS_STATE_o_1662 , LTS_STATE_o_92 , 6, 'u', LTS_STATE_o_235 , LTS_STATE_o_1663 , 3, 'g', LTS_STATE_o_92 , LTS_STATE_o_1664 , 6, 'o', LTS_STATE_o_100 , LTS_STATE_o_1665 , 3, 'k', LTS_STATE_o_1667 , LTS_STATE_o_1666 , 3, 'm', LTS_STATE_o_215 , LTS_STATE_o_92 , 4, 'k', LTS_STATE_o_100 , LTS_STATE_o_1668 , 6, 'r', LTS_STATE_o_36 , LTS_STATE_o_100 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1669 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_711 , 2, 's', LTS_STATE_o_215 , LTS_STATE_o_100 , 2, '#', LTS_STATE_o_1671 , LTS_STATE_o_1670 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_1672 , 5, 'm', LTS_STATE_o_100 , LTS_STATE_o_1673 , 3, 'd', LTS_STATE_o_92 , LTS_STATE_o_100 , 5, 'f', LTS_STATE_o_100 , LTS_STATE_o_1674 , 5, 'f', LTS_STATE_o_100 , LTS_STATE_o_1675 , 6, 's', LTS_STATE_o_871 , LTS_STATE_o_1676 , 5, 'o', LTS_STATE_o_1678 , LTS_STATE_o_1677 , 5, 'o', LTS_STATE_o_100 , LTS_STATE_o_215 , 1, 'h', LTS_STATE_o_1429 , LTS_STATE_o_1679 , 2, 'c', LTS_STATE_o_36 , LTS_STATE_o_1680 , 4, 'c', LTS_STATE_o_1682 , LTS_STATE_o_1681 , 6, 'a', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'y', LTS_STATE_o_92 , LTS_STATE_o_1683 , 6, 't', LTS_STATE_o_1685 , LTS_STATE_o_1684 , 3, 'm', LTS_STATE_o_215 , LTS_STATE_o_1686 , 4, 'b', LTS_STATE_o_1687 , LTS_STATE_o_100 , 4, 't', LTS_STATE_o_92 , LTS_STATE_o_1688 , 3, 'r', LTS_STATE_o_92 , LTS_STATE_o_1102 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_1689 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1174 , 2, 'a', LTS_STATE_o_235 , LTS_STATE_o_1690 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_36 , 3, 'i', LTS_STATE_o_100 , LTS_STATE_o_1691 , 2, 's', LTS_STATE_o_100 , LTS_STATE_o_1692 , 2, 's', LTS_STATE_o_92 , LTS_STATE_o_1693 , 2, 'p', LTS_STATE_o_1695 , LTS_STATE_o_1694 , 2, 'b', LTS_STATE_o_92 , LTS_STATE_o_1696 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1697 , 2, 'c', LTS_STATE_o_215 , LTS_STATE_o_92 , 4, 'q', LTS_STATE_o_100 , LTS_STATE_o_36 , 3, 'r', LTS_STATE_o_1699 , LTS_STATE_o_1698 , 5, 'l', LTS_STATE_o_1701 , LTS_STATE_o_1700 , 5, 'i', LTS_STATE_o_1703 , LTS_STATE_o_1702 , 2, 'e', LTS_STATE_o_215 , LTS_STATE_o_355 , 2, 'u', LTS_STATE_o_92 , LTS_STATE_o_1704 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_1705 , 2, 'u', LTS_STATE_o_36 , LTS_STATE_o_1706 , 1, 'l', LTS_STATE_o_215 , LTS_STATE_o_1707 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_36 , 1, 'b', LTS_STATE_o_235 , LTS_STATE_o_1708 , 4, 'z', LTS_STATE_o_92 , LTS_STATE_o_1709 , 4, 'c', LTS_STATE_o_1710 , LTS_STATE_o_92 , 6, '#', LTS_STATE_o_215 , LTS_STATE_o_100 , 6, 'a', LTS_STATE_o_1011 , LTS_STATE_o_100 , 4, 'p', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 'a', LTS_STATE_o_215 , LTS_STATE_o_92 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_34 , 4, 'c', LTS_STATE_o_36 , LTS_STATE_o_1711 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_1712 , 3, 'm', LTS_STATE_o_92 , LTS_STATE_o_66 , 6, 'o', LTS_STATE_o_40 , LTS_STATE_o_235 , 6, 'e', LTS_STATE_o_40 , LTS_STATE_o_1713 , 3, 'm', LTS_STATE_o_40 , LTS_STATE_o_1453 , 3, 'c', LTS_STATE_o_215 , LTS_STATE_o_1714 , 4, 'd', LTS_STATE_o_1716 , LTS_STATE_o_1715 , 6, 'n', LTS_STATE_o_100 , LTS_STATE_o_215 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_1717 , 1, 'o', LTS_STATE_o_100 , LTS_STATE_o_1718 , 6, 'a', LTS_STATE_o_92 , LTS_STATE_o_1719 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_215 , 5, 'e', LTS_STATE_o_215 , LTS_STATE_o_36 , 3, 's', LTS_STATE_o_100 , LTS_STATE_o_1720 , 6, 'i', LTS_STATE_o_100 , LTS_STATE_o_1721 , 5, 's', LTS_STATE_o_100 , LTS_STATE_o_1722 , 3, 'i', LTS_STATE_o_40 , LTS_STATE_o_1723 , 5, 'y', LTS_STATE_o_1725 , LTS_STATE_o_1724 , 4, 'p', LTS_STATE_o_1727 , LTS_STATE_o_1726 , 1, 'a', LTS_STATE_o_100 , LTS_STATE_o_1728 , 2, 'l', LTS_STATE_o_92 , LTS_STATE_o_1729 , 1, 'p', LTS_STATE_o_36 , LTS_STATE_o_1730 , 1, 'u', LTS_STATE_o_36 , LTS_STATE_o_1731 , 2, 'd', LTS_STATE_o_34 , LTS_STATE_o_1732 , 6, 'e', LTS_STATE_o_1734 , LTS_STATE_o_1733 , 4, 'v', LTS_STATE_o_100 , LTS_STATE_o_1735 , 3, 'v', LTS_STATE_o_215 , LTS_STATE_o_100 , 1, '0', LTS_STATE_o_100 , LTS_STATE_o_215 , 6, 't', LTS_STATE_o_92 , LTS_STATE_o_215 , 2, 'o', LTS_STATE_o_100 , LTS_STATE_o_1736 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1737 , 3, 'g', LTS_STATE_o_100 , LTS_STATE_o_92 , 2, 'i', LTS_STATE_o_235 , LTS_STATE_o_92 , 1, 's', LTS_STATE_o_92 , LTS_STATE_o_1738 , 3, 'i', LTS_STATE_o_215 , LTS_STATE_o_1739 , 5, 'l', LTS_STATE_o_1740 , LTS_STATE_o_92 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_1741 , 2, 'p', LTS_STATE_o_92 , LTS_STATE_o_1742 , 2, 'a', LTS_STATE_o_92 , LTS_STATE_o_1107 , 6, 'c', LTS_STATE_o_92 , LTS_STATE_o_1743 , 6, 'k', LTS_STATE_o_215 , LTS_STATE_o_1744 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_1745 , 5, 'y', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'v', LTS_STATE_o_36 , LTS_STATE_o_92 , 1, 'r', LTS_STATE_o_92 , LTS_STATE_o_1351 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1746 , 2, 't', LTS_STATE_o_100 , LTS_STATE_o_215 , 4, 'h', LTS_STATE_o_100 , LTS_STATE_o_1747 , 1, 'c', LTS_STATE_o_92 , LTS_STATE_o_1748 , 6, 'o', LTS_STATE_o_92 , LTS_STATE_o_1749 , 6, 'i', LTS_STATE_o_215 , LTS_STATE_o_1750 , 4, 'q', LTS_STATE_o_36 , LTS_STATE_o_215 , 5, 'c', LTS_STATE_o_36 , LTS_STATE_o_1751 , 6, 'l', LTS_STATE_o_40 , LTS_STATE_o_92 , 4, 'b', LTS_STATE_o_215 , LTS_STATE_o_1752 , 4, 'p', LTS_STATE_o_215 , LTS_STATE_o_1753 , 6, 'n', LTS_STATE_o_36 , LTS_STATE_o_100 , 4, 'l', LTS_STATE_o_1755 , LTS_STATE_o_1754 , 2, 's', LTS_STATE_o_100 , LTS_STATE_o_1756 , 6, 's', LTS_STATE_o_92 , LTS_STATE_o_215 , 5, 'h', LTS_STATE_o_100 , LTS_STATE_o_1757 , 5, 'c', LTS_STATE_o_100 , LTS_STATE_o_1758 , 5, 't', LTS_STATE_o_100 , LTS_STATE_o_92 , 1, 'd', LTS_STATE_o_40 , LTS_STATE_o_1759 , 5, 'l', LTS_STATE_o_1761 , LTS_STATE_o_1760 , 4, 'd', LTS_STATE_o_36 , LTS_STATE_o_1762 , 1, '0', LTS_STATE_o_1764 , LTS_STATE_o_1763 , 6, 'u', LTS_STATE_o_92 , LTS_STATE_o_1765 , 6, 'o', LTS_STATE_o_1767 , LTS_STATE_o_1766 , 1, 'o', LTS_STATE_o_92 , LTS_STATE_o_1768 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1769 , 3, 'r', LTS_STATE_o_1770 , LTS_STATE_o_643 , 1, '0', LTS_STATE_o_34 , LTS_STATE_o_100 , 4, 'v', LTS_STATE_o_36 , LTS_STATE_o_1771 , 1, 't', LTS_STATE_o_92 , LTS_STATE_o_1772 , 4, 'c', LTS_STATE_o_92 , LTS_STATE_o_1773 , 2, 'p', LTS_STATE_o_100 , LTS_STATE_o_1774 , 1, 'e', LTS_STATE_o_100 , LTS_STATE_o_92 , 1, 'n', LTS_STATE_o_92 , LTS_STATE_o_1775 , 5, 'y', LTS_STATE_o_40 , LTS_STATE_o_1776 , 4, 'c', LTS_STATE_o_36 , LTS_STATE_o_92 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_1777 , 6, 'e', LTS_STATE_o_92 , LTS_STATE_o_1778 , 2, 'p', LTS_STATE_o_1779 , LTS_STATE_o_215 , 5, 'p', LTS_STATE_o_215 , LTS_STATE_o_1780 , 1, 'm', LTS_STATE_o_92 , LTS_STATE_o_1781 , 1, 'e', LTS_STATE_o_100 , LTS_STATE_o_1782 , 2, 's', LTS_STATE_o_100 , LTS_STATE_o_1783 , 3, 'i', LTS_STATE_o_100 , LTS_STATE_o_1784 , 5, 'z', LTS_STATE_o_1591 , LTS_STATE_o_92 , 6, 'a', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 'm', LTS_STATE_o_1786 , LTS_STATE_o_1785 , 4, 'k', LTS_STATE_o_1788 , LTS_STATE_o_1787 , 4, 'c', LTS_STATE_o_215 , LTS_STATE_o_1789 , 6, 'n', LTS_STATE_o_215 , LTS_STATE_o_1790 , 6, 'n', LTS_STATE_o_36 , LTS_STATE_o_1791 , 4, 't', LTS_STATE_o_1379 , LTS_STATE_o_1792 , 2, 'r', LTS_STATE_o_100 , LTS_STATE_o_1793 , 6, 'l', LTS_STATE_o_92 , LTS_STATE_o_100 , 1, 'o', LTS_STATE_o_1795 , LTS_STATE_o_1794 , 4, 'b', LTS_STATE_o_1797 , LTS_STATE_o_1796 , 3, 'r', LTS_STATE_o_1799 , LTS_STATE_o_1798 , 4, 't', LTS_STATE_o_100 , LTS_STATE_o_1800 , 1, 'o', LTS_STATE_o_92 , LTS_STATE_o_1801 , 4, 'd', LTS_STATE_o_1803 , LTS_STATE_o_1802 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_1804 , 1, '0', LTS_STATE_o_92 , LTS_STATE_o_1805 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_1806 , 3, 'n', LTS_STATE_o_1808 , LTS_STATE_o_1807 , 2, 's', LTS_STATE_o_92 , LTS_STATE_o_100 , 6, 'e', LTS_STATE_o_1809 , LTS_STATE_o_215 , 3, 'm', LTS_STATE_o_1811 , LTS_STATE_o_1810 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_1812 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_36 , 3, 'd', LTS_STATE_o_100 , LTS_STATE_o_36 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_1813 , 4, 'm', LTS_STATE_o_1329 , LTS_STATE_o_1814 , 4, 'g', LTS_STATE_o_215 , LTS_STATE_o_100 , 2, 'b', LTS_STATE_o_92 , LTS_STATE_o_1815 , 4, 'f', LTS_STATE_o_92 , LTS_STATE_o_1816 , 2, 'o', LTS_STATE_o_100 , LTS_STATE_o_1817 , 3, 'c', LTS_STATE_o_100 , LTS_STATE_o_1818 , 2, 'i', LTS_STATE_o_36 , LTS_STATE_o_1819 , 3, 'c', LTS_STATE_o_100 , LTS_STATE_o_1820 , 2, 'd', LTS_STATE_o_92 , LTS_STATE_o_1821 , 6, 'i', LTS_STATE_o_1822 , LTS_STATE_o_92 , 5, 't', LTS_STATE_o_92 , LTS_STATE_o_1591 , 6, 's', LTS_STATE_o_215 , LTS_STATE_o_1823 , 3, 's', LTS_STATE_o_92 , LTS_STATE_o_215 , 3, 's', LTS_STATE_o_36 , LTS_STATE_o_1824 , 6, 'b', LTS_STATE_o_215 , LTS_STATE_o_1825 , 6, 'k', LTS_STATE_o_215 , LTS_STATE_o_92 , 1, 'i', LTS_STATE_o_100 , LTS_STATE_o_1826 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_92 , 5, 'n', LTS_STATE_o_1828 , LTS_STATE_o_1827 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_14 , 5, 'u', LTS_STATE_o_1830 , LTS_STATE_o_1829 , 6, 'e', LTS_STATE_o_100 , LTS_STATE_o_1831 , 6, 'e', LTS_STATE_o_1833 , LTS_STATE_o_1832 , 4, 'p', LTS_STATE_o_100 , LTS_STATE_o_36 , 4, 'g', LTS_STATE_o_100 , LTS_STATE_o_1834 , 1, 'r', LTS_STATE_o_100 , LTS_STATE_o_1835 , 6, 'n', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_92 , 2, 'h', LTS_STATE_o_100 , LTS_STATE_o_1836 , 1, 'e', LTS_STATE_o_36 , LTS_STATE_o_100 , 1, 'u', LTS_STATE_o_36 , LTS_STATE_o_100 , 1, 'a', LTS_STATE_o_92 , LTS_STATE_o_1837 , 2, 'a', LTS_STATE_o_92 , LTS_STATE_o_100 , 1, 'e', LTS_STATE_o_100 , LTS_STATE_o_36 , 4, 'k', LTS_STATE_o_215 , LTS_STATE_o_1838 , 2, 'o', LTS_STATE_o_36 , LTS_STATE_o_215 , 1, '0', LTS_STATE_o_215 , LTS_STATE_o_36 , 2, 'y', LTS_STATE_o_92 , LTS_STATE_o_1839 , 5, 'l', LTS_STATE_o_1102 , LTS_STATE_o_92 , 4, 'c', LTS_STATE_o_92 , LTS_STATE_o_215 , 6, 'n', LTS_STATE_o_92 , LTS_STATE_o_1840 , 6, 's', LTS_STATE_o_1842 , LTS_STATE_o_1841 , 1, 'o', LTS_STATE_o_100 , LTS_STATE_o_1843 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_1844 , 1, 'c', LTS_STATE_o_1846 , LTS_STATE_o_1845 , 3, 's', LTS_STATE_o_92 , LTS_STATE_o_1847 , 5, 'h', LTS_STATE_o_215 , LTS_STATE_o_92 , 6, 'l', LTS_STATE_o_658 , LTS_STATE_o_1848 , 3, 't', LTS_STATE_o_100 , LTS_STATE_o_1849 , 3, 'm', LTS_STATE_o_36 , LTS_STATE_o_1850 , 4, 'c', LTS_STATE_o_36 , LTS_STATE_o_1851 , 6, '#', LTS_STATE_o_40 , LTS_STATE_o_1852 , 2, 't', LTS_STATE_o_14 , LTS_STATE_o_1853 , 1, '0', LTS_STATE_o_1855 , LTS_STATE_o_1854 , 4, 'g', LTS_STATE_o_1857 , LTS_STATE_o_1856 , 5, 's', LTS_STATE_o_1858 , LTS_STATE_o_92 , 1, '0', LTS_STATE_o_584 , LTS_STATE_o_1859 , 4, 'g', LTS_STATE_o_215 , LTS_STATE_o_1860 , 4, 'c', LTS_STATE_o_100 , LTS_STATE_o_36 , 1, 'l', LTS_STATE_o_215 , LTS_STATE_o_1861 , 6, 'l', LTS_STATE_o_1737 , LTS_STATE_o_100 , 3, 'l', LTS_STATE_o_100 , LTS_STATE_o_1862 , 2, 'e', LTS_STATE_o_215 , LTS_STATE_o_1863 , 1, 'e', LTS_STATE_o_92 , LTS_STATE_o_1199 , 4, 'v', LTS_STATE_o_100 , LTS_STATE_o_92 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_1864 , 2, 'm', LTS_STATE_o_100 , LTS_STATE_o_1865 , 2, 's', LTS_STATE_o_92 , LTS_STATE_o_1384 , 6, 'a', LTS_STATE_o_40 , LTS_STATE_o_1866 , 6, 'c', LTS_STATE_o_36 , LTS_STATE_o_1867 , 2, 't', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'b', LTS_STATE_o_235 , LTS_STATE_o_1868 , 6, 'r', LTS_STATE_o_215 , LTS_STATE_o_714 , 3, 'j', LTS_STATE_o_36 , LTS_STATE_o_215 , 6, 'm', LTS_STATE_o_36 , LTS_STATE_o_215 , 2, 'i', LTS_STATE_o_100 , LTS_STATE_o_233 , 2, 'r', LTS_STATE_o_14 , LTS_STATE_o_1869 , 1, 'n', LTS_STATE_o_40 , LTS_STATE_o_1870 , 2, 'e', LTS_STATE_o_1872 , LTS_STATE_o_1871 , 6, 'r', LTS_STATE_o_100 , LTS_STATE_o_1873 , 1, '0', LTS_STATE_o_36 , LTS_STATE_o_1874 , 3, 'l', LTS_STATE_o_40 , LTS_STATE_o_92 , 6, 't', LTS_STATE_o_100 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_215 , LTS_STATE_o_100 , 3, 'n', LTS_STATE_o_215 , LTS_STATE_o_100 , 4, 'c', LTS_STATE_o_36 , LTS_STATE_o_1875 , 3, 'm', LTS_STATE_o_1877 , LTS_STATE_o_1876 , 1, 'i', LTS_STATE_o_36 , LTS_STATE_o_1878 , 5, 'o', LTS_STATE_o_100 , LTS_STATE_o_1879 , 2, 'a', LTS_STATE_o_1881 , LTS_STATE_o_1880 , 2, 'o', LTS_STATE_o_92 , LTS_STATE_o_1882 , 3, 'r', LTS_STATE_o_1883 , LTS_STATE_o_36 , 2, 'g', LTS_STATE_o_100 , LTS_STATE_o_1884 , 2, 'b', LTS_STATE_o_40 , LTS_STATE_o_1885 , 2, 'n', LTS_STATE_o_40 , LTS_STATE_o_1886 , 6, 'o', LTS_STATE_o_1461 , LTS_STATE_o_1887 , 1, 'r', LTS_STATE_o_100 , LTS_STATE_o_92 , 5, 'c', LTS_STATE_o_1623 , LTS_STATE_o_92 , 3, 'p', LTS_STATE_o_92 , LTS_STATE_o_1888 , 6, 's', LTS_STATE_o_36 , LTS_STATE_o_1889 , 3, 't', LTS_STATE_o_1891 , LTS_STATE_o_1890 , 4, 'c', LTS_STATE_o_100 , LTS_STATE_o_92 , 6, 'o', LTS_STATE_o_1893 , LTS_STATE_o_1892 , 6, 'z', LTS_STATE_o_100 , LTS_STATE_o_1894 , 2, 'e', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 'b', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 'c', LTS_STATE_o_92 , LTS_STATE_o_215 , 2, 't', LTS_STATE_o_36 , LTS_STATE_o_1895 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1896 , 2, 't', LTS_STATE_o_40 , LTS_STATE_o_1897 , 1, 'l', LTS_STATE_o_40 , LTS_STATE_o_1898 , 4, 'f', LTS_STATE_o_40 , LTS_STATE_o_1899 , 4, 'c', LTS_STATE_o_1858 , LTS_STATE_o_1138 , 6, 'r', LTS_STATE_o_100 , LTS_STATE_o_1900 , 4, 'g', LTS_STATE_o_100 , LTS_STATE_o_1583 , 4, 'c', LTS_STATE_o_100 , LTS_STATE_o_1901 , 2, 't', LTS_STATE_o_100 , LTS_STATE_o_1902 , 4, 'b', LTS_STATE_o_100 , LTS_STATE_o_215 , 1, 'c', LTS_STATE_o_100 , LTS_STATE_o_1903 , 6, 'n', LTS_STATE_o_1904 , LTS_STATE_o_36 , 2, 'h', LTS_STATE_o_100 , LTS_STATE_o_1905 , 6, 'n', LTS_STATE_o_40 , LTS_STATE_o_1906 , 1, 'i', LTS_STATE_o_14 , LTS_STATE_o_1907 , 6, 's', LTS_STATE_o_92 , LTS_STATE_o_1908 , 1, 'm', LTS_STATE_o_100 , LTS_STATE_o_1909 , 1, 'm', LTS_STATE_o_92 , LTS_STATE_o_100 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_1910 , 3, 'v', LTS_STATE_o_92 , LTS_STATE_o_1911 , 2, 'c', LTS_STATE_o_36 , LTS_STATE_o_100 , 2, 'r', LTS_STATE_o_100 , LTS_STATE_o_1912 , 1, 'm', LTS_STATE_o_40 , LTS_STATE_o_14 , 2, 'y', LTS_STATE_o_14 , LTS_STATE_o_1913 , 1, 'a', LTS_STATE_o_1915 , LTS_STATE_o_1914 , 2, 'e', LTS_STATE_o_100 , LTS_STATE_o_1916 , 1, 'e', LTS_STATE_o_100 , LTS_STATE_o_1917 , 6, 'n', LTS_STATE_o_1919 , LTS_STATE_o_1918 , 4, 'd', LTS_STATE_o_92 , LTS_STATE_o_1920 , 1, 'a', LTS_STATE_o_14 , LTS_STATE_o_1921 , 3, 'n', LTS_STATE_o_92 , LTS_STATE_o_1922 , 2, 'l', LTS_STATE_o_92 , LTS_STATE_o_1923 , 4, 'b', LTS_STATE_o_36 , LTS_STATE_o_1924 , 1, '0', LTS_STATE_o_36 , LTS_STATE_o_1925 , 2, 'n', LTS_STATE_o_100 , LTS_STATE_o_1926 , 3, 'r', LTS_STATE_o_215 , LTS_STATE_o_1927 , 2, 'l', LTS_STATE_o_100 , LTS_STATE_o_1928 , 3, 'h', LTS_STATE_o_40 , LTS_STATE_o_14 , 2, 'o', LTS_STATE_o_1929 , LTS_STATE_o_92 , 6, 'i', LTS_STATE_o_215 , LTS_STATE_o_92 , 4, 'd', LTS_STATE_o_1138 , LTS_STATE_o_1930 , 6, 'n', LTS_STATE_o_100 , LTS_STATE_o_1931 , 2, 'p', LTS_STATE_o_36 , LTS_STATE_o_215 , 3, 'i', LTS_STATE_o_100 , LTS_STATE_o_1932 , 1, 'p', LTS_STATE_o_100 , LTS_STATE_o_1933 , 5, 'n', LTS_STATE_o_215 , LTS_STATE_o_92 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1934 , 2, 'h', LTS_STATE_o_36 , LTS_STATE_o_100 , 1, '#', LTS_STATE_o_100 , LTS_STATE_o_36 , 3, 'r', LTS_STATE_o_100 , LTS_STATE_o_1935 , 3, 't', LTS_STATE_o_36 , LTS_STATE_o_100 , 1, 'g', LTS_STATE_o_100 , LTS_STATE_o_1936 , 3, 'l', LTS_STATE_o_92 , LTS_STATE_o_1937 , 3, 'n', LTS_STATE_o_235 , LTS_STATE_o_100 , /** letter p **/ 4, 'p', LTS_STATE_p_2 , LTS_STATE_p_1 , 4, 'h', LTS_STATE_p_4 , LTS_STATE_p_3 , 255, 0, 0,0 , 0,0 , 4, 'f', LTS_STATE_p_7 , LTS_STATE_p_6 , 2, '#', LTS_STATE_p_9 , LTS_STATE_p_8 , 4, 's', LTS_STATE_p_11 , LTS_STATE_p_10 , 2, '0', LTS_STATE_p_2 , LTS_STATE_p_12 , 2, 'h', LTS_STATE_p_14 , LTS_STATE_p_13 , 3, 'u', LTS_STATE_p_12 , LTS_STATE_p_13 , 3, 'p', LTS_STATE_p_12 , LTS_STATE_p_15 , 2, '0', LTS_STATE_p_2 , LTS_STATE_p_16 , 255, 56, 0,0 , 0,0 , 255, 37, 0,0 , 0,0 , 3, 'e', LTS_STATE_p_12 , LTS_STATE_p_13 , 4, 't', LTS_STATE_p_7 , LTS_STATE_p_17 , 2, 'o', LTS_STATE_p_18 , LTS_STATE_p_12 , 4, 'b', LTS_STATE_p_20 , LTS_STATE_p_19 , 3, 'r', LTS_STATE_p_2 , LTS_STATE_p_12 , 4, 'n', LTS_STATE_p_7 , LTS_STATE_p_12 , 2, 'a', LTS_STATE_p_2 , LTS_STATE_p_12 , /** letter q **/ 255, 22, 0,0 , 0,0 , /** letter r **/ 3, 'e', LTS_STATE_r_2 , LTS_STATE_r_1 , 4, 'r', LTS_STATE_r_4 , LTS_STATE_r_3 , 1, '#', LTS_STATE_r_6 , LTS_STATE_r_5 , 1, '0', LTS_STATE_r_8 , LTS_STATE_r_7 , 2, 'c', LTS_STATE_r_10 , LTS_STATE_r_9 , 4, '#', LTS_STATE_r_12 , LTS_STATE_r_11 , 4, 'r', LTS_STATE_r_14 , LTS_STATE_r_13 , 3, 'u', LTS_STATE_r_16 , LTS_STATE_r_15 , 3, 'u', LTS_STATE_r_18 , LTS_STATE_r_17 , 1, '0', LTS_STATE_r_10 , LTS_STATE_r_19 , 255, 0, 0,0 , 0,0 , 4, 'r', LTS_STATE_r_22 , LTS_STATE_r_21 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_23 , 4, 'i', LTS_STATE_r_26 , LTS_STATE_r_25 , 2, 'p', LTS_STATE_r_28 , LTS_STATE_r_27 , 3, 'o', LTS_STATE_r_30 , LTS_STATE_r_29 , 1, '#', LTS_STATE_r_32 , LTS_STATE_r_31 , 3, 'i', LTS_STATE_r_34 , LTS_STATE_r_33 , 4, 'i', LTS_STATE_r_10 , LTS_STATE_r_35 , 2, 'b', LTS_STATE_r_10 , LTS_STATE_r_36 , 4, 'i', LTS_STATE_r_38 , LTS_STATE_r_37 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_39 , 2, 'i', LTS_STATE_r_40 , LTS_STATE_r_41 , 255, 57, 0,0 , 0,0 , 4, 'e', LTS_STATE_r_43 , LTS_STATE_r_42 , 2, 'p', LTS_STATE_r_45 , LTS_STATE_r_44 , 2, 't', LTS_STATE_r_10 , LTS_STATE_r_46 , 5, 'i', LTS_STATE_r_40 , LTS_STATE_r_47 , 3, 'i', LTS_STATE_r_49 , LTS_STATE_r_48 , 2, 'w', LTS_STATE_r_51 , LTS_STATE_r_50 , 2, 'o', LTS_STATE_r_53 , LTS_STATE_r_52 , 4, 'i', LTS_STATE_r_55 , LTS_STATE_r_54 , 3, 'a', LTS_STATE_r_57 , LTS_STATE_r_56 , 4, 'o', LTS_STATE_r_40 , LTS_STATE_r_58 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_59 , 3, 'a', LTS_STATE_r_61 , LTS_STATE_r_60 , 2, 'i', LTS_STATE_r_63 , LTS_STATE_r_62 , 5, 'n', LTS_STATE_r_65 , LTS_STATE_r_64 , 1, 'n', LTS_STATE_r_67 , LTS_STATE_r_66 , 255, 58, 0,0 , 0,0 , 2, 'u', LTS_STATE_r_40 , LTS_STATE_r_68 , 4, 'o', LTS_STATE_r_70 , LTS_STATE_r_69 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_71 , 5, 'v', LTS_STATE_r_40 , LTS_STATE_r_72 , 5, 'o', LTS_STATE_r_24 , LTS_STATE_r_73 , 2, 'g', LTS_STATE_r_24 , LTS_STATE_r_74 , 5, 'e', LTS_STATE_r_40 , LTS_STATE_r_75 , 3, 'r', LTS_STATE_r_77 , LTS_STATE_r_76 , 2, 'a', LTS_STATE_r_24 , LTS_STATE_r_78 , 1, '#', LTS_STATE_r_80 , LTS_STATE_r_79 , 1, '#', LTS_STATE_r_75 , LTS_STATE_r_81 , 2, 'a', LTS_STATE_r_83 , LTS_STATE_r_82 , 1, 'j', LTS_STATE_r_75 , LTS_STATE_r_84 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_85 , 2, 'k', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'z', LTS_STATE_r_87 , LTS_STATE_r_86 , 4, 'o', LTS_STATE_r_89 , LTS_STATE_r_88 , 5, 'i', LTS_STATE_r_75 , LTS_STATE_r_90 , 4, 'b', LTS_STATE_r_40 , LTS_STATE_r_91 , 2, 'w', LTS_STATE_r_10 , LTS_STATE_r_92 , 2, 'g', LTS_STATE_r_10 , LTS_STATE_r_93 , 5, '#', LTS_STATE_r_95 , LTS_STATE_r_94 , 4, 's', LTS_STATE_r_96 , LTS_STATE_r_24 , 5, 'z', LTS_STATE_r_40 , LTS_STATE_r_97 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_98 , 2, 'h', LTS_STATE_r_99 , LTS_STATE_r_10 , 5, 'e', LTS_STATE_r_40 , LTS_STATE_r_10 , 2, 'a', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 'a', LTS_STATE_r_101 , LTS_STATE_r_100 , 2, 'p', LTS_STATE_r_103 , LTS_STATE_r_102 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_104 , 5, 's', LTS_STATE_r_106 , LTS_STATE_r_105 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'm', LTS_STATE_r_10 , LTS_STATE_r_107 , 255, 59, 0,0 , 0,0 , 3, 'a', LTS_STATE_r_109 , LTS_STATE_r_108 , 2, 'u', LTS_STATE_r_111 , LTS_STATE_r_110 , 4, 'e', LTS_STATE_r_113 , LTS_STATE_r_112 , 4, '#', LTS_STATE_r_115 , LTS_STATE_r_114 , 4, 'o', LTS_STATE_r_117 , LTS_STATE_r_116 , 4, 'k', LTS_STATE_r_75 , LTS_STATE_r_118 , 4, 'e', LTS_STATE_r_120 , LTS_STATE_r_119 , 1, 't', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 's', LTS_STATE_r_122 , LTS_STATE_r_121 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_123 , 3, 'o', LTS_STATE_r_124 , LTS_STATE_r_24 , 3, 'g', LTS_STATE_r_75 , LTS_STATE_r_125 , 5, 's', LTS_STATE_r_126 , LTS_STATE_r_24 , 5, 'u', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_127 , 4, 'e', LTS_STATE_r_10 , LTS_STATE_r_128 , 2, 'd', LTS_STATE_r_130 , LTS_STATE_r_129 , 1, '#', LTS_STATE_r_132 , LTS_STATE_r_131 , 1, '0', LTS_STATE_r_134 , LTS_STATE_r_133 , 4, 'a', LTS_STATE_r_136 , LTS_STATE_r_135 , 5, '#', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'e', LTS_STATE_r_138 , LTS_STATE_r_137 , 1, 't', LTS_STATE_r_40 , LTS_STATE_r_139 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_10 , 2, 'p', LTS_STATE_r_141 , LTS_STATE_r_140 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_142 , 5, 'u', LTS_STATE_r_40 , LTS_STATE_r_143 , 5, 'n', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_144 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_145 , 2, 'd', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'h', LTS_STATE_r_10 , LTS_STATE_r_146 , 5, '#', LTS_STATE_r_148 , LTS_STATE_r_147 , 2, 'e', LTS_STATE_r_150 , LTS_STATE_r_149 , 1, 'c', LTS_STATE_r_152 , LTS_STATE_r_151 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_153 , 4, 'a', LTS_STATE_r_155 , LTS_STATE_r_154 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_156 , 4, 's', LTS_STATE_r_158 , LTS_STATE_r_157 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_159 , 4, 'a', LTS_STATE_r_161 , LTS_STATE_r_160 , 2, 'b', LTS_STATE_r_162 , LTS_STATE_r_24 , 4, 't', LTS_STATE_r_164 , LTS_STATE_r_163 , 4, 'a', LTS_STATE_r_166 , LTS_STATE_r_165 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_167 , 1, 'c', LTS_STATE_r_169 , LTS_STATE_r_168 , 1, 'n', LTS_STATE_r_75 , LTS_STATE_r_24 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_170 , 5, 'g', LTS_STATE_r_126 , LTS_STATE_r_24 , 5, 'y', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'i', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'i', LTS_STATE_r_24 , LTS_STATE_r_171 , 5, 'u', LTS_STATE_r_40 , LTS_STATE_r_75 , 3, 'i', LTS_STATE_r_172 , LTS_STATE_r_10 , 5, 'a', LTS_STATE_r_24 , LTS_STATE_r_10 , 5, 'a', LTS_STATE_r_10 , LTS_STATE_r_173 , 2, 'f', LTS_STATE_r_10 , LTS_STATE_r_174 , 5, 'i', LTS_STATE_r_176 , LTS_STATE_r_175 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_177 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_178 , 2, 'h', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_179 , 2, 'p', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_180 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_181 , 4, 'u', LTS_STATE_r_40 , LTS_STATE_r_182 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_183 , 2, 'f', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'j', LTS_STATE_r_24 , LTS_STATE_r_184 , 5, 'd', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'c', LTS_STATE_r_10 , LTS_STATE_r_185 , 4, 'z', LTS_STATE_r_40 , LTS_STATE_r_186 , 4, 'e', LTS_STATE_r_187 , LTS_STATE_r_24 , 1, '#', LTS_STATE_r_189 , LTS_STATE_r_188 , 4, 'n', LTS_STATE_r_191 , LTS_STATE_r_190 , 1, '#', LTS_STATE_r_193 , LTS_STATE_r_192 , 2, 'a', LTS_STATE_r_24 , LTS_STATE_r_194 , 5, 'c', LTS_STATE_r_40 , LTS_STATE_r_195 , 4, 'o', LTS_STATE_r_197 , LTS_STATE_r_196 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_198 , 5, 'c', LTS_STATE_r_40 , LTS_STATE_r_199 , 4, 'd', LTS_STATE_r_201 , LTS_STATE_r_200 , 5, '#', LTS_STATE_r_203 , LTS_STATE_r_202 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_204 , 2, 'c', LTS_STATE_r_206 , LTS_STATE_r_205 , 5, 'i', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'w', LTS_STATE_r_40 , LTS_STATE_r_75 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_207 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_208 , 4, 'g', LTS_STATE_r_210 , LTS_STATE_r_209 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_211 , 2, 's', LTS_STATE_r_213 , LTS_STATE_r_212 , 1, 'f', LTS_STATE_r_24 , LTS_STATE_r_214 , 5, 'g', LTS_STATE_r_75 , LTS_STATE_r_215 , 2, 's', LTS_STATE_r_217 , LTS_STATE_r_216 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_75 , 5, 'e', LTS_STATE_r_10 , LTS_STATE_r_218 , 2, 'm', LTS_STATE_r_10 , LTS_STATE_r_219 , 2, 't', LTS_STATE_r_10 , LTS_STATE_r_220 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_221 , 4, 's', LTS_STATE_r_223 , LTS_STATE_r_222 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_224 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_225 , 5, 'o', LTS_STATE_r_24 , LTS_STATE_r_226 , 2, 'f', LTS_STATE_r_40 , LTS_STATE_r_227 , 4, 'y', LTS_STATE_r_24 , LTS_STATE_r_228 , 4, 'l', LTS_STATE_r_75 , LTS_STATE_r_229 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_230 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_231 , 2, 'j', LTS_STATE_r_10 , LTS_STATE_r_232 , 3, 'y', LTS_STATE_r_234 , LTS_STATE_r_233 , 3, 'y', LTS_STATE_r_24 , LTS_STATE_r_235 , 4, '#', LTS_STATE_r_237 , LTS_STATE_r_236 , 4, 'o', LTS_STATE_r_239 , LTS_STATE_r_238 , 5, 'h', LTS_STATE_r_75 , LTS_STATE_r_240 , 5, '#', LTS_STATE_r_241 , LTS_STATE_r_75 , 2, 'a', LTS_STATE_r_243 , LTS_STATE_r_242 , 2, 'a', LTS_STATE_r_244 , LTS_STATE_r_24 , 4, 'i', LTS_STATE_r_24 , LTS_STATE_r_245 , 1, 'd', LTS_STATE_r_10 , LTS_STATE_r_246 , 4, 'i', LTS_STATE_r_248 , LTS_STATE_r_247 , 5, 'n', LTS_STATE_r_249 , LTS_STATE_r_24 , 1, 'd', LTS_STATE_r_40 , LTS_STATE_r_250 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_251 , 4, 'a', LTS_STATE_r_253 , LTS_STATE_r_252 , 2, 'f', LTS_STATE_r_254 , LTS_STATE_r_24 , 5, 'h', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_255 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_256 , 4, 's', LTS_STATE_r_257 , LTS_STATE_r_24 , 1, 'r', LTS_STATE_r_75 , LTS_STATE_r_258 , 1, 't', LTS_STATE_r_75 , LTS_STATE_r_259 , 4, 'i', LTS_STATE_r_261 , LTS_STATE_r_260 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_75 , 5, 'l', LTS_STATE_r_40 , LTS_STATE_r_262 , 1, 'i', LTS_STATE_r_10 , LTS_STATE_r_263 , 1, 'n', LTS_STATE_r_24 , LTS_STATE_r_264 , 5, 'e', LTS_STATE_r_24 , LTS_STATE_r_265 , 5, 'e', LTS_STATE_r_266 , LTS_STATE_r_24 , 4, 'y', LTS_STATE_r_24 , LTS_STATE_r_267 , 4, 'v', LTS_STATE_r_40 , LTS_STATE_r_268 , 1, '#', LTS_STATE_r_24 , LTS_STATE_r_10 , 1, 'c', LTS_STATE_r_10 , LTS_STATE_r_269 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_270 , 2, 'd', LTS_STATE_r_40 , LTS_STATE_r_271 , 2, 's', LTS_STATE_r_75 , LTS_STATE_r_272 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_273 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_274 , 5, 'a', LTS_STATE_r_276 , LTS_STATE_r_275 , 2, 'h', LTS_STATE_r_40 , LTS_STATE_r_277 , 5, 'a', LTS_STATE_r_279 , LTS_STATE_r_278 , 4, 'v', LTS_STATE_r_40 , LTS_STATE_r_280 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_281 , 2, 'b', LTS_STATE_r_103 , LTS_STATE_r_24 , 2, 'k', LTS_STATE_r_10 , LTS_STATE_r_282 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_283 , 4, 'n', LTS_STATE_r_75 , LTS_STATE_r_284 , 3, 'c', LTS_STATE_r_40 , LTS_STATE_r_285 , 4, 'd', LTS_STATE_r_287 , LTS_STATE_r_286 , 2, 'l', LTS_STATE_r_40 , LTS_STATE_r_288 , 4, 'a', LTS_STATE_r_290 , LTS_STATE_r_289 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_291 , 4, 'l', LTS_STATE_r_75 , LTS_STATE_r_292 , 1, 'h', LTS_STATE_r_40 , LTS_STATE_r_75 , 1, 'f', LTS_STATE_r_294 , LTS_STATE_r_293 , 1, 'b', LTS_STATE_r_24 , LTS_STATE_r_295 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_296 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_297 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_298 , 4, '#', LTS_STATE_r_24 , LTS_STATE_r_299 , 2, 'p', LTS_STATE_r_24 , LTS_STATE_r_300 , 2, 'v', LTS_STATE_r_24 , LTS_STATE_r_301 , 5, 't', LTS_STATE_r_301 , LTS_STATE_r_302 , 5, 'd', LTS_STATE_r_40 , LTS_STATE_r_303 , 5, 'z', LTS_STATE_r_40 , LTS_STATE_r_304 , 5, '#', LTS_STATE_r_136 , LTS_STATE_r_305 , 5, '#', LTS_STATE_r_40 , LTS_STATE_r_306 , 1, 'a', LTS_STATE_r_307 , LTS_STATE_r_40 , 5, 'r', LTS_STATE_r_24 , LTS_STATE_r_308 , 5, 'e', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, '#', LTS_STATE_r_309 , LTS_STATE_r_75 , 1, 'e', LTS_STATE_r_75 , LTS_STATE_r_310 , 4, 'y', LTS_STATE_r_312 , LTS_STATE_r_311 , 1, 'i', LTS_STATE_r_10 , LTS_STATE_r_313 , 5, 't', LTS_STATE_r_315 , LTS_STATE_r_314 , 2, 'e', LTS_STATE_r_75 , LTS_STATE_r_316 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'o', LTS_STATE_r_24 , LTS_STATE_r_317 , 4, 's', LTS_STATE_r_24 , LTS_STATE_r_75 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_318 , 5, 'e', LTS_STATE_r_75 , LTS_STATE_r_319 , 2, 'h', LTS_STATE_r_10 , LTS_STATE_r_320 , 2, 'j', LTS_STATE_r_10 , LTS_STATE_r_321 , 5, 'e', LTS_STATE_r_323 , LTS_STATE_r_322 , 4, 'm', LTS_STATE_r_325 , LTS_STATE_r_324 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_75 , 4, 's', LTS_STATE_r_40 , LTS_STATE_r_326 , 1, '0', LTS_STATE_r_24 , LTS_STATE_r_327 , 2, 'l', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'o', LTS_STATE_r_329 , LTS_STATE_r_328 , 4, 'd', LTS_STATE_r_24 , LTS_STATE_r_330 , 4, 'f', LTS_STATE_r_40 , LTS_STATE_r_331 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_332 , 5, 'e', LTS_STATE_r_334 , LTS_STATE_r_333 , 4, 'a', LTS_STATE_r_336 , LTS_STATE_r_335 , 4, 't', LTS_STATE_r_75 , LTS_STATE_r_337 , 1, 'f', LTS_STATE_r_40 , LTS_STATE_r_338 , 5, 't', LTS_STATE_r_340 , LTS_STATE_r_339 , 5, '#', LTS_STATE_r_342 , LTS_STATE_r_341 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_343 , 4, 'i', LTS_STATE_r_345 , LTS_STATE_r_344 , 2, 'h', LTS_STATE_r_306 , LTS_STATE_r_346 , 2, 'p', LTS_STATE_r_348 , LTS_STATE_r_347 , 1, 'l', LTS_STATE_r_350 , LTS_STATE_r_349 , 1, 't', LTS_STATE_r_352 , LTS_STATE_r_351 , 5, 'd', LTS_STATE_r_75 , LTS_STATE_r_353 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_354 , 5, 'v', LTS_STATE_r_40 , LTS_STATE_r_355 , 5, 'c', LTS_STATE_r_40 , LTS_STATE_r_356 , 5, 't', LTS_STATE_r_75 , LTS_STATE_r_357 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_358 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_359 , 1, '#', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'h', LTS_STATE_r_24 , LTS_STATE_r_360 , 2, 'f', LTS_STATE_r_362 , LTS_STATE_r_361 , 4, 'o', LTS_STATE_r_364 , LTS_STATE_r_363 , 5, 't', LTS_STATE_r_366 , LTS_STATE_r_365 , 5, 's', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 'n', LTS_STATE_r_24 , LTS_STATE_r_367 , 4, 'd', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 'o', LTS_STATE_r_369 , LTS_STATE_r_368 , 2, 'b', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_370 , 2, 'c', LTS_STATE_r_10 , LTS_STATE_r_371 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_10 , 2, 'j', LTS_STATE_r_40 , LTS_STATE_r_372 , 1, 'p', LTS_STATE_r_24 , LTS_STATE_r_373 , 5, 'u', LTS_STATE_r_375 , LTS_STATE_r_374 , 4, 'm', LTS_STATE_r_40 , LTS_STATE_r_376 , 5, 'e', LTS_STATE_r_10 , LTS_STATE_r_377 , 5, 'i', LTS_STATE_r_10 , LTS_STATE_r_378 , 2, 'h', LTS_STATE_r_380 , LTS_STATE_r_379 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_381 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_382 , 1, 'e', LTS_STATE_r_75 , LTS_STATE_r_383 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_384 , 2, 'd', LTS_STATE_r_40 , LTS_STATE_r_385 , 5, 'u', LTS_STATE_r_387 , LTS_STATE_r_386 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_388 , 2, 'd', LTS_STATE_r_75 , LTS_STATE_r_389 , 4, 'n', LTS_STATE_r_40 , LTS_STATE_r_390 , 5, 't', LTS_STATE_r_24 , LTS_STATE_r_391 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_392 , 2, 'f', LTS_STATE_r_24 , LTS_STATE_r_10 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_393 , 3, 'h', LTS_STATE_r_394 , LTS_STATE_r_24 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_395 , 3, 't', LTS_STATE_r_40 , LTS_STATE_r_396 , 4, 's', LTS_STATE_r_398 , LTS_STATE_r_397 , 4, 'i', LTS_STATE_r_400 , LTS_STATE_r_399 , 2, 'w', LTS_STATE_r_402 , LTS_STATE_r_401 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_403 , 2, 'n', LTS_STATE_r_40 , LTS_STATE_r_404 , 4, 'e', LTS_STATE_r_257 , LTS_STATE_r_24 , 5, 't', LTS_STATE_r_24 , LTS_STATE_r_405 , 5, 'd', LTS_STATE_r_407 , LTS_STATE_r_406 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_408 , 5, 'l', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 's', LTS_STATE_r_410 , LTS_STATE_r_409 , 4, '#', LTS_STATE_r_40 , LTS_STATE_r_126 , 1, 'w', LTS_STATE_r_412 , LTS_STATE_r_411 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_413 , 5, 'r', LTS_STATE_r_40 , LTS_STATE_r_414 , 1, 'g', LTS_STATE_r_24 , LTS_STATE_r_415 , 4, 'i', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 'e', LTS_STATE_r_417 , LTS_STATE_r_416 , 4, 'e', LTS_STATE_r_75 , LTS_STATE_r_418 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_419 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_420 , 5, 'b', LTS_STATE_r_24 , LTS_STATE_r_421 , 5, 's', LTS_STATE_r_264 , LTS_STATE_r_422 , 5, 'f', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 's', LTS_STATE_r_424 , LTS_STATE_r_423 , 5, 'u', LTS_STATE_r_426 , LTS_STATE_r_425 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_427 , 1, 'r', LTS_STATE_r_40 , LTS_STATE_r_428 , 4, 'g', LTS_STATE_r_430 , LTS_STATE_r_429 , 4, '#', LTS_STATE_r_432 , LTS_STATE_r_431 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_433 , 5, 'a', LTS_STATE_r_24 , LTS_STATE_r_434 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'r', LTS_STATE_r_10 , LTS_STATE_r_435 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_436 , 5, 'i', LTS_STATE_r_75 , LTS_STATE_r_437 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 'p', LTS_STATE_r_40 , LTS_STATE_r_75 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_438 , 5, 'y', LTS_STATE_r_10 , LTS_STATE_r_439 , 4, 'v', LTS_STATE_r_441 , LTS_STATE_r_440 , 4, 'm', LTS_STATE_r_75 , LTS_STATE_r_442 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_443 , 2, 'd', LTS_STATE_r_40 , LTS_STATE_r_444 , 1, 'x', LTS_STATE_r_75 , LTS_STATE_r_445 , 4, 'y', LTS_STATE_r_40 , LTS_STATE_r_446 , 5, 's', LTS_STATE_r_448 , LTS_STATE_r_447 , 5, 'i', LTS_STATE_r_450 , LTS_STATE_r_449 , 4, 'm', LTS_STATE_r_40 , LTS_STATE_r_451 , 2, 'b', LTS_STATE_r_452 , LTS_STATE_r_75 , 2, 'c', LTS_STATE_r_75 , LTS_STATE_r_453 , 4, 'c', LTS_STATE_r_47 , LTS_STATE_r_454 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_455 , 5, 'i', LTS_STATE_r_10 , LTS_STATE_r_456 , 4, '#', LTS_STATE_r_24 , LTS_STATE_r_457 , 2, 'a', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_458 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_459 , 5, 'z', LTS_STATE_r_461 , LTS_STATE_r_460 , 5, '#', LTS_STATE_r_462 , LTS_STATE_r_24 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_463 , 2, 'l', LTS_STATE_r_24 , LTS_STATE_r_464 , 5, 's', LTS_STATE_r_466 , LTS_STATE_r_465 , 5, 'l', LTS_STATE_r_40 , LTS_STATE_r_467 , 2, 'w', LTS_STATE_r_40 , LTS_STATE_r_468 , 2, 'a', LTS_STATE_r_24 , LTS_STATE_r_469 , 2, 'p', LTS_STATE_r_24 , LTS_STATE_r_470 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_471 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'u', LTS_STATE_r_40 , LTS_STATE_r_231 , 4, '#', LTS_STATE_r_24 , LTS_STATE_r_472 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_473 , 1, 'u', LTS_STATE_r_475 , LTS_STATE_r_474 , 4, 'i', LTS_STATE_r_75 , LTS_STATE_r_24 , 2, 'i', LTS_STATE_r_75 , LTS_STATE_r_476 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_477 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_478 , 5, 'b', LTS_STATE_r_40 , LTS_STATE_r_479 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_480 , 4, 'o', LTS_STATE_r_482 , LTS_STATE_r_481 , 4, 'y', LTS_STATE_r_24 , LTS_STATE_r_483 , 1, 'q', LTS_STATE_r_40 , LTS_STATE_r_484 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_485 , 5, 't', LTS_STATE_r_40 , LTS_STATE_r_486 , 2, 'b', LTS_STATE_r_488 , LTS_STATE_r_487 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_489 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_490 , 1, 't', LTS_STATE_r_75 , LTS_STATE_r_40 , 5, 'b', LTS_STATE_r_40 , LTS_STATE_r_491 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_492 , 5, 'z', LTS_STATE_r_40 , LTS_STATE_r_493 , 2, 'f', LTS_STATE_r_161 , LTS_STATE_r_24 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_494 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_495 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'z', LTS_STATE_r_40 , LTS_STATE_r_496 , 1, 'e', LTS_STATE_r_497 , LTS_STATE_r_24 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_498 , 4, 'v', LTS_STATE_r_75 , LTS_STATE_r_499 , 2, 'v', LTS_STATE_r_24 , LTS_STATE_r_10 , 2, 'd', LTS_STATE_r_10 , LTS_STATE_r_500 , 4, 'n', LTS_STATE_r_502 , LTS_STATE_r_501 , 5, 'a', LTS_STATE_r_503 , LTS_STATE_r_40 , 1, 't', LTS_STATE_r_505 , LTS_STATE_r_504 , 2, 't', LTS_STATE_r_507 , LTS_STATE_r_506 , 4, 'c', LTS_STATE_r_509 , LTS_STATE_r_508 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_510 , 4, 'm', LTS_STATE_r_75 , LTS_STATE_r_511 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_512 , 2, 'v', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'e', LTS_STATE_r_513 , LTS_STATE_r_75 , 4, 'l', LTS_STATE_r_210 , LTS_STATE_r_514 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 't', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'f', LTS_STATE_r_40 , LTS_STATE_r_515 , 4, 'k', LTS_STATE_r_75 , LTS_STATE_r_516 , 5, 'r', LTS_STATE_r_40 , LTS_STATE_r_517 , 2, 's', LTS_STATE_r_24 , LTS_STATE_r_10 , 3, 'd', LTS_STATE_r_519 , LTS_STATE_r_518 , 2, 's', LTS_STATE_r_520 , LTS_STATE_r_24 , 3, 'd', LTS_STATE_r_24 , LTS_STATE_r_521 , 5, 'n', LTS_STATE_r_523 , LTS_STATE_r_522 , 4, 'i', LTS_STATE_r_40 , LTS_STATE_r_524 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_525 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_526 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_527 , 5, 'l', LTS_STATE_r_40 , LTS_STATE_r_528 , 1, 'b', LTS_STATE_r_24 , LTS_STATE_r_529 , 1, 'k', LTS_STATE_r_40 , LTS_STATE_r_530 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_531 , 1, 'l', LTS_STATE_r_533 , LTS_STATE_r_532 , 5, 'e', LTS_STATE_r_534 , LTS_STATE_r_24 , 5, 'm', LTS_STATE_r_24 , LTS_STATE_r_535 , 5, 'n', LTS_STATE_r_24 , LTS_STATE_r_536 , 5, 'e', LTS_STATE_r_75 , LTS_STATE_r_537 , 4, 'h', LTS_STATE_r_40 , LTS_STATE_r_538 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_539 , 4, 'u', LTS_STATE_r_40 , LTS_STATE_r_540 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_541 , 1, 'f', LTS_STATE_r_24 , LTS_STATE_r_542 , 5, 'p', LTS_STATE_r_40 , LTS_STATE_r_543 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, '#', LTS_STATE_r_75 , LTS_STATE_r_544 , 5, 'w', LTS_STATE_r_75 , LTS_STATE_r_24 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_545 , 2, 'c', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_546 , 5, 'r', LTS_STATE_r_40 , LTS_STATE_r_547 , 5, 'd', LTS_STATE_r_549 , LTS_STATE_r_548 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_550 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_551 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'h', LTS_STATE_r_24 , LTS_STATE_r_552 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_553 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_554 , 5, 't', LTS_STATE_r_40 , LTS_STATE_r_555 , 2, 'e', LTS_STATE_r_557 , LTS_STATE_r_556 , 2, 't', LTS_STATE_r_559 , LTS_STATE_r_558 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_10 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_560 , 5, 'l', LTS_STATE_r_75 , LTS_STATE_r_561 , 2, 'p', LTS_STATE_r_10 , LTS_STATE_r_562 , 2, 'r', LTS_STATE_r_24 , LTS_STATE_r_563 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_564 , 2, 's', LTS_STATE_r_565 , LTS_STATE_r_40 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_566 , 5, 'p', LTS_STATE_r_24 , LTS_STATE_r_567 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_568 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_569 , 4, 't', LTS_STATE_r_571 , LTS_STATE_r_570 , 2, 'x', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'd', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'k', LTS_STATE_r_75 , LTS_STATE_r_572 , 2, 'm', LTS_STATE_r_574 , LTS_STATE_r_573 , 4, 'm', LTS_STATE_r_576 , LTS_STATE_r_575 , 4, 'd', LTS_STATE_r_75 , LTS_STATE_r_577 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_578 , 5, 'i', LTS_STATE_r_580 , LTS_STATE_r_579 , 5, 'f', LTS_STATE_r_40 , LTS_STATE_r_581 , 1, '#', LTS_STATE_r_24 , LTS_STATE_r_582 , 5, 'n', LTS_STATE_r_583 , LTS_STATE_r_24 , 5, 'a', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'a', LTS_STATE_r_40 , LTS_STATE_r_584 , 5, 'v', LTS_STATE_r_40 , LTS_STATE_r_585 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_586 , 4, 'c', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_587 , 1, 'p', LTS_STATE_r_40 , LTS_STATE_r_588 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'i', LTS_STATE_r_589 , LTS_STATE_r_24 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_590 , 5, 'e', LTS_STATE_r_40 , LTS_STATE_r_306 , 2, 'a', LTS_STATE_r_24 , LTS_STATE_r_591 , 2, 's', LTS_STATE_r_593 , LTS_STATE_r_592 , 2, 'i', LTS_STATE_r_40 , LTS_STATE_r_594 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'g', LTS_STATE_r_24 , LTS_STATE_r_595 , 1, 'y', LTS_STATE_r_24 , LTS_STATE_r_596 , 1, 'h', LTS_STATE_r_75 , LTS_STATE_r_24 , 1, 'g', LTS_STATE_r_598 , LTS_STATE_r_597 , 4, 'i', LTS_STATE_r_40 , LTS_STATE_r_10 , 5, 'n', LTS_STATE_r_599 , LTS_STATE_r_24 , 5, 'l', LTS_STATE_r_75 , LTS_STATE_r_600 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_601 , 4, 'a', LTS_STATE_r_40 , LTS_STATE_r_602 , 5, 'e', LTS_STATE_r_75 , LTS_STATE_r_603 , 1, '#', LTS_STATE_r_605 , LTS_STATE_r_604 , 2, 'v', LTS_STATE_r_24 , LTS_STATE_r_606 , 2, 't', LTS_STATE_r_96 , LTS_STATE_r_24 , 4, 'y', LTS_STATE_r_608 , LTS_STATE_r_607 , 4, 'e', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'n', LTS_STATE_r_40 , LTS_STATE_r_609 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_610 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_611 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_612 , 2, 'b', LTS_STATE_r_24 , LTS_STATE_r_613 , 2, 'b', LTS_STATE_r_615 , LTS_STATE_r_614 , 1, 's', LTS_STATE_r_75 , LTS_STATE_r_616 , 1, 't', LTS_STATE_r_24 , LTS_STATE_r_617 , 5, 'n', LTS_STATE_r_618 , LTS_STATE_r_24 , 5, 'n', LTS_STATE_r_40 , LTS_STATE_r_306 , 4, '#', LTS_STATE_r_24 , LTS_STATE_r_619 , 2, 't', LTS_STATE_r_75 , LTS_STATE_r_620 , 2, 'h', LTS_STATE_r_24 , LTS_STATE_r_621 , 4, 't', LTS_STATE_r_623 , LTS_STATE_r_622 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_624 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_75 , 5, 'y', LTS_STATE_r_40 , LTS_STATE_r_625 , 4, 't', LTS_STATE_r_75 , LTS_STATE_r_626 , 1, 't', LTS_STATE_r_40 , LTS_STATE_r_627 , 1, 'e', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'n', LTS_STATE_r_629 , LTS_STATE_r_628 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_630 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_631 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_632 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_633 , 4, 'g', LTS_STATE_r_634 , LTS_STATE_r_75 , 2, 'f', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 't', LTS_STATE_r_75 , LTS_STATE_r_635 , 4, 'm', LTS_STATE_r_75 , LTS_STATE_r_636 , 4, 'm', LTS_STATE_r_75 , LTS_STATE_r_637 , 4, 'm', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'c', LTS_STATE_r_40 , LTS_STATE_r_638 , 5, 's', LTS_STATE_r_639 , LTS_STATE_r_24 , 4, 'e', LTS_STATE_r_640 , LTS_STATE_r_24 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_641 , 1, 's', LTS_STATE_r_643 , LTS_STATE_r_642 , 4, 'o', LTS_STATE_r_40 , LTS_STATE_r_644 , 1, 'u', LTS_STATE_r_40 , LTS_STATE_r_645 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_646 , 2, 'n', LTS_STATE_r_24 , LTS_STATE_r_647 , 2, 'y', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'y', LTS_STATE_r_24 , LTS_STATE_r_648 , 1, 'm', LTS_STATE_r_40 , LTS_STATE_r_649 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'n', LTS_STATE_r_650 , LTS_STATE_r_24 , 5, 'o', LTS_STATE_r_652 , LTS_STATE_r_651 , 1, 'p', LTS_STATE_r_24 , LTS_STATE_r_653 , 2, 'e', LTS_STATE_r_10 , LTS_STATE_r_24 , 4, 'a', LTS_STATE_r_40 , LTS_STATE_r_75 , 5, 'n', LTS_STATE_r_654 , LTS_STATE_r_24 , 5, 'w', LTS_STATE_r_10 , LTS_STATE_r_655 , 4, 'o', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'y', LTS_STATE_r_75 , LTS_STATE_r_656 , 5, 'a', LTS_STATE_r_40 , LTS_STATE_r_657 , 2, 'v', LTS_STATE_r_658 , LTS_STATE_r_75 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_638 , 4, 'n', LTS_STATE_r_660 , LTS_STATE_r_659 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_661 , 5, 'e', LTS_STATE_r_24 , LTS_STATE_r_662 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_663 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_664 , 2, 'c', LTS_STATE_r_40 , LTS_STATE_r_665 , 4, 'b', LTS_STATE_r_161 , LTS_STATE_r_24 , 5, 'a', LTS_STATE_r_667 , LTS_STATE_r_666 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_668 , 2, 'c', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 's', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 's', LTS_STATE_r_24 , LTS_STATE_r_669 , 5, 'o', LTS_STATE_r_671 , LTS_STATE_r_670 , 5, 'e', LTS_STATE_r_10 , LTS_STATE_r_672 , 5, 's', LTS_STATE_r_674 , LTS_STATE_r_673 , 2, 'b', LTS_STATE_r_676 , LTS_STATE_r_675 , 1, 'a', LTS_STATE_r_678 , LTS_STATE_r_677 , 4, 't', LTS_STATE_r_75 , LTS_STATE_r_679 , 4, 'e', LTS_STATE_r_145 , LTS_STATE_r_40 , 2, 'p', LTS_STATE_r_681 , LTS_STATE_r_680 , 1, 's', LTS_STATE_r_682 , LTS_STATE_r_40 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_683 , 1, 'e', LTS_STATE_r_75 , LTS_STATE_r_684 , 4, 't', LTS_STATE_r_40 , LTS_STATE_r_685 , 1, 'x', LTS_STATE_r_24 , LTS_STATE_r_686 , 5, 'c', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 's', LTS_STATE_r_24 , LTS_STATE_r_75 , 2, 'v', LTS_STATE_r_75 , LTS_STATE_r_687 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_688 , 4, 'p', LTS_STATE_r_40 , LTS_STATE_r_689 , 5, 'n', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_690 , 2, 'n', LTS_STATE_r_40 , LTS_STATE_r_24 , 3, 'b', LTS_STATE_r_40 , LTS_STATE_r_24 , 5, 'b', LTS_STATE_r_40 , LTS_STATE_r_691 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_692 , 1, 'g', LTS_STATE_r_24 , LTS_STATE_r_693 , 1, 'i', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_371 , 1, 'e', LTS_STATE_r_24 , LTS_STATE_r_694 , 2, 'k', LTS_STATE_r_40 , LTS_STATE_r_695 , 2, 'f', LTS_STATE_r_24 , LTS_STATE_r_696 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 'd', LTS_STATE_r_537 , LTS_STATE_r_697 , 1, 'd', LTS_STATE_r_75 , LTS_STATE_r_24 , 2, 'i', LTS_STATE_r_10 , LTS_STATE_r_698 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_75 , 4, 'y', LTS_STATE_r_24 , LTS_STATE_r_699 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_412 , 2, 'k', LTS_STATE_r_671 , LTS_STATE_r_75 , 5, 'i', LTS_STATE_r_40 , LTS_STATE_r_75 , 5, '#', LTS_STATE_r_701 , LTS_STATE_r_700 , 5, '#', LTS_STATE_r_702 , LTS_STATE_r_24 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_703 , 4, 'g', LTS_STATE_r_24 , LTS_STATE_r_704 , 4, 'f', LTS_STATE_r_24 , LTS_STATE_r_705 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_706 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_707 , 1, 's', LTS_STATE_r_75 , LTS_STATE_r_708 , 4, 'b', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 's', LTS_STATE_r_75 , LTS_STATE_r_709 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_549 , 4, 'g', LTS_STATE_r_75 , LTS_STATE_r_710 , 4, 'k', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'w', LTS_STATE_r_24 , LTS_STATE_r_711 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_712 , 1, 'i', LTS_STATE_r_24 , LTS_STATE_r_713 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_714 , 5, 's', LTS_STATE_r_40 , LTS_STATE_r_715 , 2, 't', LTS_STATE_r_717 , LTS_STATE_r_716 , 5, 'a', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'a', LTS_STATE_r_40 , LTS_STATE_r_718 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_719 , 1, 's', LTS_STATE_r_720 , LTS_STATE_r_40 , 4, 'o', LTS_STATE_r_40 , LTS_STATE_r_721 , 2, 't', LTS_STATE_r_722 , LTS_STATE_r_75 , 1, 'd', LTS_STATE_r_40 , LTS_STATE_r_723 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_724 , 2, 'h', LTS_STATE_r_24 , LTS_STATE_r_725 , 2, 'c', LTS_STATE_r_726 , LTS_STATE_r_75 , 2, 'b', LTS_STATE_r_75 , LTS_STATE_r_727 , 5, 'u', LTS_STATE_r_728 , LTS_STATE_r_452 , 3, 'p', LTS_STATE_r_24 , LTS_STATE_r_729 , 5, 'y', LTS_STATE_r_731 , LTS_STATE_r_730 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_732 , 4, 'a', LTS_STATE_r_136 , LTS_STATE_r_733 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_734 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_735 , 1, 's', LTS_STATE_r_737 , LTS_STATE_r_736 , 4, 'i', LTS_STATE_r_24 , LTS_STATE_r_738 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_739 , 5, 'n', LTS_STATE_r_741 , LTS_STATE_r_740 , 1, 'o', LTS_STATE_r_743 , LTS_STATE_r_742 , 2, 'f', LTS_STATE_r_744 , LTS_STATE_r_24 , 1, 'g', LTS_STATE_r_24 , LTS_STATE_r_745 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_746 , 5, '#', LTS_STATE_r_747 , LTS_STATE_r_40 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_748 , 2, 'n', LTS_STATE_r_40 , LTS_STATE_r_749 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_594 , 2, 'e', LTS_STATE_r_75 , LTS_STATE_r_750 , 5, 'a', LTS_STATE_r_75 , LTS_STATE_r_751 , 5, 'a', LTS_STATE_r_452 , LTS_STATE_r_75 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_752 , 4, 'a', LTS_STATE_r_754 , LTS_STATE_r_753 , 4, 'u', LTS_STATE_r_40 , LTS_STATE_r_755 , 5, 's', LTS_STATE_r_757 , LTS_STATE_r_756 , 5, 'y', LTS_STATE_r_40 , LTS_STATE_r_758 , 5, 'a', LTS_STATE_r_40 , LTS_STATE_r_759 , 1, 's', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_760 , 4, 'l', LTS_STATE_r_40 , LTS_STATE_r_761 , 4, 's', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'l', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 'a', LTS_STATE_r_75 , LTS_STATE_r_40 , 2, 'v', LTS_STATE_r_75 , LTS_STATE_r_40 , 4, 'd', LTS_STATE_r_40 , LTS_STATE_r_762 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_763 , 4, 't', LTS_STATE_r_75 , LTS_STATE_r_40 , 2, 'h', LTS_STATE_r_75 , LTS_STATE_r_764 , 4, 's', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 'u', LTS_STATE_r_24 , LTS_STATE_r_765 , 4, 'y', LTS_STATE_r_767 , LTS_STATE_r_766 , 1, 'u', LTS_STATE_r_40 , LTS_STATE_r_768 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_769 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_770 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_771 , 1, 'p', LTS_STATE_r_40 , LTS_STATE_r_772 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_773 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_407 , 1, 'h', LTS_STATE_r_24 , LTS_STATE_r_774 , 4, 'a', LTS_STATE_r_776 , LTS_STATE_r_775 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_777 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_778 , 1, 'a', LTS_STATE_r_780 , LTS_STATE_r_779 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_781 , 4, 't', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'h', LTS_STATE_r_40 , LTS_STATE_r_782 , 2, 's', LTS_STATE_r_40 , LTS_STATE_r_783 , 1, 'l', LTS_STATE_r_40 , LTS_STATE_r_784 , 5, 'e', LTS_STATE_r_24 , LTS_STATE_r_355 , 5, 'n', LTS_STATE_r_786 , LTS_STATE_r_785 , 5, 'o', LTS_STATE_r_75 , LTS_STATE_r_787 , 1, 'y', LTS_STATE_r_40 , LTS_STATE_r_788 , 2, 'n', LTS_STATE_r_24 , LTS_STATE_r_10 , 4, 'e', LTS_STATE_r_790 , LTS_STATE_r_789 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_791 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_792 , 2, 'c', LTS_STATE_r_40 , LTS_STATE_r_793 , 2, 's', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 'l', LTS_STATE_r_75 , LTS_STATE_r_24 , 5, 'o', LTS_STATE_r_40 , LTS_STATE_r_75 , 4, 'n', LTS_STATE_r_75 , LTS_STATE_r_794 , 4, 'e', LTS_STATE_r_40 , LTS_STATE_r_795 , 4, 'n', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_796 , 4, 'b', LTS_STATE_r_40 , LTS_STATE_r_797 , 3, 'g', LTS_STATE_r_24 , LTS_STATE_r_798 , 5, '#', LTS_STATE_r_800 , LTS_STATE_r_799 , 2, 'n', LTS_STATE_r_24 , LTS_STATE_r_801 , 4, 't', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'e', LTS_STATE_r_24 , LTS_STATE_r_802 , 1, 's', LTS_STATE_r_24 , LTS_STATE_r_803 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_804 , 1, 'y', LTS_STATE_r_40 , LTS_STATE_r_805 , 1, 'u', LTS_STATE_r_40 , LTS_STATE_r_806 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_807 , 5, 'r', LTS_STATE_r_24 , LTS_STATE_r_808 , 1, 's', LTS_STATE_r_10 , LTS_STATE_r_24 , 1, 'j', LTS_STATE_r_24 , LTS_STATE_r_809 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_810 , 2, 'r', LTS_STATE_r_40 , LTS_STATE_r_811 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_812 , 4, 'c', LTS_STATE_r_40 , LTS_STATE_r_813 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_106 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_814 , 5, 'l', LTS_STATE_r_815 , LTS_STATE_r_24 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'i', LTS_STATE_r_75 , LTS_STATE_r_576 , 1, 'n', LTS_STATE_r_75 , LTS_STATE_r_816 , 4, 'o', LTS_STATE_r_818 , LTS_STATE_r_817 , 5, 'o', LTS_STATE_r_24 , LTS_STATE_r_819 , 2, 'v', LTS_STATE_r_820 , LTS_STATE_r_40 , 4, 'e', LTS_STATE_r_534 , LTS_STATE_r_40 , 2, 'w', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 's', LTS_STATE_r_75 , LTS_STATE_r_821 , 1, 'm', LTS_STATE_r_40 , LTS_STATE_r_822 , 5, 'd', LTS_STATE_r_40 , LTS_STATE_r_823 , 2, 's', LTS_STATE_r_75 , LTS_STATE_r_723 , 2, 'e', LTS_STATE_r_24 , LTS_STATE_r_824 , 4, 'o', LTS_STATE_r_73 , LTS_STATE_r_825 , 1, 'g', LTS_STATE_r_527 , LTS_STATE_r_24 , 1, 'e', LTS_STATE_r_24 , LTS_STATE_r_826 , 5, '#', LTS_STATE_r_24 , LTS_STATE_r_827 , 2, 'l', LTS_STATE_r_24 , LTS_STATE_r_828 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_650 , 1, 'e', LTS_STATE_r_830 , LTS_STATE_r_829 , 1, 'g', LTS_STATE_r_24 , LTS_STATE_r_831 , 4, 'y', LTS_STATE_r_24 , LTS_STATE_r_832 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_833 , 4, 'i', LTS_STATE_r_835 , LTS_STATE_r_834 , 1, 'w', LTS_STATE_r_10 , LTS_STATE_r_24 , 4, 'i', LTS_STATE_r_837 , LTS_STATE_r_836 , 2, 'v', LTS_STATE_r_40 , LTS_STATE_r_838 , 2, 'n', LTS_STATE_r_40 , LTS_STATE_r_839 , 1, 'n', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 'e', LTS_STATE_r_24 , LTS_STATE_r_840 , 5, 'e', LTS_STATE_r_75 , LTS_STATE_r_841 , 4, 'y', LTS_STATE_r_843 , LTS_STATE_r_842 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_844 , 5, 'd', LTS_STATE_r_40 , LTS_STATE_r_845 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_846 , 1, 'p', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'm', LTS_STATE_r_75 , LTS_STATE_r_847 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_848 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_849 , 5, 's', LTS_STATE_r_851 , LTS_STATE_r_850 , 2, 'r', LTS_STATE_r_24 , LTS_STATE_r_852 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_853 , 1, 't', LTS_STATE_r_24 , LTS_STATE_r_854 , 2, 'h', LTS_STATE_r_814 , LTS_STATE_r_855 , 2, 'r', LTS_STATE_r_24 , LTS_STATE_r_640 , 1, 'a', LTS_STATE_r_24 , LTS_STATE_r_856 , 4, 'a', LTS_STATE_r_24 , LTS_STATE_r_857 , 2, 'e', LTS_STATE_r_858 , LTS_STATE_r_24 , 1, 't', LTS_STATE_r_24 , LTS_STATE_r_859 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_860 , 5, 't', LTS_STATE_r_40 , LTS_STATE_r_861 , 5, 'a', LTS_STATE_r_24 , LTS_STATE_r_862 , 5, 'h', LTS_STATE_r_24 , LTS_STATE_r_863 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_276 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 'r', LTS_STATE_r_40 , LTS_STATE_r_617 , 2, 'u', LTS_STATE_r_865 , LTS_STATE_r_864 , 1, 'e', LTS_STATE_r_24 , LTS_STATE_r_40 , 5, 'u', LTS_STATE_r_40 , LTS_STATE_r_866 , 5, 'r', LTS_STATE_r_40 , LTS_STATE_r_867 , 5, 'g', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 'd', LTS_STATE_r_24 , LTS_STATE_r_868 , 5, 'c', LTS_STATE_r_40 , LTS_STATE_r_348 , 2, 's', LTS_STATE_r_24 , LTS_STATE_r_869 , 4, 'e', LTS_STATE_r_871 , LTS_STATE_r_870 , 4, 'i', LTS_STATE_r_872 , LTS_STATE_r_24 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_873 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_874 , 2, 'p', LTS_STATE_r_24 , LTS_STATE_r_875 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_876 , 1, 'i', LTS_STATE_r_24 , LTS_STATE_r_877 , 4, 'm', LTS_STATE_r_24 , LTS_STATE_r_878 , 4, '#', LTS_STATE_r_24 , LTS_STATE_r_879 , 1, 'n', LTS_STATE_r_24 , LTS_STATE_r_880 , 5, 'e', LTS_STATE_r_24 , LTS_STATE_r_10 , 5, 'u', LTS_STATE_r_821 , LTS_STATE_r_881 , 5, 'o', LTS_STATE_r_24 , LTS_STATE_r_882 , 2, 'm', LTS_STATE_r_40 , LTS_STATE_r_883 , 2, 'y', LTS_STATE_r_885 , LTS_STATE_r_884 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_886 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_887 , 1, 'n', LTS_STATE_r_24 , LTS_STATE_r_888 , 2, 'v', LTS_STATE_r_890 , LTS_STATE_r_889 , 2, 'o', LTS_STATE_r_24 , LTS_STATE_r_891 , 4, 'a', LTS_STATE_r_893 , LTS_STATE_r_892 , 1, 'q', LTS_STATE_r_24 , LTS_STATE_r_894 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_895 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_896 , 2, 'w', LTS_STATE_r_24 , LTS_STATE_r_897 , 2, 'h', LTS_STATE_r_40 , LTS_STATE_r_898 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_899 , 2, 'c', LTS_STATE_r_24 , LTS_STATE_r_900 , 4, 'h', LTS_STATE_r_24 , LTS_STATE_r_901 , 1, 'v', LTS_STATE_r_24 , LTS_STATE_r_902 , 1, 'p', LTS_STATE_r_24 , LTS_STATE_r_903 , 2, 'f', LTS_STATE_r_905 , LTS_STATE_r_904 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_906 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_907 , 1, 'a', LTS_STATE_r_40 , LTS_STATE_r_908 , 4, 'l', LTS_STATE_r_40 , LTS_STATE_r_24 , 4, 's', LTS_STATE_r_24 , LTS_STATE_r_909 , 2, 'p', LTS_STATE_r_40 , LTS_STATE_r_910 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_911 , 4, 'v', LTS_STATE_r_75 , LTS_STATE_r_912 , 4, 't', LTS_STATE_r_75 , LTS_STATE_r_913 , 4, 'i', LTS_STATE_r_24 , LTS_STATE_r_914 , 4, 'i', LTS_STATE_r_916 , LTS_STATE_r_915 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_917 , 2, 'p', LTS_STATE_r_24 , LTS_STATE_r_918 , 1, 'c', LTS_STATE_r_24 , LTS_STATE_r_919 , 1, 'i', LTS_STATE_r_24 , LTS_STATE_r_920 , 4, 'k', LTS_STATE_r_24 , LTS_STATE_r_921 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_24 , 2, 'r', LTS_STATE_r_24 , LTS_STATE_r_922 , 1, 'n', LTS_STATE_r_24 , LTS_STATE_r_923 , 1, '#', LTS_STATE_r_24 , LTS_STATE_r_75 , 4, 'o', LTS_STATE_r_24 , LTS_STATE_r_924 , 4, 'a', LTS_STATE_r_926 , LTS_STATE_r_925 , 4, 'f', LTS_STATE_r_814 , LTS_STATE_r_24 , 1, 'm', LTS_STATE_r_40 , LTS_STATE_r_927 , 5, 's', LTS_STATE_r_40 , LTS_STATE_r_928 , 2, 'f', LTS_STATE_r_24 , LTS_STATE_r_549 , 4, 'm', LTS_STATE_r_40 , LTS_STATE_r_929 , 5, 'a', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_103 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_930 , 1, 's', LTS_STATE_r_75 , LTS_STATE_r_931 , 4, 'g', LTS_STATE_r_75 , LTS_STATE_r_932 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_394 , 1, 'l', LTS_STATE_r_933 , LTS_STATE_r_24 , 2, 't', LTS_STATE_r_24 , LTS_STATE_r_934 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_935 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_936 , 2, 'l', LTS_STATE_r_24 , LTS_STATE_r_40 , 1, 'c', LTS_STATE_r_24 , LTS_STATE_r_937 , 4, 'l', LTS_STATE_r_24 , LTS_STATE_r_938 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_939 , 2, 'd', LTS_STATE_r_40 , LTS_STATE_r_940 , 4, 'y', LTS_STATE_r_10 , LTS_STATE_r_941 , 5, '#', LTS_STATE_r_10 , LTS_STATE_r_942 , 1, 's', LTS_STATE_r_40 , LTS_STATE_r_943 , 4, 'c', LTS_STATE_r_24 , LTS_STATE_r_944 , 1, 'g', LTS_STATE_r_24 , LTS_STATE_r_945 , 2, 'p', LTS_STATE_r_947 , LTS_STATE_r_946 , 1, 'f', LTS_STATE_r_40 , LTS_STATE_r_103 , 1, 'c', LTS_STATE_r_75 , LTS_STATE_r_948 , 4, 's', LTS_STATE_r_950 , LTS_STATE_r_949 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_276 , 2, 'h', LTS_STATE_r_40 , LTS_STATE_r_951 , 5, 'm', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'c', LTS_STATE_r_40 , LTS_STATE_r_952 , 1, 'u', LTS_STATE_r_24 , LTS_STATE_r_953 , 5, 'd', LTS_STATE_r_24 , LTS_STATE_r_954 , 2, 'n', LTS_STATE_r_955 , LTS_STATE_r_40 , 1, 'h', LTS_STATE_r_40 , LTS_STATE_r_956 , 1, 'd', LTS_STATE_r_958 , LTS_STATE_r_957 , 4, 'e', LTS_STATE_r_960 , LTS_STATE_r_959 , 1, 'h', LTS_STATE_r_10 , LTS_STATE_r_24 , 1, 'n', LTS_STATE_r_961 , LTS_STATE_r_24 , 1, 't', LTS_STATE_r_24 , LTS_STATE_r_962 , 5, 'r', LTS_STATE_r_964 , LTS_STATE_r_963 , 4, 's', LTS_STATE_r_965 , LTS_STATE_r_40 , 4, 'n', LTS_STATE_r_75 , LTS_STATE_r_966 , 4, 'b', LTS_STATE_r_75 , LTS_STATE_r_40 , 1, 'n', LTS_STATE_r_40 , LTS_STATE_r_75 , 5, 'e', LTS_STATE_r_967 , LTS_STATE_r_24 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_968 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_969 , 5, 'a', LTS_STATE_r_24 , LTS_STATE_r_970 , 1, 'i', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'k', LTS_STATE_r_40 , LTS_STATE_r_971 , 5, 't', LTS_STATE_r_10 , LTS_STATE_r_24 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_10 , 1, 'h', LTS_STATE_r_10 , LTS_STATE_r_972 , 1, 'h', LTS_STATE_r_24 , LTS_STATE_r_973 , 5, 's', LTS_STATE_r_24 , LTS_STATE_r_974 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_975 , 2, 'w', LTS_STATE_r_309 , LTS_STATE_r_976 , 1, 'n', LTS_STATE_r_977 , LTS_STATE_r_40 , 5, 't', LTS_STATE_r_40 , LTS_STATE_r_978 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_726 , 2, 'n', LTS_STATE_r_24 , LTS_STATE_r_979 , 5, 'k', LTS_STATE_r_24 , LTS_STATE_r_919 , 1, 'o', LTS_STATE_r_24 , LTS_STATE_r_980 , 2, 'h', LTS_STATE_r_981 , LTS_STATE_r_24 , 2, 'b', LTS_STATE_r_24 , LTS_STATE_r_982 , 1, 'm', LTS_STATE_r_24 , LTS_STATE_r_10 , 5, 'l', LTS_STATE_r_24 , LTS_STATE_r_10 , 4, 'm', LTS_STATE_r_909 , LTS_STATE_r_40 , 1, 'h', LTS_STATE_r_24 , LTS_STATE_r_983 , 1, 'c', LTS_STATE_r_985 , LTS_STATE_r_984 , 2, 'g', LTS_STATE_r_40 , LTS_STATE_r_75 , 1, 'm', LTS_STATE_r_75 , LTS_STATE_r_759 , 2, 'u', LTS_STATE_r_24 , LTS_STATE_r_986 , 2, 'd', LTS_STATE_r_24 , LTS_STATE_r_987 , 4, 'e', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'm', LTS_STATE_r_24 , LTS_STATE_r_988 , 5, 'n', LTS_STATE_r_919 , LTS_STATE_r_989 , 2, 't', LTS_STATE_r_40 , LTS_STATE_r_990 , 2, 'k', LTS_STATE_r_40 , LTS_STATE_r_75 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_919 , 2, 'i', LTS_STATE_r_24 , LTS_STATE_r_991 , 1, 'e', LTS_STATE_r_40 , LTS_STATE_r_992 , 1, 'i', LTS_STATE_r_24 , LTS_STATE_r_993 , 2, 'b', LTS_STATE_r_40 , LTS_STATE_r_994 , 1, 'l', LTS_STATE_r_24 , LTS_STATE_r_40 , 2, 'v', LTS_STATE_r_24 , LTS_STATE_r_995 , 2, 't', LTS_STATE_r_783 , LTS_STATE_r_996 , 5, 'a', LTS_STATE_r_997 , LTS_STATE_r_40 , 1, 'o', LTS_STATE_r_40 , LTS_STATE_r_998 , 5, 'c', LTS_STATE_r_24 , LTS_STATE_r_40 , 4, 's', LTS_STATE_r_999 , LTS_STATE_r_40 , 2, 'i', LTS_STATE_r_40 , LTS_STATE_r_24 , 1, 'i', LTS_STATE_r_75 , LTS_STATE_r_40 , /** letter s **/ 4, '#', LTS_STATE_s_2 , LTS_STATE_s_1 , 4, 'h', LTS_STATE_s_4 , LTS_STATE_s_3 , 3, 't', LTS_STATE_s_6 , LTS_STATE_s_5 , 4, 's', LTS_STATE_s_8 , LTS_STATE_s_7 , 3, 't', LTS_STATE_s_10 , LTS_STATE_s_9 , 3, 's', LTS_STATE_s_12 , LTS_STATE_s_11 , 255, 24, 0,0 , 0,0 , 5, 'h', LTS_STATE_s_15 , LTS_STATE_s_14 , 3, 'e', LTS_STATE_s_17 , LTS_STATE_s_16 , 1, '#', LTS_STATE_s_19 , LTS_STATE_s_18 , 255, 0, 0,0 , 0,0 , 3, 'u', LTS_STATE_s_21 , LTS_STATE_s_20 , 1, 'n', LTS_STATE_s_6 , LTS_STATE_s_22 , 2, '0', LTS_STATE_s_24 , LTS_STATE_s_23 , 3, 't', LTS_STATE_s_10 , LTS_STATE_s_25 , 5, 'p', LTS_STATE_s_27 , LTS_STATE_s_26 , 6, 'o', LTS_STATE_s_10 , LTS_STATE_s_28 , 255, 25, 0,0 , 0,0 , 3, 'i', LTS_STATE_s_29 , LTS_STATE_s_18 , 3, 'i', LTS_STATE_s_31 , LTS_STATE_s_30 , 2, 'a', LTS_STATE_s_32 , LTS_STATE_s_6 , 2, 'e', LTS_STATE_s_33 , LTS_STATE_s_6 , 4, 't', LTS_STATE_s_35 , LTS_STATE_s_34 , 4, 'z', LTS_STATE_s_18 , LTS_STATE_s_36 , 4, 'c', LTS_STATE_s_37 , LTS_STATE_s_6 , 1, '0', LTS_STATE_s_10 , LTS_STATE_s_38 , 3, 'i', LTS_STATE_s_6 , LTS_STATE_s_10 , 2, 'n', LTS_STATE_s_40 , LTS_STATE_s_39 , 6, 'n', LTS_STATE_s_6 , LTS_STATE_s_18 , 2, 't', LTS_STATE_s_42 , LTS_STATE_s_41 , 2, 'a', LTS_STATE_s_10 , LTS_STATE_s_43 , 1, 'h', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, 'i', LTS_STATE_s_6 , LTS_STATE_s_45 , 3, 's', LTS_STATE_s_47 , LTS_STATE_s_46 , 6, 'w', LTS_STATE_s_48 , LTS_STATE_s_6 , 4, 'j', LTS_STATE_s_18 , LTS_STATE_s_49 , 6, 'o', LTS_STATE_s_51 , LTS_STATE_s_50 , 1, '#', LTS_STATE_s_53 , LTS_STATE_s_52 , 2, 'm', LTS_STATE_s_10 , LTS_STATE_s_54 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_10 , 3, 'k', LTS_STATE_s_6 , LTS_STATE_s_55 , 3, 'e', LTS_STATE_s_6 , LTS_STATE_s_56 , 2, 'o', LTS_STATE_s_10 , LTS_STATE_s_57 , 255, 60, 0,0 , 0,0 , 1, 'l', LTS_STATE_s_6 , LTS_STATE_s_58 , 4, 'k', LTS_STATE_s_6 , LTS_STATE_s_59 , 5, 'o', LTS_STATE_s_61 , LTS_STATE_s_60 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_62 , 4, 'r', LTS_STATE_s_64 , LTS_STATE_s_63 , 6, 'i', LTS_STATE_s_66 , LTS_STATE_s_65 , 2, '0', LTS_STATE_s_18 , LTS_STATE_s_6 , 5, 'o', LTS_STATE_s_68 , LTS_STATE_s_67 , 2, 'f', LTS_STATE_s_70 , LTS_STATE_s_69 , 1, '0', LTS_STATE_s_10 , LTS_STATE_s_71 , 3, 'p', LTS_STATE_s_6 , LTS_STATE_s_72 , 3, 'h', LTS_STATE_s_6 , LTS_STATE_s_73 , 2, 'e', LTS_STATE_s_44 , LTS_STATE_s_74 , 1, 'u', LTS_STATE_s_6 , LTS_STATE_s_75 , 6, 'n', LTS_STATE_s_77 , LTS_STATE_s_76 , 4, 'u', LTS_STATE_s_79 , LTS_STATE_s_78 , 6, 'n', LTS_STATE_s_18 , LTS_STATE_s_6 , 2, 'r', LTS_STATE_s_6 , LTS_STATE_s_44 , 6, 'a', LTS_STATE_s_6 , LTS_STATE_s_80 , 5, 'i', LTS_STATE_s_6 , LTS_STATE_s_18 , 3, 'z', LTS_STATE_s_10 , LTS_STATE_s_81 , 1, '0', LTS_STATE_s_18 , LTS_STATE_s_6 , 6, 'a', LTS_STATE_s_83 , LTS_STATE_s_82 , 1, 's', LTS_STATE_s_44 , LTS_STATE_s_84 , 5, 't', LTS_STATE_s_6 , LTS_STATE_s_85 , 3, 'o', LTS_STATE_s_6 , LTS_STATE_s_86 , 2, 'f', LTS_STATE_s_10 , LTS_STATE_s_87 , 3, 'c', LTS_STATE_s_6 , LTS_STATE_s_88 , 1, 'i', LTS_STATE_s_6 , LTS_STATE_s_89 , 2, 'u', LTS_STATE_s_44 , LTS_STATE_s_90 , 1, 't', LTS_STATE_s_10 , LTS_STATE_s_6 , 4, 'z', LTS_STATE_s_92 , LTS_STATE_s_91 , 4, 'i', LTS_STATE_s_94 , LTS_STATE_s_93 , 2, 'e', LTS_STATE_s_96 , LTS_STATE_s_95 , 5, 'r', LTS_STATE_s_18 , LTS_STATE_s_97 , 5, 'r', LTS_STATE_s_98 , LTS_STATE_s_6 , 1, '#', LTS_STATE_s_99 , LTS_STATE_s_18 , 6, 'o', LTS_STATE_s_10 , LTS_STATE_s_100 , 3, 'u', LTS_STATE_s_10 , LTS_STATE_s_101 , 3, 'u', LTS_STATE_s_6 , LTS_STATE_s_102 , 2, 'b', LTS_STATE_s_104 , LTS_STATE_s_103 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_10 , 2, 'i', LTS_STATE_s_10 , LTS_STATE_s_105 , 2, 'k', LTS_STATE_s_107 , LTS_STATE_s_106 , 1, 'n', LTS_STATE_s_109 , LTS_STATE_s_108 , 1, 'o', LTS_STATE_s_6 , LTS_STATE_s_110 , 4, 'm', LTS_STATE_s_112 , LTS_STATE_s_111 , 6, 'o', LTS_STATE_s_6 , LTS_STATE_s_18 , 4, 'z', LTS_STATE_s_18 , LTS_STATE_s_113 , 5, 'o', LTS_STATE_s_115 , LTS_STATE_s_114 , 5, 'a', LTS_STATE_s_117 , LTS_STATE_s_116 , 1, 'm', LTS_STATE_s_6 , LTS_STATE_s_118 , 2, 'i', LTS_STATE_s_119 , LTS_STATE_s_6 , 4, 'u', LTS_STATE_s_120 , LTS_STATE_s_6 , 6, 'a', LTS_STATE_s_6 , LTS_STATE_s_121 , 1, 'w', LTS_STATE_s_123 , LTS_STATE_s_122 , 5, 'm', LTS_STATE_s_102 , LTS_STATE_s_10 , 2, 'l', LTS_STATE_s_6 , LTS_STATE_s_10 , 2, 'g', LTS_STATE_s_86 , LTS_STATE_s_124 , 3, 'u', LTS_STATE_s_10 , LTS_STATE_s_125 , 1, 'p', LTS_STATE_s_127 , LTS_STATE_s_126 , 3, 'f', LTS_STATE_s_6 , LTS_STATE_s_128 , 3, 'e', LTS_STATE_s_6 , LTS_STATE_s_129 , 1, 'o', LTS_STATE_s_44 , LTS_STATE_s_130 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_131 , 4, 'e', LTS_STATE_s_133 , LTS_STATE_s_132 , 5, '#', LTS_STATE_s_44 , LTS_STATE_s_134 , 4, 'c', LTS_STATE_s_6 , LTS_STATE_s_135 , 5, 'g', LTS_STATE_s_137 , LTS_STATE_s_136 , 3, 'n', LTS_STATE_s_18 , LTS_STATE_s_138 , 6, 'v', LTS_STATE_s_44 , LTS_STATE_s_139 , 4, 'i', LTS_STATE_s_18 , LTS_STATE_s_140 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_141 , 1, '#', LTS_STATE_s_18 , LTS_STATE_s_6 , 6, 'e', LTS_STATE_s_18 , LTS_STATE_s_6 , 6, 'e', LTS_STATE_s_142 , LTS_STATE_s_18 , 3, 'i', LTS_STATE_s_144 , LTS_STATE_s_143 , 5, '#', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 'd', LTS_STATE_s_145 , LTS_STATE_s_10 , 3, 'i', LTS_STATE_s_10 , LTS_STATE_s_146 , 1, '#', LTS_STATE_s_148 , LTS_STATE_s_147 , 5, 'u', LTS_STATE_s_10 , LTS_STATE_s_149 , 3, 'a', LTS_STATE_s_151 , LTS_STATE_s_150 , 1, 'i', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, 't', LTS_STATE_s_44 , LTS_STATE_s_152 , 1, 'i', LTS_STATE_s_154 , LTS_STATE_s_153 , 4, 'u', LTS_STATE_s_156 , LTS_STATE_s_155 , 3, 'r', LTS_STATE_s_6 , LTS_STATE_s_157 , 5, 's', LTS_STATE_s_44 , LTS_STATE_s_158 , 4, 'p', LTS_STATE_s_6 , LTS_STATE_s_159 , 255, 39, 0,0 , 0,0 , 3, 'e', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'l', LTS_STATE_s_18 , LTS_STATE_s_136 , 6, 's', LTS_STATE_s_161 , LTS_STATE_s_160 , 1, 'l', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'd', LTS_STATE_s_6 , LTS_STATE_s_162 , 3, 'u', LTS_STATE_s_18 , LTS_STATE_s_163 , 1, 'e', LTS_STATE_s_10 , LTS_STATE_s_164 , 5, 'a', LTS_STATE_s_165 , LTS_STATE_s_10 , 3, 'i', LTS_STATE_s_10 , LTS_STATE_s_166 , 6, '#', LTS_STATE_s_6 , LTS_STATE_s_167 , 1, 'r', LTS_STATE_s_169 , LTS_STATE_s_168 , 2, 'b', LTS_STATE_s_10 , LTS_STATE_s_170 , 5, 'l', LTS_STATE_s_10 , LTS_STATE_s_171 , 2, 'p', LTS_STATE_s_173 , LTS_STATE_s_172 , 2, 'z', LTS_STATE_s_44 , LTS_STATE_s_174 , 1, 'l', LTS_STATE_s_44 , LTS_STATE_s_175 , 1, 'a', LTS_STATE_s_6 , LTS_STATE_s_176 , 2, 't', LTS_STATE_s_6 , LTS_STATE_s_44 , 4, 'c', LTS_STATE_s_178 , LTS_STATE_s_177 , 5, 'r', LTS_STATE_s_180 , LTS_STATE_s_179 , 3, 'n', LTS_STATE_s_182 , LTS_STATE_s_181 , 3, 'r', LTS_STATE_s_6 , LTS_STATE_s_183 , 3, 'd', LTS_STATE_s_44 , LTS_STATE_s_184 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_185 , 1, 'p', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'b', LTS_STATE_s_6 , LTS_STATE_s_186 , 2, 'r', LTS_STATE_s_6 , LTS_STATE_s_187 , 6, 'c', LTS_STATE_s_10 , LTS_STATE_s_188 , 2, 'r', LTS_STATE_s_6 , LTS_STATE_s_10 , 3, 'o', LTS_STATE_s_10 , LTS_STATE_s_6 , 5, 'i', LTS_STATE_s_10 , LTS_STATE_s_86 , 2, 'r', LTS_STATE_s_190 , LTS_STATE_s_189 , 2, 'g', LTS_STATE_s_10 , LTS_STATE_s_191 , 5, 'o', LTS_STATE_s_6 , LTS_STATE_s_192 , 6, '#', LTS_STATE_s_10 , LTS_STATE_s_193 , 3, 'o', LTS_STATE_s_195 , LTS_STATE_s_194 , 3, 'o', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 'y', LTS_STATE_s_6 , LTS_STATE_s_196 , 1, 's', LTS_STATE_s_44 , LTS_STATE_s_197 , 2, 'k', LTS_STATE_s_44 , LTS_STATE_s_6 , 4, 'i', LTS_STATE_s_199 , LTS_STATE_s_198 , 5, 'i', LTS_STATE_s_201 , LTS_STATE_s_200 , 6, 'l', LTS_STATE_s_136 , LTS_STATE_s_202 , 3, 'n', LTS_STATE_s_204 , LTS_STATE_s_203 , 2, 'o', LTS_STATE_s_206 , LTS_STATE_s_205 , 5, 'y', LTS_STATE_s_44 , LTS_STATE_s_207 , 5, 'i', LTS_STATE_s_209 , LTS_STATE_s_208 , 3, 't', LTS_STATE_s_6 , LTS_STATE_s_210 , 2, 'i', LTS_STATE_s_6 , LTS_STATE_s_211 , 6, 'd', LTS_STATE_s_10 , LTS_STATE_s_212 , 3, 'o', LTS_STATE_s_6 , LTS_STATE_s_18 , 1, 'l', LTS_STATE_s_10 , LTS_STATE_s_213 , 2, 'h', LTS_STATE_s_10 , LTS_STATE_s_214 , 5, 'l', LTS_STATE_s_10 , LTS_STATE_s_215 , 5, '#', LTS_STATE_s_216 , LTS_STATE_s_6 , 2, 'r', LTS_STATE_s_10 , LTS_STATE_s_217 , 5, 'e', LTS_STATE_s_6 , LTS_STATE_s_218 , 3, 'h', LTS_STATE_s_220 , LTS_STATE_s_219 , 2, 'o', LTS_STATE_s_44 , LTS_STATE_s_221 , 1, 'u', LTS_STATE_s_44 , LTS_STATE_s_222 , 1, 'a', LTS_STATE_s_44 , LTS_STATE_s_173 , 3, 'x', LTS_STATE_s_10 , LTS_STATE_s_223 , 5, 'a', LTS_STATE_s_225 , LTS_STATE_s_224 , 2, 'e', LTS_STATE_s_226 , LTS_STATE_s_6 , 2, 'o', LTS_STATE_s_18 , LTS_STATE_s_6 , 3, 'e', LTS_STATE_s_227 , LTS_STATE_s_6 , 6, 'e', LTS_STATE_s_136 , LTS_STATE_s_228 , 6, 'e', LTS_STATE_s_18 , LTS_STATE_s_229 , 5, '#', LTS_STATE_s_231 , LTS_STATE_s_230 , 5, 'r', LTS_STATE_s_233 , LTS_STATE_s_232 , 1, 'e', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'l', LTS_STATE_s_44 , LTS_STATE_s_234 , 6, 'c', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'w', LTS_STATE_s_44 , LTS_STATE_s_235 , 1, 'c', LTS_STATE_s_6 , LTS_STATE_s_236 , 1, 'f', LTS_STATE_s_6 , LTS_STATE_s_237 , 1, 't', LTS_STATE_s_10 , LTS_STATE_s_238 , 1, 'l', LTS_STATE_s_6 , LTS_STATE_s_239 , 6, 'r', LTS_STATE_s_10 , LTS_STATE_s_240 , 2, 'l', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 'h', LTS_STATE_s_6 , LTS_STATE_s_241 , 6, 'n', LTS_STATE_s_243 , LTS_STATE_s_242 , 3, 'e', LTS_STATE_s_244 , LTS_STATE_s_44 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_245 , 1, 'u', LTS_STATE_s_247 , LTS_STATE_s_246 , 2, 'l', LTS_STATE_s_249 , LTS_STATE_s_248 , 4, 'p', LTS_STATE_s_251 , LTS_STATE_s_250 , 2, 'p', LTS_STATE_s_253 , LTS_STATE_s_252 , 6, '#', LTS_STATE_s_255 , LTS_STATE_s_254 , 5, 'o', LTS_STATE_s_6 , LTS_STATE_s_44 , 5, 'm', LTS_STATE_s_44 , LTS_STATE_s_256 , 2, 'e', LTS_STATE_s_136 , LTS_STATE_s_6 , 6, 'g', LTS_STATE_s_6 , LTS_STATE_s_257 , 5, 'd', LTS_STATE_s_259 , LTS_STATE_s_258 , 3, 'p', LTS_STATE_s_6 , LTS_STATE_s_260 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_261 , 1, '#', LTS_STATE_s_44 , LTS_STATE_s_262 , 2, 'c', LTS_STATE_s_44 , LTS_STATE_s_263 , 1, '0', LTS_STATE_s_265 , LTS_STATE_s_264 , 4, 'o', LTS_STATE_s_267 , LTS_STATE_s_266 , 1, 'h', LTS_STATE_s_10 , LTS_STATE_s_268 , 6, 'i', LTS_STATE_s_270 , LTS_STATE_s_269 , 1, 'b', LTS_STATE_s_10 , LTS_STATE_s_271 , 6, 'v', LTS_STATE_s_10 , LTS_STATE_s_272 , 2, 'l', LTS_STATE_s_274 , LTS_STATE_s_273 , 2, 'r', LTS_STATE_s_123 , LTS_STATE_s_6 , 5, 'i', LTS_STATE_s_6 , LTS_STATE_s_10 , 1, 'q', LTS_STATE_s_6 , LTS_STATE_s_275 , 1, 'i', LTS_STATE_s_44 , LTS_STATE_s_276 , 2, 'l', LTS_STATE_s_44 , LTS_STATE_s_277 , 2, 'l', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_278 , 1, 'l', LTS_STATE_s_44 , LTS_STATE_s_279 , 4, 'o', LTS_STATE_s_281 , LTS_STATE_s_280 , 3, 'w', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'u', LTS_STATE_s_283 , LTS_STATE_s_282 , 6, 'i', LTS_STATE_s_44 , LTS_STATE_s_284 , 6, 'k', LTS_STATE_s_6 , LTS_STATE_s_285 , 2, 'n', LTS_STATE_s_136 , LTS_STATE_s_286 , 5, 'l', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 'i', LTS_STATE_s_18 , LTS_STATE_s_6 , 5, 'r', LTS_STATE_s_288 , LTS_STATE_s_287 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_289 , 3, 'a', LTS_STATE_s_291 , LTS_STATE_s_290 , 5, 'd', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'r', LTS_STATE_s_44 , LTS_STATE_s_292 , 3, 'd', LTS_STATE_s_44 , LTS_STATE_s_293 , 3, 'r', LTS_STATE_s_6 , LTS_STATE_s_294 , 3, 'i', LTS_STATE_s_10 , LTS_STATE_s_295 , 1, 'g', LTS_STATE_s_297 , LTS_STATE_s_296 , 1, 'l', LTS_STATE_s_10 , LTS_STATE_s_298 , 1, 'i', LTS_STATE_s_6 , LTS_STATE_s_299 , 5, 'u', LTS_STATE_s_10 , LTS_STATE_s_300 , 5, 'f', LTS_STATE_s_6 , LTS_STATE_s_10 , 1, 'o', LTS_STATE_s_10 , LTS_STATE_s_301 , 1, 'b', LTS_STATE_s_10 , LTS_STATE_s_302 , 2, 'w', LTS_STATE_s_6 , LTS_STATE_s_303 , 6, 'n', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 'f', LTS_STATE_s_6 , LTS_STATE_s_304 , 2, 'a', LTS_STATE_s_44 , LTS_STATE_s_305 , 2, 'g', LTS_STATE_s_44 , LTS_STATE_s_306 , 1, 'a', LTS_STATE_s_44 , LTS_STATE_s_307 , 1, 'a', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'g', LTS_STATE_s_309 , LTS_STATE_s_308 , 5, 'r', LTS_STATE_s_311 , LTS_STATE_s_310 , 3, 'i', LTS_STATE_s_313 , LTS_STATE_s_312 , 5, 'v', LTS_STATE_s_6 , LTS_STATE_s_314 , 1, 'e', LTS_STATE_s_44 , LTS_STATE_s_315 , 1, 't', LTS_STATE_s_44 , LTS_STATE_s_316 , 3, 'o', LTS_STATE_s_6 , LTS_STATE_s_317 , 2, 'r', LTS_STATE_s_319 , LTS_STATE_s_318 , 2, 'e', LTS_STATE_s_321 , LTS_STATE_s_320 , 3, 'p', LTS_STATE_s_6 , LTS_STATE_s_322 , 3, 'l', LTS_STATE_s_6 , LTS_STATE_s_323 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_324 , 3, 'u', LTS_STATE_s_6 , LTS_STATE_s_44 , 6, 's', LTS_STATE_s_44 , LTS_STATE_s_325 , 2, 'u', LTS_STATE_s_6 , LTS_STATE_s_326 , 4, 'm', LTS_STATE_s_44 , LTS_STATE_s_6 , 5, 'i', LTS_STATE_s_328 , LTS_STATE_s_327 , 2, 'a', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'h', LTS_STATE_s_6 , LTS_STATE_s_329 , 1, 'c', LTS_STATE_s_331 , LTS_STATE_s_330 , 2, 'c', LTS_STATE_s_10 , LTS_STATE_s_332 , 2, 'l', LTS_STATE_s_10 , LTS_STATE_s_333 , 5, 'e', LTS_STATE_s_335 , LTS_STATE_s_334 , 6, 'l', LTS_STATE_s_10 , LTS_STATE_s_336 , 1, 'e', LTS_STATE_s_247 , LTS_STATE_s_44 , 2, 'g', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 'd', LTS_STATE_s_44 , LTS_STATE_s_337 , 2, 'e', LTS_STATE_s_339 , LTS_STATE_s_338 , 5, 'e', LTS_STATE_s_341 , LTS_STATE_s_340 , 4, 'b', LTS_STATE_s_44 , LTS_STATE_s_342 , 3, 'a', LTS_STATE_s_344 , LTS_STATE_s_343 , 2, 'v', LTS_STATE_s_44 , LTS_STATE_s_345 , 3, 'e', LTS_STATE_s_347 , LTS_STATE_s_346 , 5, 't', LTS_STATE_s_44 , LTS_STATE_s_348 , 5, '#', LTS_STATE_s_6 , LTS_STATE_s_349 , 6, 'e', LTS_STATE_s_44 , LTS_STATE_s_350 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_18 , 3, 'a', LTS_STATE_s_136 , LTS_STATE_s_6 , 3, 'i', LTS_STATE_s_352 , LTS_STATE_s_351 , 5, 'n', LTS_STATE_s_354 , LTS_STATE_s_353 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_355 , 3, 'y', LTS_STATE_s_44 , LTS_STATE_s_356 , 1, 'o', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'w', LTS_STATE_s_44 , LTS_STATE_s_357 , 2, 'b', LTS_STATE_s_6 , LTS_STATE_s_358 , 1, 'u', LTS_STATE_s_6 , LTS_STATE_s_359 , 4, 'o', LTS_STATE_s_6 , LTS_STATE_s_360 , 1, 'f', LTS_STATE_s_362 , LTS_STATE_s_361 , 2, 'o', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 'u', LTS_STATE_s_123 , LTS_STATE_s_6 , 1, 'v', LTS_STATE_s_6 , LTS_STATE_s_363 , 5, 'r', LTS_STATE_s_364 , LTS_STATE_s_6 , 6, 'f', LTS_STATE_s_10 , LTS_STATE_s_365 , 5, 'i', LTS_STATE_s_10 , LTS_STATE_s_366 , 1, 'd', LTS_STATE_s_6 , LTS_STATE_s_367 , 1, 'd', LTS_STATE_s_10 , LTS_STATE_s_368 , 2, 'j', LTS_STATE_s_6 , LTS_STATE_s_369 , 1, 'a', LTS_STATE_s_371 , LTS_STATE_s_370 , 1, 'r', LTS_STATE_s_373 , LTS_STATE_s_372 , 1, 'n', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'd', LTS_STATE_s_375 , LTS_STATE_s_374 , 6, '#', LTS_STATE_s_377 , LTS_STATE_s_376 , 1, 'i', LTS_STATE_s_44 , LTS_STATE_s_378 , 1, '#', LTS_STATE_s_380 , LTS_STATE_s_379 , 2, 'e', LTS_STATE_s_381 , LTS_STATE_s_6 , 3, 'b', LTS_STATE_s_44 , LTS_STATE_s_382 , 2, 'h', LTS_STATE_s_384 , LTS_STATE_s_383 , 2, 'r', LTS_STATE_s_386 , LTS_STATE_s_385 , 2, 'd', LTS_STATE_s_6 , LTS_STATE_s_387 , 6, 'e', LTS_STATE_s_44 , LTS_STATE_s_388 , 6, 'g', LTS_STATE_s_44 , LTS_STATE_s_389 , 3, 'u', LTS_STATE_s_391 , LTS_STATE_s_390 , 2, 'w', LTS_STATE_s_44 , LTS_STATE_s_392 , 1, '#', LTS_STATE_s_394 , LTS_STATE_s_393 , 6, 't', LTS_STATE_s_44 , LTS_STATE_s_395 , 2, 'i', LTS_STATE_s_6 , LTS_STATE_s_396 , 3, 'l', LTS_STATE_s_6 , LTS_STATE_s_397 , 2, 'h', LTS_STATE_s_44 , LTS_STATE_s_398 , 1, 'c', LTS_STATE_s_6 , LTS_STATE_s_399 , 6, 't', LTS_STATE_s_401 , LTS_STATE_s_400 , 3, 'i', LTS_STATE_s_6 , LTS_STATE_s_402 , 1, 'b', LTS_STATE_s_404 , LTS_STATE_s_403 , 2, 'u', LTS_STATE_s_6 , LTS_STATE_s_405 , 4, 'y', LTS_STATE_s_6 , LTS_STATE_s_406 , 6, '#', LTS_STATE_s_6 , LTS_STATE_s_407 , 2, 'l', LTS_STATE_s_409 , LTS_STATE_s_408 , 2, 'u', LTS_STATE_s_10 , LTS_STATE_s_410 , 5, '#', LTS_STATE_s_10 , LTS_STATE_s_411 , 6, 's', LTS_STATE_s_6 , LTS_STATE_s_10 , 5, 'e', LTS_STATE_s_10 , LTS_STATE_s_412 , 2, 'm', LTS_STATE_s_44 , LTS_STATE_s_413 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_378 , 2, 'r', LTS_STATE_s_415 , LTS_STATE_s_414 , 2, 'g', LTS_STATE_s_6 , LTS_STATE_s_44 , 4, 'l', LTS_STATE_s_417 , LTS_STATE_s_416 , 4, 'r', LTS_STATE_s_418 , LTS_STATE_s_6 , 1, '0', LTS_STATE_s_420 , LTS_STATE_s_419 , 3, 'i', LTS_STATE_s_10 , LTS_STATE_s_421 , 2, 'n', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'i', LTS_STATE_s_161 , LTS_STATE_s_422 , 2, 'r', LTS_STATE_s_424 , LTS_STATE_s_423 , 6, '#', LTS_STATE_s_425 , LTS_STATE_s_44 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_6 , 5, 'e', LTS_STATE_s_6 , LTS_STATE_s_426 , 3, 'y', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'a', LTS_STATE_s_44 , LTS_STATE_s_427 , 1, '#', LTS_STATE_s_44 , LTS_STATE_s_428 , 2, 'v', LTS_STATE_s_44 , LTS_STATE_s_429 , 6, 'g', LTS_STATE_s_431 , LTS_STATE_s_430 , 5, 't', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'o', LTS_STATE_s_433 , LTS_STATE_s_432 , 2, 'a', LTS_STATE_s_44 , LTS_STATE_s_434 , 1, 'r', LTS_STATE_s_44 , LTS_STATE_s_435 , 5, 's', LTS_STATE_s_436 , LTS_STATE_s_6 , 3, 'o', LTS_STATE_s_44 , LTS_STATE_s_437 , 3, 'o', LTS_STATE_s_44 , LTS_STATE_s_438 , 3, 'e', LTS_STATE_s_44 , LTS_STATE_s_439 , 1, 'h', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'b', LTS_STATE_s_44 , LTS_STATE_s_440 , 1, 'r', LTS_STATE_s_6 , LTS_STATE_s_441 , 6, 'y', LTS_STATE_s_6 , LTS_STATE_s_442 , 5, 'a', LTS_STATE_s_6 , LTS_STATE_s_44 , 3, 'k', LTS_STATE_s_6 , LTS_STATE_s_443 , 1, 'l', LTS_STATE_s_445 , LTS_STATE_s_444 , 2, 'u', LTS_STATE_s_6 , LTS_STATE_s_446 , 4, 'i', LTS_STATE_s_6 , LTS_STATE_s_10 , 1, 'j', LTS_STATE_s_448 , LTS_STATE_s_447 , 6, 'i', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'g', LTS_STATE_s_10 , LTS_STATE_s_449 , 6, 's', LTS_STATE_s_10 , LTS_STATE_s_450 , 2, 'c', LTS_STATE_s_10 , LTS_STATE_s_451 , 5, 'i', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 't', LTS_STATE_s_6 , LTS_STATE_s_10 , 1, 'l', LTS_STATE_s_6 , LTS_STATE_s_452 , 1, 't', LTS_STATE_s_44 , LTS_STATE_s_453 , 1, 't', LTS_STATE_s_44 , LTS_STATE_s_207 , 3, 'p', LTS_STATE_s_6 , LTS_STATE_s_454 , 2, 'o', LTS_STATE_s_6 , LTS_STATE_s_455 , 3, 'e', LTS_STATE_s_10 , LTS_STATE_s_6 , 3, 'u', LTS_STATE_s_6 , LTS_STATE_s_456 , 3, 'i', LTS_STATE_s_10 , LTS_STATE_s_6 , 4, 'n', LTS_STATE_s_10 , LTS_STATE_s_6 , 3, 'y', LTS_STATE_s_457 , LTS_STATE_s_6 , 2, 'm', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'a', LTS_STATE_s_44 , LTS_STATE_s_256 , 1, 'r', LTS_STATE_s_6 , LTS_STATE_s_44 , 6, 'g', LTS_STATE_s_173 , LTS_STATE_s_458 , 5, 'r', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'e', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'p', LTS_STATE_s_44 , LTS_STATE_s_459 , 5, 'b', LTS_STATE_s_44 , LTS_STATE_s_460 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_44 , 3, 'e', LTS_STATE_s_462 , LTS_STATE_s_461 , 6, '#', LTS_STATE_s_464 , LTS_STATE_s_463 , 2, 'm', LTS_STATE_s_44 , LTS_STATE_s_465 , 2, 'h', LTS_STATE_s_44 , LTS_STATE_s_466 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_6 , 5, 'm', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'd', LTS_STATE_s_6 , LTS_STATE_s_137 , 1, 'h', LTS_STATE_s_44 , LTS_STATE_s_467 , 2, 'e', LTS_STATE_s_469 , LTS_STATE_s_468 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_470 , 5, 'a', LTS_STATE_s_472 , LTS_STATE_s_471 , 2, 'r', LTS_STATE_s_474 , LTS_STATE_s_473 , 5, 'e', LTS_STATE_s_6 , LTS_STATE_s_475 , 5, 'f', LTS_STATE_s_6 , LTS_STATE_s_476 , 5, '#', LTS_STATE_s_10 , LTS_STATE_s_477 , 4, 'l', LTS_STATE_s_479 , LTS_STATE_s_478 , 6, '#', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'o', LTS_STATE_s_10 , LTS_STATE_s_480 , 5, 'b', LTS_STATE_s_10 , LTS_STATE_s_481 , 2, 's', LTS_STATE_s_10 , LTS_STATE_s_482 , 2, 'n', LTS_STATE_s_484 , LTS_STATE_s_483 , 1, 'm', LTS_STATE_s_44 , LTS_STATE_s_485 , 4, 'q', LTS_STATE_s_6 , LTS_STATE_s_486 , 1, 'r', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'y', LTS_STATE_s_488 , LTS_STATE_s_487 , 2, 'a', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'a', LTS_STATE_s_490 , LTS_STATE_s_489 , 2, 'a', LTS_STATE_s_44 , LTS_STATE_s_491 , 5, 'c', LTS_STATE_s_44 , LTS_STATE_s_6 , 5, 'y', LTS_STATE_s_493 , LTS_STATE_s_492 , 1, 'h', LTS_STATE_s_44 , LTS_STATE_s_494 , 2, 'j', LTS_STATE_s_6 , LTS_STATE_s_495 , 2, 'p', LTS_STATE_s_44 , LTS_STATE_s_496 , 2, 'f', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'h', LTS_STATE_s_44 , LTS_STATE_s_497 , 6, '#', LTS_STATE_s_499 , LTS_STATE_s_498 , 1, 'i', LTS_STATE_s_6 , LTS_STATE_s_500 , 3, 'e', LTS_STATE_s_425 , LTS_STATE_s_6 , 1, 'l', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'd', LTS_STATE_s_6 , LTS_STATE_s_501 , 2, 'a', LTS_STATE_s_6 , LTS_STATE_s_502 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_503 , 1, '#', LTS_STATE_s_44 , LTS_STATE_s_6 , 6, 'a', LTS_STATE_s_6 , LTS_STATE_s_504 , 5, 's', LTS_STATE_s_6 , LTS_STATE_s_505 , 5, 'd', LTS_STATE_s_6 , LTS_STATE_s_506 , 1, 'r', LTS_STATE_s_508 , LTS_STATE_s_507 , 1, 'r', LTS_STATE_s_6 , LTS_STATE_s_509 , 5, 'a', LTS_STATE_s_10 , LTS_STATE_s_510 , 3, 'a', LTS_STATE_s_511 , LTS_STATE_s_10 , 2, 't', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'd', LTS_STATE_s_62 , LTS_STATE_s_512 , 1, 'i', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'p', LTS_STATE_s_6 , LTS_STATE_s_513 , 4, 'a', LTS_STATE_s_515 , LTS_STATE_s_514 , 3, 'i', LTS_STATE_s_6 , LTS_STATE_s_516 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_490 , 1, 'r', LTS_STATE_s_457 , LTS_STATE_s_517 , 2, 'e', LTS_STATE_s_44 , LTS_STATE_s_6 , 5, '#', LTS_STATE_s_6 , LTS_STATE_s_518 , 3, 'a', LTS_STATE_s_519 , LTS_STATE_s_6 , 3, 't', LTS_STATE_s_6 , LTS_STATE_s_520 , 5, 't', LTS_STATE_s_6 , LTS_STATE_s_521 , 6, 'u', LTS_STATE_s_6 , LTS_STATE_s_522 , 2, 'l', LTS_STATE_s_44 , LTS_STATE_s_474 , 5, 's', LTS_STATE_s_44 , LTS_STATE_s_523 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_524 , 1, '#', LTS_STATE_s_44 , LTS_STATE_s_525 , 2, 't', LTS_STATE_s_6 , LTS_STATE_s_526 , 5, 'e', LTS_STATE_s_137 , LTS_STATE_s_6 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_527 , 3, 'o', LTS_STATE_s_6 , LTS_STATE_s_528 , 6, 'g', LTS_STATE_s_6 , LTS_STATE_s_529 , 2, 'a', LTS_STATE_s_530 , LTS_STATE_s_6 , 4, 'i', LTS_STATE_s_6 , LTS_STATE_s_297 , 5, 'a', LTS_STATE_s_6 , LTS_STATE_s_531 , 6, 'g', LTS_STATE_s_10 , LTS_STATE_s_532 , 6, 'r', LTS_STATE_s_10 , LTS_STATE_s_6 , 2, 'a', LTS_STATE_s_10 , LTS_STATE_s_533 , 1, 'c', LTS_STATE_s_10 , LTS_STATE_s_534 , 1, 'n', LTS_STATE_s_6 , LTS_STATE_s_535 , 1, 'e', LTS_STATE_s_44 , LTS_STATE_s_536 , 3, 't', LTS_STATE_s_6 , LTS_STATE_s_537 , 3, 'r', LTS_STATE_s_6 , LTS_STATE_s_538 , 2, 'e', LTS_STATE_s_540 , LTS_STATE_s_539 , 2, 'r', LTS_STATE_s_474 , LTS_STATE_s_6 , 2, 'o', LTS_STATE_s_44 , LTS_STATE_s_541 , 2, 'e', LTS_STATE_s_256 , LTS_STATE_s_6 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_542 , 1, 'g', LTS_STATE_s_6 , LTS_STATE_s_543 , 1, '#', LTS_STATE_s_256 , LTS_STATE_s_6 , 6, '#', LTS_STATE_s_6 , LTS_STATE_s_544 , 6, 's', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_545 , 2, 'c', LTS_STATE_s_547 , LTS_STATE_s_546 , 6, 'r', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, 'k', LTS_STATE_s_44 , LTS_STATE_s_548 , 1, 'o', LTS_STATE_s_6 , LTS_STATE_s_549 , 5, 'c', LTS_STATE_s_10 , LTS_STATE_s_6 , 4, 'o', LTS_STATE_s_10 , LTS_STATE_s_550 , 4, 'm', LTS_STATE_s_10 , LTS_STATE_s_551 , 2, 't', LTS_STATE_s_10 , LTS_STATE_s_552 , 5, '#', LTS_STATE_s_10 , LTS_STATE_s_553 , 2, 'h', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, 'i', LTS_STATE_s_44 , LTS_STATE_s_554 , 3, 'i', LTS_STATE_s_556 , LTS_STATE_s_555 , 5, 'n', LTS_STATE_s_558 , LTS_STATE_s_557 , 3, 'd', LTS_STATE_s_44 , LTS_STATE_s_559 , 1, 'r', LTS_STATE_s_6 , LTS_STATE_s_560 , 2, 'u', LTS_STATE_s_44 , LTS_STATE_s_561 , 3, 'l', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'h', LTS_STATE_s_6 , LTS_STATE_s_562 , 1, 'w', LTS_STATE_s_6 , LTS_STATE_s_563 , 1, 's', LTS_STATE_s_6 , LTS_STATE_s_564 , 1, 'e', LTS_STATE_s_566 , LTS_STATE_s_565 , 3, 'u', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'l', LTS_STATE_s_44 , LTS_STATE_s_567 , 1, 'w', LTS_STATE_s_6 , LTS_STATE_s_568 , 5, 'n', LTS_STATE_s_6 , LTS_STATE_s_569 , 5, 'r', LTS_STATE_s_6 , LTS_STATE_s_570 , 6, 'm', LTS_STATE_s_10 , LTS_STATE_s_571 , 1, 'g', LTS_STATE_s_6 , LTS_STATE_s_10 , 2, 'd', LTS_STATE_s_44 , LTS_STATE_s_572 , 3, 'w', LTS_STATE_s_44 , LTS_STATE_s_573 , 4, 'r', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 'v', LTS_STATE_s_44 , LTS_STATE_s_574 , 2, 'e', LTS_STATE_s_44 , LTS_STATE_s_575 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_576 , 4, 'b', LTS_STATE_s_44 , LTS_STATE_s_577 , 6, 'e', LTS_STATE_s_6 , LTS_STATE_s_578 , 6, 's', LTS_STATE_s_44 , LTS_STATE_s_579 , 2, 'e', LTS_STATE_s_580 , LTS_STATE_s_6 , 3, 'u', LTS_STATE_s_6 , LTS_STATE_s_457 , 1, 'a', LTS_STATE_s_137 , LTS_STATE_s_581 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_436 , 1, 'i', LTS_STATE_s_44 , LTS_STATE_s_582 , 6, 'l', LTS_STATE_s_583 , LTS_STATE_s_6 , 5, 's', LTS_STATE_s_6 , LTS_STATE_s_584 , 6, 't', LTS_STATE_s_6 , LTS_STATE_s_585 , 1, 'r', LTS_STATE_s_587 , LTS_STATE_s_586 , 2, 's', LTS_STATE_s_6 , LTS_STATE_s_44 , 5, 's', LTS_STATE_s_6 , LTS_STATE_s_588 , 5, 'l', LTS_STATE_s_590 , LTS_STATE_s_589 , 6, '#', LTS_STATE_s_44 , LTS_STATE_s_524 , 1, 'c', LTS_STATE_s_6 , LTS_STATE_s_591 , 1, 'n', LTS_STATE_s_44 , LTS_STATE_s_592 , 2, 'r', LTS_STATE_s_44 , LTS_STATE_s_593 , 5, 'n', LTS_STATE_s_594 , LTS_STATE_s_6 , 5, 'n', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'i', LTS_STATE_s_44 , LTS_STATE_s_595 , 2, 'l', LTS_STATE_s_44 , LTS_STATE_s_596 , 4, 'a', LTS_STATE_s_10 , LTS_STATE_s_6 , 1, 'n', LTS_STATE_s_598 , LTS_STATE_s_597 , 5, 'v', LTS_STATE_s_6 , LTS_STATE_s_599 , 6, 'e', LTS_STATE_s_10 , LTS_STATE_s_600 , 2, 'e', LTS_STATE_s_10 , LTS_STATE_s_165 , 3, 'k', LTS_STATE_s_6 , LTS_STATE_s_601 , 3, 'a', LTS_STATE_s_6 , LTS_STATE_s_602 , 6, 'e', LTS_STATE_s_6 , LTS_STATE_s_603 , 6, 'l', LTS_STATE_s_605 , LTS_STATE_s_604 , 3, 'n', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_606 , 6, '#', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'r', LTS_STATE_s_608 , LTS_STATE_s_607 , 3, 'a', LTS_STATE_s_295 , LTS_STATE_s_609 , 6, '#', LTS_STATE_s_611 , LTS_STATE_s_610 , 5, 'e', LTS_STATE_s_6 , LTS_STATE_s_10 , 5, '#', LTS_STATE_s_6 , LTS_STATE_s_612 , 6, 's', LTS_STATE_s_10 , LTS_STATE_s_613 , 3, 'a', LTS_STATE_s_490 , LTS_STATE_s_614 , 2, 'e', LTS_STATE_s_6 , LTS_STATE_s_615 , 3, 'o', LTS_STATE_s_44 , LTS_STATE_s_616 , 4, 'f', LTS_STATE_s_6 , LTS_STATE_s_617 , 4, 'n', LTS_STATE_s_6 , LTS_STATE_s_44 , 2, 'e', LTS_STATE_s_6 , LTS_STATE_s_322 , 2, 'p', LTS_STATE_s_44 , LTS_STATE_s_618 , 2, 'i', LTS_STATE_s_44 , LTS_STATE_s_6 , 2, 't', LTS_STATE_s_6 , LTS_STATE_s_619 , 6, 'r', LTS_STATE_s_6 , LTS_STATE_s_620 , 5, 'd', LTS_STATE_s_6 , LTS_STATE_s_10 , 4, 'e', LTS_STATE_s_621 , LTS_STATE_s_10 , 2, 'm', LTS_STATE_s_10 , LTS_STATE_s_622 , 4, 'f', LTS_STATE_s_6 , LTS_STATE_s_623 , 6, 'l', LTS_STATE_s_44 , LTS_STATE_s_624 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_592 , 2, 'o', LTS_STATE_s_6 , LTS_STATE_s_625 , 1, '#', LTS_STATE_s_44 , LTS_STATE_s_626 , 4, 'b', LTS_STATE_s_44 , LTS_STATE_s_627 , 4, 'e', LTS_STATE_s_6 , LTS_STATE_s_628 , 5, 's', LTS_STATE_s_10 , LTS_STATE_s_629 , 6, 'd', LTS_STATE_s_10 , LTS_STATE_s_630 , 4, 'n', LTS_STATE_s_6 , LTS_STATE_s_631 , 6, 'c', LTS_STATE_s_173 , LTS_STATE_s_632 , 2, 'c', LTS_STATE_s_6 , LTS_STATE_s_633 , 1, 'l', LTS_STATE_s_44 , LTS_STATE_s_634 , 2, 'i', LTS_STATE_s_44 , LTS_STATE_s_635 , 1, 's', LTS_STATE_s_6 , LTS_STATE_s_636 , 5, 'd', LTS_STATE_s_10 , LTS_STATE_s_6 , 6, '#', LTS_STATE_s_10 , LTS_STATE_s_637 , 2, 'l', LTS_STATE_s_44 , LTS_STATE_s_638 , 6, 'i', LTS_STATE_s_547 , LTS_STATE_s_639 , 4, 'w', LTS_STATE_s_6 , LTS_STATE_s_640 , 2, 'i', LTS_STATE_s_6 , LTS_STATE_s_44 , 1, 'h', LTS_STATE_s_6 , LTS_STATE_s_641 , 1, 'l', LTS_STATE_s_6 , LTS_STATE_s_10 , 1, 'a', LTS_STATE_s_10 , LTS_STATE_s_642 , 1, 'f', LTS_STATE_s_6 , LTS_STATE_s_643 , 5, 'b', LTS_STATE_s_431 , LTS_STATE_s_644 , 1, 'g', LTS_STATE_s_6 , LTS_STATE_s_645 , 2, 'e', LTS_STATE_s_6 , LTS_STATE_s_646 , 1, 'b', LTS_STATE_s_10 , LTS_STATE_s_647 , 1, 'c', LTS_STATE_s_44 , LTS_STATE_s_648 , 6, 'e', LTS_STATE_s_6 , LTS_STATE_s_649 , 4, 'l', LTS_STATE_s_6 , LTS_STATE_s_650 , 4, 'm', LTS_STATE_s_6 , LTS_STATE_s_547 , 1, 'm', LTS_STATE_s_10 , LTS_STATE_s_651 , 3, 'u', LTS_STATE_s_6 , LTS_STATE_s_652 , 2, 'a', LTS_STATE_s_654 , LTS_STATE_s_653 , 6, 'r', LTS_STATE_s_655 , LTS_STATE_s_44 , 1, 's', LTS_STATE_s_10 , LTS_STATE_s_656 , 3, 'o', LTS_STATE_s_658 , LTS_STATE_s_657 , 6, 's', LTS_STATE_s_6 , LTS_STATE_s_659 , 5, '#', LTS_STATE_s_6 , LTS_STATE_s_455 , 2, 'a', LTS_STATE_s_6 , LTS_STATE_s_660 , 3, 'a', LTS_STATE_s_123 , LTS_STATE_s_10 , 4, 'd', LTS_STATE_s_662 , LTS_STATE_s_661 , 5, '#', LTS_STATE_s_44 , LTS_STATE_s_6 , 3, 'u', LTS_STATE_s_663 , LTS_STATE_s_517 , 1, '#', LTS_STATE_s_6 , LTS_STATE_s_664 , 3, 'e', LTS_STATE_s_378 , LTS_STATE_s_665 , 1, 'd', LTS_STATE_s_44 , LTS_STATE_s_666 , 6, '#', LTS_STATE_s_6 , LTS_STATE_s_667 , 3, 'n', LTS_STATE_s_44 , LTS_STATE_s_6 , 1, 'h', LTS_STATE_s_6 , LTS_STATE_s_668 , 2, 'u', LTS_STATE_s_44 , LTS_STATE_s_669 , 5, '#', LTS_STATE_s_6 , LTS_STATE_s_44 , 5, 'r', LTS_STATE_s_44 , LTS_STATE_s_670 , 2, 'a', LTS_STATE_s_6 , LTS_STATE_s_44 , 3, 'm', LTS_STATE_s_44 , LTS_STATE_s_671 , 3, 'r', LTS_STATE_s_6 , LTS_STATE_s_672 , 6, 'c', LTS_STATE_s_44 , LTS_STATE_s_673 , 2, 'u', LTS_STATE_s_6 , LTS_STATE_s_674 , 4, 'v', LTS_STATE_s_44 , LTS_STATE_s_675 , 6, 'r', LTS_STATE_s_676 , LTS_STATE_s_457 , 2, 'e', LTS_STATE_s_44 , LTS_STATE_s_677 , 4, 'b', LTS_STATE_s_44 , LTS_STATE_s_669 , /** letter t **/ 4, 'h', LTS_STATE_t_2 , LTS_STATE_t_1 , 5, 'o', LTS_STATE_t_4 , LTS_STATE_t_3 , 5, 'e', LTS_STATE_t_6 , LTS_STATE_t_5 , 4, 't', LTS_STATE_t_8 , LTS_STATE_t_7 , 4, 'i', LTS_STATE_t_10 , LTS_STATE_t_9 , 5, '#', LTS_STATE_t_12 , LTS_STATE_t_11 , 6, 'r', LTS_STATE_t_14 , LTS_STATE_t_13 , 4, 'c', LTS_STATE_t_16 , LTS_STATE_t_15 , 3, 'e', LTS_STATE_t_18 , LTS_STATE_t_17 , 4, 't', LTS_STATE_t_20 , LTS_STATE_t_19 , 3, 's', LTS_STATE_t_22 , LTS_STATE_t_21 , 3, 's', LTS_STATE_t_24 , LTS_STATE_t_23 , 255, 61, 0,0 , 0,0 , 6, '#', LTS_STATE_t_27 , LTS_STATE_t_26 , 3, '#', LTS_STATE_t_12 , LTS_STATE_t_28 , 4, 'u', LTS_STATE_t_30 , LTS_STATE_t_29 , 5, 'h', LTS_STATE_t_32 , LTS_STATE_t_31 , 5, 's', LTS_STATE_t_34 , LTS_STATE_t_33 , 5, 's', LTS_STATE_t_32 , LTS_STATE_t_35 , 4, 'u', LTS_STATE_t_37 , LTS_STATE_t_36 , 3, 'e', LTS_STATE_t_32 , LTS_STATE_t_38 , 3, 'n', LTS_STATE_t_40 , LTS_STATE_t_39 , 255, 21, 0,0 , 0,0 , 5, 'o', LTS_STATE_t_42 , LTS_STATE_t_41 , 6, 'a', LTS_STATE_t_12 , LTS_STATE_t_31 , 6, 'a', LTS_STATE_t_44 , LTS_STATE_t_43 , 3, 'n', LTS_STATE_t_12 , LTS_STATE_t_45 , 3, 'a', LTS_STATE_t_45 , LTS_STATE_t_27 , 3, 't', LTS_STATE_t_47 , LTS_STATE_t_46 , 3, '#', LTS_STATE_t_31 , LTS_STATE_t_48 , 255, 27, 0,0 , 0,0 , 255, 0, 0,0 , 0,0 , 6, 'd', LTS_STATE_t_32 , LTS_STATE_t_49 , 6, '#', LTS_STATE_t_51 , LTS_STATE_t_50 , 5, 'l', LTS_STATE_t_52 , LTS_STATE_t_32 , 3, 't', LTS_STATE_t_54 , LTS_STATE_t_53 , 6, 'u', LTS_STATE_t_22 , LTS_STATE_t_31 , 6, 'm', LTS_STATE_t_32 , LTS_STATE_t_55 , 6, 'n', LTS_STATE_t_40 , LTS_STATE_t_56 , 255, 25, 0,0 , 0,0 , 6, '#', LTS_STATE_t_58 , LTS_STATE_t_57 , 6, 'r', LTS_STATE_t_12 , LTS_STATE_t_59 , 6, 'd', LTS_STATE_t_61 , LTS_STATE_t_60 , 3, '#', LTS_STATE_t_12 , LTS_STATE_t_62 , 255, 62, 0,0 , 0,0 , 5, 'a', LTS_STATE_t_64 , LTS_STATE_t_63 , 4, 's', LTS_STATE_t_32 , LTS_STATE_t_65 , 5, 'r', LTS_STATE_t_67 , LTS_STATE_t_66 , 5, 'r', LTS_STATE_t_32 , LTS_STATE_t_68 , 3, 'i', LTS_STATE_t_31 , LTS_STATE_t_32 , 3, 'o', LTS_STATE_t_31 , LTS_STATE_t_69 , 6, 'e', LTS_STATE_t_32 , LTS_STATE_t_31 , 4, 'a', LTS_STATE_t_70 , LTS_STATE_t_31 , 4, 'r', LTS_STATE_t_31 , LTS_STATE_t_71 , 6, '#', LTS_STATE_t_73 , LTS_STATE_t_72 , 6, 'u', LTS_STATE_t_40 , LTS_STATE_t_74 , 5, 'a', LTS_STATE_t_76 , LTS_STATE_t_75 , 3, 'r', LTS_STATE_t_78 , LTS_STATE_t_77 , 3, 'l', LTS_STATE_t_31 , LTS_STATE_t_79 , 6, 'i', LTS_STATE_t_12 , LTS_STATE_t_80 , 3, 'a', LTS_STATE_t_45 , LTS_STATE_t_12 , 3, 'r', LTS_STATE_t_12 , LTS_STATE_t_31 , 6, 'h', LTS_STATE_t_82 , LTS_STATE_t_81 , 4, 'i', LTS_STATE_t_84 , LTS_STATE_t_83 , 6, '0', LTS_STATE_t_31 , LTS_STATE_t_85 , 5, 'a', LTS_STATE_t_22 , LTS_STATE_t_86 , 6, 'e', LTS_STATE_t_22 , LTS_STATE_t_87 , 6, 's', LTS_STATE_t_32 , LTS_STATE_t_88 , 3, 'a', LTS_STATE_t_32 , LTS_STATE_t_31 , 255, 26, 0,0 , 0,0 , 4, 'o', LTS_STATE_t_31 , LTS_STATE_t_32 , 3, 'o', LTS_STATE_t_90 , LTS_STATE_t_89 , 3, 'o', LTS_STATE_t_31 , LTS_STATE_t_32 , 3, 'a', LTS_STATE_t_40 , LTS_STATE_t_31 , 6, 'n', LTS_STATE_t_92 , LTS_STATE_t_91 , 6, 'i', LTS_STATE_t_31 , LTS_STATE_t_12 , 5, 'y', LTS_STATE_t_12 , LTS_STATE_t_93 , 5, 'y', LTS_STATE_t_45 , LTS_STATE_t_12 , 3, 'o', LTS_STATE_t_31 , LTS_STATE_t_94 , 6, 'y', LTS_STATE_t_45 , LTS_STATE_t_95 , 4, 'l', LTS_STATE_t_97 , LTS_STATE_t_96 , 4, 's', LTS_STATE_t_32 , LTS_STATE_t_31 , 4, 'g', LTS_STATE_t_99 , LTS_STATE_t_98 , 3, 's', LTS_STATE_t_101 , LTS_STATE_t_100 , 5, 'd', LTS_STATE_t_31 , LTS_STATE_t_102 , 6, 'a', LTS_STATE_t_104 , LTS_STATE_t_103 , 6, 'a', LTS_STATE_t_22 , LTS_STATE_t_105 , 6, 'n', LTS_STATE_t_32 , LTS_STATE_t_106 , 3, 'u', LTS_STATE_t_31 , LTS_STATE_t_107 , 6, 'n', LTS_STATE_t_32 , LTS_STATE_t_31 , 6, 'l', LTS_STATE_t_109 , LTS_STATE_t_108 , 3, 'r', LTS_STATE_t_45 , LTS_STATE_t_61 , 5, 's', LTS_STATE_t_12 , LTS_STATE_t_110 , 6, 'd', LTS_STATE_t_12 , LTS_STATE_t_111 , 6, 's', LTS_STATE_t_113 , LTS_STATE_t_112 , 5, 'h', LTS_STATE_t_115 , LTS_STATE_t_114 , 3, 's', LTS_STATE_t_116 , LTS_STATE_t_31 , 4, 'r', LTS_STATE_t_31 , LTS_STATE_t_117 , 3, 'r', LTS_STATE_t_32 , LTS_STATE_t_31 , 3, 'n', LTS_STATE_t_119 , LTS_STATE_t_118 , 6, '#', LTS_STATE_t_31 , LTS_STATE_t_22 , 4, 'r', LTS_STATE_t_31 , LTS_STATE_t_120 , 5, 'e', LTS_STATE_t_22 , LTS_STATE_t_121 , 5, 'l', LTS_STATE_t_22 , LTS_STATE_t_122 , 6, 'i', LTS_STATE_t_123 , LTS_STATE_t_31 , 5, '#', LTS_STATE_t_32 , LTS_STATE_t_124 , 6, 'n', LTS_STATE_t_31 , LTS_STATE_t_125 , 3, 'y', LTS_STATE_t_127 , LTS_STATE_t_126 , 5, 'i', LTS_STATE_t_31 , LTS_STATE_t_12 , 3, 'n', LTS_STATE_t_12 , LTS_STATE_t_128 , 6, 'l', LTS_STATE_t_12 , LTS_STATE_t_129 , 3, '#', LTS_STATE_t_12 , LTS_STATE_t_130 , 3, 'o', LTS_STATE_t_45 , LTS_STATE_t_61 , 4, '#', LTS_STATE_t_31 , LTS_STATE_t_131 , 4, 's', LTS_STATE_t_132 , LTS_STATE_t_31 , 5, 'e', LTS_STATE_t_32 , LTS_STATE_t_31 , 3, '#', LTS_STATE_t_133 , LTS_STATE_t_31 , 3, '#', LTS_STATE_t_31 , LTS_STATE_t_40 , 6, 'l', LTS_STATE_t_22 , LTS_STATE_t_134 , 5, 'a', LTS_STATE_t_31 , LTS_STATE_t_135 , 3, 's', LTS_STATE_t_31 , LTS_STATE_t_136 , 3, 'r', LTS_STATE_t_22 , LTS_STATE_t_31 , 3, 'n', LTS_STATE_t_31 , LTS_STATE_t_22 , 6, 'a', LTS_STATE_t_32 , LTS_STATE_t_137 , 3, 'a', LTS_STATE_t_138 , LTS_STATE_t_32 , 6, 's', LTS_STATE_t_139 , LTS_STATE_t_12 , 5, 'm', LTS_STATE_t_45 , LTS_STATE_t_12 , 5, 'a', LTS_STATE_t_12 , LTS_STATE_t_45 , 6, 'n', LTS_STATE_t_12 , LTS_STATE_t_140 , 3, 'o', LTS_STATE_t_141 , LTS_STATE_t_12 , 5, 'n', LTS_STATE_t_143 , LTS_STATE_t_142 , 6, 'a', LTS_STATE_t_22 , LTS_STATE_t_144 , 4, 'e', LTS_STATE_t_31 , LTS_STATE_t_145 , 6, 't', LTS_STATE_t_40 , LTS_STATE_t_146 , 6, 't', LTS_STATE_t_31 , LTS_STATE_t_147 , 6, '#', LTS_STATE_t_31 , LTS_STATE_t_148 , 3, 'a', LTS_STATE_t_150 , LTS_STATE_t_149 , 6, 'o', LTS_STATE_t_32 , LTS_STATE_t_31 , 3, '#', LTS_STATE_t_45 , LTS_STATE_t_12 , 6, 'g', LTS_STATE_t_12 , LTS_STATE_t_151 , 6, 'n', LTS_STATE_t_45 , LTS_STATE_t_12 , 6, 'n', LTS_STATE_t_153 , LTS_STATE_t_152 , 4, 'e', LTS_STATE_t_154 , LTS_STATE_t_31 , 6, 'o', LTS_STATE_t_31 , LTS_STATE_t_22 , 4, 'o', LTS_STATE_t_31 , LTS_STATE_t_155 , 6, '#', LTS_STATE_t_40 , LTS_STATE_t_31 , 4, 'o', LTS_STATE_t_157 , LTS_STATE_t_156 , 3, 'i', LTS_STATE_t_31 , LTS_STATE_t_158 , 6, '#', LTS_STATE_t_32 , LTS_STATE_t_159 , 5, 'n', LTS_STATE_t_31 , LTS_STATE_t_160 , 3, '#', LTS_STATE_t_12 , LTS_STATE_t_161 , 3, 'd', LTS_STATE_t_163 , LTS_STATE_t_162 , 4, 'i', LTS_STATE_t_164 , LTS_STATE_t_31 , 3, 's', LTS_STATE_t_166 , LTS_STATE_t_165 , 4, 'w', LTS_STATE_t_31 , LTS_STATE_t_167 , 5, 's', LTS_STATE_t_31 , LTS_STATE_t_168 , 5, 'm', LTS_STATE_t_31 , LTS_STATE_t_169 , 6, 'e', LTS_STATE_t_170 , LTS_STATE_t_31 , 5, 'k', LTS_STATE_t_32 , LTS_STATE_t_171 , 5, 'y', LTS_STATE_t_32 , LTS_STATE_t_172 , 6, 'u', LTS_STATE_t_31 , LTS_STATE_t_173 , 5, 'u', LTS_STATE_t_174 , LTS_STATE_t_31 , 4, 'k', LTS_STATE_t_32 , LTS_STATE_t_31 , 5, 'e', LTS_STATE_t_74 , LTS_STATE_t_31 , 3, 'f', LTS_STATE_t_32 , LTS_STATE_t_31 , 6, 'i', LTS_STATE_t_32 , LTS_STATE_t_52 , 4, 's', LTS_STATE_t_31 , LTS_STATE_t_32 , 5, 'n', LTS_STATE_t_31 , LTS_STATE_t_175 , 5, 'n', LTS_STATE_t_176 , LTS_STATE_t_32 , 3, 'r', LTS_STATE_t_22 , LTS_STATE_t_177 , 6, 'i', LTS_STATE_t_32 , LTS_STATE_t_178 , 6, 't', LTS_STATE_t_31 , LTS_STATE_t_32 , 3, 'a', LTS_STATE_t_12 , LTS_STATE_t_179 , 4, 'e', LTS_STATE_t_180 , LTS_STATE_t_31 , 5, 'w', LTS_STATE_t_32 , LTS_STATE_t_181 , 6, '#', LTS_STATE_t_32 , LTS_STATE_t_31 , 3, 'a', LTS_STATE_t_22 , LTS_STATE_t_31 , 3, 'r', LTS_STATE_t_31 , LTS_STATE_t_182 , 3, 'r', LTS_STATE_t_12 , LTS_STATE_t_183 , 6, 'r', LTS_STATE_t_184 , LTS_STATE_t_31 , 5, 'g', LTS_STATE_t_31 , LTS_STATE_t_185 , 6, 'k', LTS_STATE_t_31 , LTS_STATE_t_186 , 3, 'e', LTS_STATE_t_12 , LTS_STATE_t_31 , 3, 's', LTS_STATE_t_22 , LTS_STATE_t_31 , 6, 'k', LTS_STATE_t_31 , LTS_STATE_t_187 , 3, 'u', LTS_STATE_t_189 , LTS_STATE_t_188 , 5, 'm', LTS_STATE_t_31 , LTS_STATE_t_190 , 6, 'g', LTS_STATE_t_32 , LTS_STATE_t_191 , 6, 'e', LTS_STATE_t_32 , LTS_STATE_t_116 , 6, 'f', LTS_STATE_t_31 , LTS_STATE_t_192 , 5, 'i', LTS_STATE_t_52 , LTS_STATE_t_193 , 6, 'n', LTS_STATE_t_31 , LTS_STATE_t_194 , 6, 'm', LTS_STATE_t_32 , LTS_STATE_t_195 , 6, 'd', LTS_STATE_t_32 , LTS_STATE_t_196 , 5, 'a', LTS_STATE_t_50 , LTS_STATE_t_197 , 6, 'o', LTS_STATE_t_32 , LTS_STATE_t_198 , 5, 'l', LTS_STATE_t_73 , LTS_STATE_t_199 , 6, 'e', LTS_STATE_t_201 , LTS_STATE_t_200 , 5, 'e', LTS_STATE_t_202 , LTS_STATE_t_32 , 6, 'l', LTS_STATE_t_204 , LTS_STATE_t_203 , 5, 'r', LTS_STATE_t_32 , LTS_STATE_t_31 , 6, 'r', LTS_STATE_t_32 , LTS_STATE_t_205 , 6, 'y', LTS_STATE_t_32 , LTS_STATE_t_206 , 4, 'e', LTS_STATE_t_32 , LTS_STATE_t_31 , 6, 'l', LTS_STATE_t_32 , LTS_STATE_t_31 , 4, 'n', LTS_STATE_t_31 , LTS_STATE_t_207 , 6, 'a', LTS_STATE_t_204 , LTS_STATE_t_208 , 4, 'l', LTS_STATE_t_210 , LTS_STATE_t_209 , 6, 'b', LTS_STATE_t_32 , LTS_STATE_t_211 , 6, 's', LTS_STATE_t_32 , LTS_STATE_t_31 , 5, 'l', LTS_STATE_t_213 , LTS_STATE_t_212 , 6, 's', LTS_STATE_t_215 , LTS_STATE_t_214 , 6, '#', LTS_STATE_t_216 , LTS_STATE_t_210 , 4, 'k', LTS_STATE_t_31 , LTS_STATE_t_217 , 4, 'e', LTS_STATE_t_31 , LTS_STATE_t_32 , 4, 'a', LTS_STATE_t_31 , LTS_STATE_t_32 , 6, 'i', LTS_STATE_t_31 , LTS_STATE_t_218 , 6, 'm', LTS_STATE_t_31 , LTS_STATE_t_219 , 6, '#', LTS_STATE_t_31 , LTS_STATE_t_220 , 4, 'i', LTS_STATE_t_31 , LTS_STATE_t_221 , 6, 'r', LTS_STATE_t_32 , LTS_STATE_t_31 , /** letter u **/ 4, 'r', LTS_STATE_u_2 , LTS_STATE_u_1 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_3 , 5, 'y', LTS_STATE_u_6 , LTS_STATE_u_5 , 3, 'o', LTS_STATE_u_8 , LTS_STATE_u_7 , 255, 0, 0,0 , 0,0 , 5, 'i', LTS_STATE_u_11 , LTS_STATE_u_10 , 3, 'b', LTS_STATE_u_12 , LTS_STATE_u_4 , 3, 'q', LTS_STATE_u_14 , LTS_STATE_u_13 , 4, 'p', LTS_STATE_u_16 , LTS_STATE_u_15 , 5, 'o', LTS_STATE_u_18 , LTS_STATE_u_17 , 3, '#', LTS_STATE_u_20 , LTS_STATE_u_19 , 255, 1, 0,0 , 0,0 , 5, '#', LTS_STATE_u_22 , LTS_STATE_u_21 , 4, 'e', LTS_STATE_u_24 , LTS_STATE_u_23 , 4, 'i', LTS_STATE_u_26 , LTS_STATE_u_25 , 5, 'l', LTS_STATE_u_28 , LTS_STATE_u_27 , 5, 'a', LTS_STATE_u_30 , LTS_STATE_u_29 , 3, 'e', LTS_STATE_u_32 , LTS_STATE_u_31 , 3, 'p', LTS_STATE_u_34 , LTS_STATE_u_33 , 6, 'n', LTS_STATE_u_36 , LTS_STATE_u_35 , 5, 'e', LTS_STATE_u_38 , LTS_STATE_u_37 , 4, 'e', LTS_STATE_u_40 , LTS_STATE_u_39 , 5, 'a', LTS_STATE_u_42 , LTS_STATE_u_41 , 5, '#', LTS_STATE_u_4 , LTS_STATE_u_43 , 4, 's', LTS_STATE_u_45 , LTS_STATE_u_44 , 5, 's', LTS_STATE_u_46 , LTS_STATE_u_42 , 255, 33, 0,0 , 0,0 , 255, 50, 0,0 , 0,0 , 5, 'e', LTS_STATE_u_48 , LTS_STATE_u_47 , 6, '#', LTS_STATE_u_50 , LTS_STATE_u_49 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_51 , 6, 'p', LTS_STATE_u_34 , LTS_STATE_u_52 , 3, 'c', LTS_STATE_u_34 , LTS_STATE_u_53 , 255, 63, 0,0 , 0,0 , 255, 64, 0,0 , 0,0 , 255, 65, 0,0 , 0,0 , 5, 'i', LTS_STATE_u_55 , LTS_STATE_u_54 , 4, 's', LTS_STATE_u_57 , LTS_STATE_u_56 , 4, 'a', LTS_STATE_u_59 , LTS_STATE_u_58 , 3, 'g', LTS_STATE_u_4 , LTS_STATE_u_60 , 6, '#', LTS_STATE_u_62 , LTS_STATE_u_61 , 255, 53, 0,0 , 0,0 , 6, '#', LTS_STATE_u_64 , LTS_STATE_u_63 , 4, 'n', LTS_STATE_u_66 , LTS_STATE_u_65 , 5, 's', LTS_STATE_u_27 , LTS_STATE_u_67 , 255, 36, 0,0 , 0,0 , 5, 'r', LTS_STATE_u_69 , LTS_STATE_u_68 , 3, 't', LTS_STATE_u_4 , LTS_STATE_u_70 , 3, 't', LTS_STATE_u_4 , LTS_STATE_u_71 , 255, 51, 0,0 , 0,0 , 6, '#', LTS_STATE_u_50 , LTS_STATE_u_72 , 6, 'l', LTS_STATE_u_74 , LTS_STATE_u_73 , 3, 'f', LTS_STATE_u_34 , LTS_STATE_u_75 , 5, 'a', LTS_STATE_u_77 , LTS_STATE_u_76 , 3, '#', LTS_STATE_u_79 , LTS_STATE_u_78 , 3, '#', LTS_STATE_u_81 , LTS_STATE_u_80 , 6, 's', LTS_STATE_u_83 , LTS_STATE_u_82 , 4, 's', LTS_STATE_u_85 , LTS_STATE_u_84 , 3, 'g', LTS_STATE_u_42 , LTS_STATE_u_86 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_87 , 4, 'a', LTS_STATE_u_42 , LTS_STATE_u_88 , 5, 'l', LTS_STATE_u_42 , LTS_STATE_u_89 , 5, 't', LTS_STATE_u_4 , LTS_STATE_u_90 , 5, 'z', LTS_STATE_u_42 , LTS_STATE_u_4 , 4, 't', LTS_STATE_u_92 , LTS_STATE_u_91 , 5, 'g', LTS_STATE_u_94 , LTS_STATE_u_93 , 5, '#', LTS_STATE_u_4 , LTS_STATE_u_95 , 5, 'u', LTS_STATE_u_96 , LTS_STATE_u_4 , 3, 'd', LTS_STATE_u_97 , LTS_STATE_u_4 , 3, 's', LTS_STATE_u_99 , LTS_STATE_u_98 , 3, 'c', LTS_STATE_u_101 , LTS_STATE_u_100 , 6, 'n', LTS_STATE_u_27 , LTS_STATE_u_4 , 6, 's', LTS_STATE_u_50 , LTS_STATE_u_102 , 255, 52, 0,0 , 0,0 , 3, 'b', LTS_STATE_u_12 , LTS_STATE_u_103 , 4, 'e', LTS_STATE_u_105 , LTS_STATE_u_104 , 4, 'l', LTS_STATE_u_107 , LTS_STATE_u_106 , 3, 'm', LTS_STATE_u_109 , LTS_STATE_u_108 , 6, 'n', LTS_STATE_u_28 , LTS_STATE_u_110 , 3, 'r', LTS_STATE_u_112 , LTS_STATE_u_111 , 4, 'n', LTS_STATE_u_114 , LTS_STATE_u_113 , 3, 'e', LTS_STATE_u_116 , LTS_STATE_u_115 , 3, 'r', LTS_STATE_u_85 , LTS_STATE_u_117 , 4, 'm', LTS_STATE_u_85 , LTS_STATE_u_118 , 255, 5, 0,0 , 0,0 , 3, 'h', LTS_STATE_u_46 , LTS_STATE_u_27 , 3, 's', LTS_STATE_u_46 , LTS_STATE_u_119 , 4, 'i', LTS_STATE_u_42 , LTS_STATE_u_120 , 5, 'd', LTS_STATE_u_42 , LTS_STATE_u_121 , 5, 'u', LTS_STATE_u_4 , LTS_STATE_u_122 , 5, 'h', LTS_STATE_u_124 , LTS_STATE_u_123 , 6, 'e', LTS_STATE_u_126 , LTS_STATE_u_125 , 6, 'r', LTS_STATE_u_28 , LTS_STATE_u_4 , 6, 'e', LTS_STATE_u_4 , LTS_STATE_u_28 , 5, 't', LTS_STATE_u_127 , LTS_STATE_u_4 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_50 , 255, 7, 0,0 , 0,0 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_128 , 6, '#', LTS_STATE_u_4 , LTS_STATE_u_129 , 3, 'g', LTS_STATE_u_35 , LTS_STATE_u_130 , 6, 't', LTS_STATE_u_34 , LTS_STATE_u_35 , 255, 30, 0,0 , 0,0 , 3, 'g', LTS_STATE_u_34 , LTS_STATE_u_131 , 4, 'a', LTS_STATE_u_133 , LTS_STATE_u_132 , 3, 'g', LTS_STATE_u_4 , LTS_STATE_u_134 , 3, '#', LTS_STATE_u_136 , LTS_STATE_u_135 , 6, 't', LTS_STATE_u_138 , LTS_STATE_u_137 , 3, 'c', LTS_STATE_u_140 , LTS_STATE_u_139 , 4, 'n', LTS_STATE_u_142 , LTS_STATE_u_141 , 6, 'm', LTS_STATE_u_28 , LTS_STATE_u_143 , 3, 's', LTS_STATE_u_145 , LTS_STATE_u_144 , 4, 'm', LTS_STATE_u_147 , LTS_STATE_u_146 , 4, 't', LTS_STATE_u_102 , LTS_STATE_u_85 , 6, 'a', LTS_STATE_u_85 , LTS_STATE_u_148 , 3, 'm', LTS_STATE_u_102 , LTS_STATE_u_149 , 6, 'r', LTS_STATE_u_4 , LTS_STATE_u_102 , 3, 'b', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 'f', LTS_STATE_u_85 , LTS_STATE_u_150 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_151 , 4, 'o', LTS_STATE_u_42 , LTS_STATE_u_27 , 5, 't', LTS_STATE_u_42 , LTS_STATE_u_152 , 5, 'r', LTS_STATE_u_4 , LTS_STATE_u_153 , 5, 'l', LTS_STATE_u_155 , LTS_STATE_u_154 , 4, 'g', LTS_STATE_u_4 , LTS_STATE_u_156 , 5, 'e', LTS_STATE_u_158 , LTS_STATE_u_157 , 5, 'h', LTS_STATE_u_28 , LTS_STATE_u_4 , 6, '#', LTS_STATE_u_4 , LTS_STATE_u_159 , 3, 'g', LTS_STATE_u_35 , LTS_STATE_u_160 , 6, 'r', LTS_STATE_u_50 , LTS_STATE_u_161 , 3, 'o', LTS_STATE_u_4 , LTS_STATE_u_162 , 3, 'm', LTS_STATE_u_34 , LTS_STATE_u_163 , 4, 'i', LTS_STATE_u_165 , LTS_STATE_u_164 , 3, 'g', LTS_STATE_u_167 , LTS_STATE_u_166 , 3, 'r', LTS_STATE_u_169 , LTS_STATE_u_168 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_170 , 4, 'n', LTS_STATE_u_171 , LTS_STATE_u_102 , 6, 'r', LTS_STATE_u_173 , LTS_STATE_u_172 , 3, 't', LTS_STATE_u_85 , LTS_STATE_u_174 , 3, 'b', LTS_STATE_u_176 , LTS_STATE_u_175 , 4, 's', LTS_STATE_u_178 , LTS_STATE_u_177 , 6, 'o', LTS_STATE_u_27 , LTS_STATE_u_102 , 6, 'c', LTS_STATE_u_102 , LTS_STATE_u_179 , 4, 'n', LTS_STATE_u_102 , LTS_STATE_u_180 , 3, 'l', LTS_STATE_u_182 , LTS_STATE_u_181 , 4, 'l', LTS_STATE_u_85 , LTS_STATE_u_27 , 6, 't', LTS_STATE_u_46 , LTS_STATE_u_183 , 6, 'n', LTS_STATE_u_85 , LTS_STATE_u_27 , 6, 'x', LTS_STATE_u_28 , LTS_STATE_u_184 , 3, 'f', LTS_STATE_u_102 , LTS_STATE_u_185 , 3, 'e', LTS_STATE_u_187 , LTS_STATE_u_186 , 3, 'n', LTS_STATE_u_189 , LTS_STATE_u_188 , 5, 'n', LTS_STATE_u_42 , LTS_STATE_u_190 , 6, 'y', LTS_STATE_u_4 , LTS_STATE_u_42 , 4, 'x', LTS_STATE_u_27 , LTS_STATE_u_191 , 4, 'b', LTS_STATE_u_28 , LTS_STATE_u_192 , 6, 'a', LTS_STATE_u_28 , LTS_STATE_u_193 , 5, 'a', LTS_STATE_u_46 , LTS_STATE_u_4 , 6, 'd', LTS_STATE_u_4 , LTS_STATE_u_194 , 6, 'i', LTS_STATE_u_27 , LTS_STATE_u_4 , 3, 'o', LTS_STATE_u_4 , LTS_STATE_u_195 , 6, 's', LTS_STATE_u_4 , LTS_STATE_u_196 , 3, 'm', LTS_STATE_u_4 , LTS_STATE_u_197 , 3, 'd', LTS_STATE_u_50 , LTS_STATE_u_198 , 3, '#', LTS_STATE_u_200 , LTS_STATE_u_199 , 3, 'g', LTS_STATE_u_202 , LTS_STATE_u_201 , 5, 't', LTS_STATE_u_204 , LTS_STATE_u_203 , 5, 'r', LTS_STATE_u_4 , LTS_STATE_u_205 , 6, '#', LTS_STATE_u_207 , LTS_STATE_u_206 , 5, 'n', LTS_STATE_u_50 , LTS_STATE_u_27 , 6, 't', LTS_STATE_u_209 , LTS_STATE_u_208 , 6, 'b', LTS_STATE_u_102 , LTS_STATE_u_210 , 3, 't', LTS_STATE_u_27 , LTS_STATE_u_211 , 3, 'c', LTS_STATE_u_213 , LTS_STATE_u_212 , 3, 's', LTS_STATE_u_85 , LTS_STATE_u_214 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_215 , 4, 's', LTS_STATE_u_217 , LTS_STATE_u_216 , 6, 'e', LTS_STATE_u_213 , LTS_STATE_u_218 , 6, 'n', LTS_STATE_u_102 , LTS_STATE_u_27 , 6, 'z', LTS_STATE_u_213 , LTS_STATE_u_219 , 4, 't', LTS_STATE_u_102 , LTS_STATE_u_46 , 3, 't', LTS_STATE_u_221 , LTS_STATE_u_220 , 6, 'n', LTS_STATE_u_222 , LTS_STATE_u_27 , 6, 'l', LTS_STATE_u_27 , LTS_STATE_u_223 , 6, 'm', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 'b', LTS_STATE_u_102 , LTS_STATE_u_224 , 4, 'i', LTS_STATE_u_27 , LTS_STATE_u_225 , 4, 'x', LTS_STATE_u_4 , LTS_STATE_u_226 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_227 , 255, 35, 0,0 , 0,0 , 4, 'i', LTS_STATE_u_42 , LTS_STATE_u_4 , 4, 'e', LTS_STATE_u_229 , LTS_STATE_u_228 , 4, 'e', LTS_STATE_u_46 , LTS_STATE_u_4 , 6, 'e', LTS_STATE_u_4 , LTS_STATE_u_230 , 6, 'r', LTS_STATE_u_4 , LTS_STATE_u_27 , 3, 'b', LTS_STATE_u_232 , LTS_STATE_u_231 , 6, 'd', LTS_STATE_u_50 , LTS_STATE_u_4 , 3, '#', LTS_STATE_u_34 , LTS_STATE_u_233 , 3, 'k', LTS_STATE_u_4 , LTS_STATE_u_234 , 5, 'o', LTS_STATE_u_236 , LTS_STATE_u_235 , 4, 'n', LTS_STATE_u_238 , LTS_STATE_u_237 , 3, 'b', LTS_STATE_u_4 , LTS_STATE_u_239 , 6, 'h', LTS_STATE_u_42 , LTS_STATE_u_240 , 5, 'l', LTS_STATE_u_242 , LTS_STATE_u_241 , 3, 't', LTS_STATE_u_46 , LTS_STATE_u_243 , 6, 'a', LTS_STATE_u_42 , LTS_STATE_u_244 , 3, 'l', LTS_STATE_u_246 , LTS_STATE_u_245 , 3, 's', LTS_STATE_u_27 , LTS_STATE_u_247 , 3, 'h', LTS_STATE_u_249 , LTS_STATE_u_248 , 4, 't', LTS_STATE_u_251 , LTS_STATE_u_250 , 6, 'n', LTS_STATE_u_28 , LTS_STATE_u_252 , 3, 'c', LTS_STATE_u_213 , LTS_STATE_u_253 , 3, 'g', LTS_STATE_u_213 , LTS_STATE_u_254 , 255, 66, 0,0 , 0,0 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_213 , 3, 'p', LTS_STATE_u_256 , LTS_STATE_u_255 , 6, 'o', LTS_STATE_u_102 , LTS_STATE_u_257 , 255, 12, 0,0 , 0,0 , 6, 'v', LTS_STATE_u_213 , LTS_STATE_u_258 , 6, 's', LTS_STATE_u_213 , LTS_STATE_u_102 , 3, 'd', LTS_STATE_u_260 , LTS_STATE_u_259 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_261 , 4, 'm', LTS_STATE_u_28 , LTS_STATE_u_27 , 6, 'n', LTS_STATE_u_262 , LTS_STATE_u_27 , 3, '#', LTS_STATE_u_102 , LTS_STATE_u_263 , 4, 'y', LTS_STATE_u_4 , LTS_STATE_u_264 , 4, 'p', LTS_STATE_u_28 , LTS_STATE_u_46 , 3, 'c', LTS_STATE_u_189 , LTS_STATE_u_102 , 5, 't', LTS_STATE_u_4 , LTS_STATE_u_265 , 6, 't', LTS_STATE_u_46 , LTS_STATE_u_27 , 6, 'i', LTS_STATE_u_4 , LTS_STATE_u_266 , 3, 'c', LTS_STATE_u_268 , LTS_STATE_u_267 , 6, 'a', LTS_STATE_u_34 , LTS_STATE_u_12 , 6, 's', LTS_STATE_u_50 , LTS_STATE_u_269 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_270 , 4, '#', LTS_STATE_u_272 , LTS_STATE_u_271 , 6, '#', LTS_STATE_u_274 , LTS_STATE_u_273 , 4, 'p', LTS_STATE_u_276 , LTS_STATE_u_275 , 5, 'd', LTS_STATE_u_278 , LTS_STATE_u_277 , 3, 'c', LTS_STATE_u_280 , LTS_STATE_u_279 , 5, 't', LTS_STATE_u_4 , LTS_STATE_u_281 , 3, 't', LTS_STATE_u_283 , LTS_STATE_u_282 , 3, 'n', LTS_STATE_u_189 , LTS_STATE_u_284 , 3, 'd', LTS_STATE_u_286 , LTS_STATE_u_285 , 5, 'n', LTS_STATE_u_42 , LTS_STATE_u_287 , 3, 'b', LTS_STATE_u_289 , LTS_STATE_u_288 , 5, 'n', LTS_STATE_u_46 , LTS_STATE_u_290 , 3, 'n', LTS_STATE_u_292 , LTS_STATE_u_291 , 3, 's', LTS_STATE_u_294 , LTS_STATE_u_293 , 4, 'm', LTS_STATE_u_102 , LTS_STATE_u_27 , 3, 'c', LTS_STATE_u_213 , LTS_STATE_u_295 , 3, 'p', LTS_STATE_u_213 , LTS_STATE_u_189 , 6, 'l', LTS_STATE_u_85 , LTS_STATE_u_28 , 3, 'm', LTS_STATE_u_213 , LTS_STATE_u_296 , 3, 'p', LTS_STATE_u_213 , LTS_STATE_u_85 , 3, 'f', LTS_STATE_u_298 , LTS_STATE_u_297 , 6, 's', LTS_STATE_u_28 , LTS_STATE_u_102 , 4, 't', LTS_STATE_u_189 , LTS_STATE_u_178 , 6, 'n', LTS_STATE_u_213 , LTS_STATE_u_102 , 3, 'e', LTS_STATE_u_300 , LTS_STATE_u_299 , 4, 'l', LTS_STATE_u_46 , LTS_STATE_u_27 , 4, 't', LTS_STATE_u_27 , LTS_STATE_u_301 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_302 , 3, 'c', LTS_STATE_u_102 , LTS_STATE_u_303 , 4, 'z', LTS_STATE_u_46 , LTS_STATE_u_304 , 4, '#', LTS_STATE_u_27 , LTS_STATE_u_305 , 6, '#', LTS_STATE_u_4 , LTS_STATE_u_28 , 3, 'p', LTS_STATE_u_34 , LTS_STATE_u_306 , 6, '#', LTS_STATE_u_35 , LTS_STATE_u_34 , 3, 'a', LTS_STATE_u_4 , LTS_STATE_u_307 , 3, 'o', LTS_STATE_u_4 , LTS_STATE_u_308 , 4, 'o', LTS_STATE_u_310 , LTS_STATE_u_309 , 3, 'c', LTS_STATE_u_189 , LTS_STATE_u_311 , 6, 'u', LTS_STATE_u_313 , LTS_STATE_u_312 , 3, 'c', LTS_STATE_u_102 , LTS_STATE_u_27 , 5, 'u', LTS_STATE_u_102 , LTS_STATE_u_314 , 5, 'h', LTS_STATE_u_85 , LTS_STATE_u_315 , 5, 'o', LTS_STATE_u_28 , LTS_STATE_u_316 , 6, 'o', LTS_STATE_u_85 , LTS_STATE_u_317 , 5, 'n', LTS_STATE_u_319 , LTS_STATE_u_318 , 5, 's', LTS_STATE_u_42 , LTS_STATE_u_4 , 6, 'g', LTS_STATE_u_4 , LTS_STATE_u_320 , 3, 'n', LTS_STATE_u_27 , LTS_STATE_u_321 , 6, 'y', LTS_STATE_u_46 , LTS_STATE_u_322 , 3, 'd', LTS_STATE_u_46 , LTS_STATE_u_323 , 3, 'l', LTS_STATE_u_189 , LTS_STATE_u_324 , 255, 67, 0,0 , 0,0 , 6, '#', LTS_STATE_u_4 , LTS_STATE_u_42 , 3, 'm', LTS_STATE_u_326 , LTS_STATE_u_325 , 5, 'n', LTS_STATE_u_42 , LTS_STATE_u_102 , 6, 'e', LTS_STATE_u_50 , LTS_STATE_u_27 , 3, 'l', LTS_STATE_u_328 , LTS_STATE_u_327 , 5, 'l', LTS_STATE_u_74 , LTS_STATE_u_189 , 3, 'g', LTS_STATE_u_330 , LTS_STATE_u_329 , 6, 'r', LTS_STATE_u_50 , LTS_STATE_u_331 , 4, 'm', LTS_STATE_u_27 , LTS_STATE_u_332 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_333 , 3, 'h', LTS_STATE_u_335 , LTS_STATE_u_334 , 4, 'j', LTS_STATE_u_27 , LTS_STATE_u_102 , 4, 'y', LTS_STATE_u_4 , LTS_STATE_u_336 , 4, 'g', LTS_STATE_u_189 , LTS_STATE_u_337 , 4, 'n', LTS_STATE_u_338 , LTS_STATE_u_27 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_85 , 6, 'n', LTS_STATE_u_27 , LTS_STATE_u_339 , 4, 'l', LTS_STATE_u_85 , LTS_STATE_u_340 , 4, 'v', LTS_STATE_u_342 , LTS_STATE_u_341 , 3, '#', LTS_STATE_u_36 , LTS_STATE_u_343 , 6, 'l', LTS_STATE_u_4 , LTS_STATE_u_344 , 3, 'e', LTS_STATE_u_4 , LTS_STATE_u_345 , 3, 'e', LTS_STATE_u_347 , LTS_STATE_u_346 , 5, 'u', LTS_STATE_u_349 , LTS_STATE_u_348 , 3, 'e', LTS_STATE_u_27 , LTS_STATE_u_350 , 3, 'c', LTS_STATE_u_352 , LTS_STATE_u_351 , 4, 'l', LTS_STATE_u_213 , LTS_STATE_u_28 , 4, 'h', LTS_STATE_u_354 , LTS_STATE_u_353 , 5, 'd', LTS_STATE_u_85 , LTS_STATE_u_355 , 6, 'o', LTS_STATE_u_357 , LTS_STATE_u_356 , 6, 'e', LTS_STATE_u_28 , LTS_STATE_u_358 , 3, 'm', LTS_STATE_u_27 , LTS_STATE_u_359 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_360 , 6, 'd', LTS_STATE_u_4 , LTS_STATE_u_361 , 5, 'n', LTS_STATE_u_363 , LTS_STATE_u_362 , 6, 'i', LTS_STATE_u_46 , LTS_STATE_u_27 , 3, 't', LTS_STATE_u_365 , LTS_STATE_u_364 , 3, 'n', LTS_STATE_u_189 , LTS_STATE_u_213 , 3, 'f', LTS_STATE_u_367 , LTS_STATE_u_366 , 5, 'l', LTS_STATE_u_189 , LTS_STATE_u_102 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_368 , 5, 'd', LTS_STATE_u_189 , LTS_STATE_u_27 , 3, 'n', LTS_STATE_u_370 , LTS_STATE_u_369 , 6, 'n', LTS_STATE_u_4 , LTS_STATE_u_85 , 6, 'n', LTS_STATE_u_46 , LTS_STATE_u_27 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_371 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_27 , 3, 'k', LTS_STATE_u_373 , LTS_STATE_u_372 , 4, 'm', LTS_STATE_u_189 , LTS_STATE_u_374 , 6, 'n', LTS_STATE_u_376 , LTS_STATE_u_375 , 6, 'r', LTS_STATE_u_378 , LTS_STATE_u_377 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_85 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_379 , 4, 'h', LTS_STATE_u_46 , LTS_STATE_u_380 , 5, 'a', LTS_STATE_u_382 , LTS_STATE_u_381 , 5, 'i', LTS_STATE_u_46 , LTS_STATE_u_27 , 6, 'k', LTS_STATE_u_50 , LTS_STATE_u_383 , 6, 'n', LTS_STATE_u_385 , LTS_STATE_u_384 , 6, 'n', LTS_STATE_u_387 , LTS_STATE_u_386 , 5, 'u', LTS_STATE_u_389 , LTS_STATE_u_388 , 4, 'p', LTS_STATE_u_28 , LTS_STATE_u_390 , 5, 'r', LTS_STATE_u_4 , LTS_STATE_u_391 , 3, 'n', LTS_STATE_u_189 , LTS_STATE_u_392 , 3, 'g', LTS_STATE_u_46 , LTS_STATE_u_393 , 3, 'b', LTS_STATE_u_395 , LTS_STATE_u_394 , 4, 't', LTS_STATE_u_213 , LTS_STATE_u_27 , 4, 'm', LTS_STATE_u_28 , LTS_STATE_u_396 , 6, 'i', LTS_STATE_u_50 , LTS_STATE_u_27 , 5, 'p', LTS_STATE_u_28 , LTS_STATE_u_397 , 5, 'u', LTS_STATE_u_85 , LTS_STATE_u_398 , 5, 'c', LTS_STATE_u_28 , LTS_STATE_u_85 , 6, 'i', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 's', LTS_STATE_u_27 , LTS_STATE_u_399 , 6, 'g', LTS_STATE_u_27 , LTS_STATE_u_213 , 6, 'e', LTS_STATE_u_4 , LTS_STATE_u_400 , 3, 's', LTS_STATE_u_42 , LTS_STATE_u_401 , 3, 'h', LTS_STATE_u_42 , LTS_STATE_u_402 , 3, 's', LTS_STATE_u_286 , LTS_STATE_u_403 , 6, 'i', LTS_STATE_u_286 , LTS_STATE_u_46 , 5, 'r', LTS_STATE_u_405 , LTS_STATE_u_404 , 5, 'l', LTS_STATE_u_102 , LTS_STATE_u_42 , 5, 'r', LTS_STATE_u_4 , LTS_STATE_u_406 , 3, 'c', LTS_STATE_u_258 , LTS_STATE_u_407 , 4, 'f', LTS_STATE_u_213 , LTS_STATE_u_27 , 4, 'g', LTS_STATE_u_85 , LTS_STATE_u_408 , 3, 'g', LTS_STATE_u_46 , LTS_STATE_u_409 , 6, 'c', LTS_STATE_u_102 , LTS_STATE_u_410 , 6, 'a', LTS_STATE_u_27 , LTS_STATE_u_411 , 3, 'n', LTS_STATE_u_413 , LTS_STATE_u_412 , 4, 'm', LTS_STATE_u_213 , LTS_STATE_u_414 , 6, '#', LTS_STATE_u_28 , LTS_STATE_u_415 , 4, 'v', LTS_STATE_u_27 , LTS_STATE_u_416 , 6, '#', LTS_STATE_u_102 , LTS_STATE_u_27 , 4, 'k', LTS_STATE_u_85 , LTS_STATE_u_417 , 4, 'a', LTS_STATE_u_46 , LTS_STATE_u_418 , 4, 'g', LTS_STATE_u_27 , LTS_STATE_u_419 , 3, 'l', LTS_STATE_u_50 , LTS_STATE_u_420 , 3, 'd', LTS_STATE_u_50 , LTS_STATE_u_4 , 3, 'd', LTS_STATE_u_4 , LTS_STATE_u_421 , 6, 'z', LTS_STATE_u_4 , LTS_STATE_u_422 , 3, 't', LTS_STATE_u_4 , LTS_STATE_u_423 , 3, 's', LTS_STATE_u_425 , LTS_STATE_u_424 , 3, 'c', LTS_STATE_u_427 , LTS_STATE_u_426 , 5, 'r', LTS_STATE_u_27 , LTS_STATE_u_428 , 6, '#', LTS_STATE_u_4 , LTS_STATE_u_429 , 3, 'c', LTS_STATE_u_189 , LTS_STATE_u_430 , 3, 'n', LTS_STATE_u_46 , LTS_STATE_u_431 , 3, 'm', LTS_STATE_u_189 , LTS_STATE_u_432 , 4, 't', LTS_STATE_u_213 , LTS_STATE_u_102 , 5, 't', LTS_STATE_u_28 , LTS_STATE_u_433 , 6, 'i', LTS_STATE_u_28 , LTS_STATE_u_434 , 5, 'w', LTS_STATE_u_85 , LTS_STATE_u_435 , 6, '#', LTS_STATE_u_437 , LTS_STATE_u_436 , 5, 'l', LTS_STATE_u_4 , LTS_STATE_u_438 , 5, 'd', LTS_STATE_u_42 , LTS_STATE_u_439 , 3, 'j', LTS_STATE_u_42 , LTS_STATE_u_46 , 3, 'x', LTS_STATE_u_286 , LTS_STATE_u_46 , 6, 'a', LTS_STATE_u_42 , LTS_STATE_u_440 , 3, 'e', LTS_STATE_u_4 , LTS_STATE_u_441 , 3, 'c', LTS_STATE_u_102 , LTS_STATE_u_442 , 4, 't', LTS_STATE_u_444 , LTS_STATE_u_443 , 3, 't', LTS_STATE_u_85 , LTS_STATE_u_445 , 6, 'e', LTS_STATE_u_447 , LTS_STATE_u_446 , 4, 'l', LTS_STATE_u_189 , LTS_STATE_u_147 , 4, 'l', LTS_STATE_u_102 , LTS_STATE_u_27 , 3, 'j', LTS_STATE_u_27 , LTS_STATE_u_448 , 4, 't', LTS_STATE_u_85 , LTS_STATE_u_27 , 4, 'l', LTS_STATE_u_213 , LTS_STATE_u_449 , 6, 'n', LTS_STATE_u_4 , LTS_STATE_u_27 , 4, 't', LTS_STATE_u_27 , LTS_STATE_u_450 , 3, 'n', LTS_STATE_u_28 , LTS_STATE_u_451 , 6, 'u', LTS_STATE_u_4 , LTS_STATE_u_452 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_260 , 6, 't', LTS_STATE_u_4 , LTS_STATE_u_453 , 3, 's', LTS_STATE_u_50 , LTS_STATE_u_102 , 3, 'j', LTS_STATE_u_50 , LTS_STATE_u_454 , 3, 's', LTS_STATE_u_50 , LTS_STATE_u_4 , 4, 'l', LTS_STATE_u_456 , LTS_STATE_u_455 , 5, 'r', LTS_STATE_u_458 , LTS_STATE_u_457 , 4, 't', LTS_STATE_u_460 , LTS_STATE_u_459 , 4, 'm', LTS_STATE_u_102 , LTS_STATE_u_213 , 6, 'a', LTS_STATE_u_189 , LTS_STATE_u_461 , 5, 'y', LTS_STATE_u_4 , LTS_STATE_u_462 , 3, 't', LTS_STATE_u_85 , LTS_STATE_u_46 , 3, 'l', LTS_STATE_u_46 , LTS_STATE_u_463 , 4, 'b', LTS_STATE_u_465 , LTS_STATE_u_464 , 5, 'o', LTS_STATE_u_189 , LTS_STATE_u_466 , 6, 'a', LTS_STATE_u_28 , LTS_STATE_u_467 , 6, 'a', LTS_STATE_u_85 , LTS_STATE_u_468 , 5, 'd', LTS_STATE_u_46 , LTS_STATE_u_469 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_46 , 6, 't', LTS_STATE_u_42 , LTS_STATE_u_470 , 5, 'r', LTS_STATE_u_42 , LTS_STATE_u_27 , 3, 'k', LTS_STATE_u_50 , LTS_STATE_u_471 , 3, 'h', LTS_STATE_u_4 , LTS_STATE_u_50 , 5, 'l', LTS_STATE_u_27 , LTS_STATE_u_102 , 6, 'm', LTS_STATE_u_27 , LTS_STATE_u_472 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_473 , 4, 'n', LTS_STATE_u_46 , LTS_STATE_u_27 , 3, 'e', LTS_STATE_u_475 , LTS_STATE_u_474 , 4, 'l', LTS_STATE_u_27 , LTS_STATE_u_476 , 3, 'h', LTS_STATE_u_478 , LTS_STATE_u_477 , 3, 'j', LTS_STATE_u_27 , LTS_STATE_u_102 , 4, 'b', LTS_STATE_u_4 , LTS_STATE_u_27 , 4, 'g', LTS_STATE_u_28 , LTS_STATE_u_479 , 6, 'r', LTS_STATE_u_4 , LTS_STATE_u_480 , 3, 'j', LTS_STATE_u_4 , LTS_STATE_u_481 , 6, 's', LTS_STATE_u_4 , LTS_STATE_u_482 , 5, 'h', LTS_STATE_u_484 , LTS_STATE_u_483 , 3, 'f', LTS_STATE_u_486 , LTS_STATE_u_485 , 4, 'b', LTS_STATE_u_488 , LTS_STATE_u_487 , 6, 'e', LTS_STATE_u_46 , LTS_STATE_u_489 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_490 , 3, 'm', LTS_STATE_u_102 , LTS_STATE_u_491 , 6, 'c', LTS_STATE_u_4 , LTS_STATE_u_492 , 3, 'b', LTS_STATE_u_42 , LTS_STATE_u_493 , 3, 'r', LTS_STATE_u_46 , LTS_STATE_u_494 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_495 , 3, 's', LTS_STATE_u_85 , LTS_STATE_u_496 , 4, 'z', LTS_STATE_u_46 , LTS_STATE_u_28 , 5, 't', LTS_STATE_u_28 , LTS_STATE_u_497 , 5, 'f', LTS_STATE_u_85 , LTS_STATE_u_498 , 3, 'h', LTS_STATE_u_4 , LTS_STATE_u_499 , 6, 'i', LTS_STATE_u_4 , LTS_STATE_u_500 , 3, 'h', LTS_STATE_u_502 , LTS_STATE_u_501 , 3, 'e', LTS_STATE_u_504 , LTS_STATE_u_503 , 3, 'l', LTS_STATE_u_46 , LTS_STATE_u_505 , 3, 'n', LTS_STATE_u_27 , LTS_STATE_u_506 , 6, 'c', LTS_STATE_u_102 , LTS_STATE_u_27 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_28 , 4, 't', LTS_STATE_u_508 , LTS_STATE_u_507 , 4, 'l', LTS_STATE_u_27 , LTS_STATE_u_509 , 4, 'p', LTS_STATE_u_511 , LTS_STATE_u_510 , 6, 't', LTS_STATE_u_46 , LTS_STATE_u_512 , 3, 'e', LTS_STATE_u_4 , LTS_STATE_u_513 , 3, 't', LTS_STATE_u_50 , LTS_STATE_u_514 , 6, '#', LTS_STATE_u_516 , LTS_STATE_u_515 , 4, 's', LTS_STATE_u_518 , LTS_STATE_u_517 , 3, 'b', LTS_STATE_u_520 , LTS_STATE_u_519 , 6, 'y', LTS_STATE_u_85 , LTS_STATE_u_521 , 5, 'p', LTS_STATE_u_523 , LTS_STATE_u_522 , 6, 'c', LTS_STATE_u_85 , LTS_STATE_u_524 , 6, 'a', LTS_STATE_u_27 , LTS_STATE_u_28 , 4, 'k', LTS_STATE_u_46 , LTS_STATE_u_525 , 6, 'r', LTS_STATE_u_102 , LTS_STATE_u_27 , 6, 'i', LTS_STATE_u_27 , LTS_STATE_u_526 , 5, 'm', LTS_STATE_u_42 , LTS_STATE_u_527 , 3, 'k', LTS_STATE_u_27 , LTS_STATE_u_528 , 3, 'h', LTS_STATE_u_249 , LTS_STATE_u_529 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_28 , 6, 'r', LTS_STATE_u_85 , LTS_STATE_u_530 , 5, 'l', LTS_STATE_u_85 , LTS_STATE_u_531 , 3, 'd', LTS_STATE_u_46 , LTS_STATE_u_27 , 6, 'n', LTS_STATE_u_4 , LTS_STATE_u_532 , 3, '#', LTS_STATE_u_50 , LTS_STATE_u_533 , 5, 't', LTS_STATE_u_27 , LTS_STATE_u_534 , 6, 's', LTS_STATE_u_536 , LTS_STATE_u_535 , 6, 'l', LTS_STATE_u_102 , LTS_STATE_u_27 , 3, 'b', LTS_STATE_u_213 , LTS_STATE_u_537 , 6, 'o', LTS_STATE_u_27 , LTS_STATE_u_538 , 3, 'm', LTS_STATE_u_540 , LTS_STATE_u_539 , 3, 'b', LTS_STATE_u_189 , LTS_STATE_u_102 , 4, 't', LTS_STATE_u_27 , LTS_STATE_u_541 , 3, 'm', LTS_STATE_u_85 , LTS_STATE_u_542 , 3, 'r', LTS_STATE_u_85 , LTS_STATE_u_543 , 5, 'i', LTS_STATE_u_545 , LTS_STATE_u_544 , 3, 'n', LTS_STATE_u_35 , LTS_STATE_u_546 , 6, 'a', LTS_STATE_u_50 , LTS_STATE_u_547 , 4, 'y', LTS_STATE_u_4 , LTS_STATE_u_548 , 5, 'y', LTS_STATE_u_550 , LTS_STATE_u_549 , 4, 't', LTS_STATE_u_552 , LTS_STATE_u_551 , 3, 'b', LTS_STATE_u_50 , LTS_STATE_u_553 , 3, 'p', LTS_STATE_u_555 , LTS_STATE_u_554 , 5, 'l', LTS_STATE_u_50 , LTS_STATE_u_556 , 5, 'n', LTS_STATE_u_85 , LTS_STATE_u_557 , 5, 'c', LTS_STATE_u_559 , LTS_STATE_u_558 , 4, 'm', LTS_STATE_u_28 , LTS_STATE_u_560 , 6, 'l', LTS_STATE_u_28 , LTS_STATE_u_561 , 6, 'l', LTS_STATE_u_27 , LTS_STATE_u_562 , 6, '#', LTS_STATE_u_563 , LTS_STATE_u_4 , 6, 'o', LTS_STATE_u_42 , LTS_STATE_u_564 , 3, 'm', LTS_STATE_u_27 , LTS_STATE_u_46 , 3, 'e', LTS_STATE_u_566 , LTS_STATE_u_565 , 6, 'e', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'h', LTS_STATE_u_85 , LTS_STATE_u_567 , 6, 'o', LTS_STATE_u_4 , LTS_STATE_u_568 , 6, 'd', LTS_STATE_u_27 , LTS_STATE_u_569 , 5, 'l', LTS_STATE_u_27 , LTS_STATE_u_50 , 3, 'k', LTS_STATE_u_46 , LTS_STATE_u_570 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_571 , 3, 'p', LTS_STATE_u_213 , LTS_STATE_u_102 , 6, '#', LTS_STATE_u_27 , LTS_STATE_u_572 , 4, 'p', LTS_STATE_u_27 , LTS_STATE_u_573 , 4, 'n', LTS_STATE_u_574 , LTS_STATE_u_102 , 6, '#', LTS_STATE_u_102 , LTS_STATE_u_249 , 3, 'b', LTS_STATE_u_85 , LTS_STATE_u_575 , 3, 'd', LTS_STATE_u_28 , LTS_STATE_u_576 , 5, 'f', LTS_STATE_u_4 , LTS_STATE_u_577 , 6, 'n', LTS_STATE_u_579 , LTS_STATE_u_578 , 6, '#', LTS_STATE_u_50 , LTS_STATE_u_580 , 3, 'l', LTS_STATE_u_50 , LTS_STATE_u_4 , 5, 'c', LTS_STATE_u_582 , LTS_STATE_u_581 , 5, 'd', LTS_STATE_u_584 , LTS_STATE_u_583 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_585 , 4, 'g', LTS_STATE_u_587 , LTS_STATE_u_586 , 6, '#', LTS_STATE_u_589 , LTS_STATE_u_588 , 3, 'p', LTS_STATE_u_50 , LTS_STATE_u_590 , 5, 'l', LTS_STATE_u_592 , LTS_STATE_u_591 , 5, 'l', LTS_STATE_u_50 , LTS_STATE_u_593 , 6, 'a', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'f', LTS_STATE_u_74 , LTS_STATE_u_594 , 4, 'g', LTS_STATE_u_85 , LTS_STATE_u_595 , 6, 'e', LTS_STATE_u_85 , LTS_STATE_u_596 , 6, 'h', LTS_STATE_u_28 , LTS_STATE_u_597 , 6, 'a', LTS_STATE_u_28 , LTS_STATE_u_598 , 6, 's', LTS_STATE_u_27 , LTS_STATE_u_599 , 5, 'z', LTS_STATE_u_4 , LTS_STATE_u_27 , 5, 'n', LTS_STATE_u_46 , LTS_STATE_u_27 , 6, 'w', LTS_STATE_u_85 , LTS_STATE_u_600 , 6, 'g', LTS_STATE_u_102 , LTS_STATE_u_4 , 5, 'v', LTS_STATE_u_85 , LTS_STATE_u_601 , 5, 'n', LTS_STATE_u_4 , LTS_STATE_u_602 , 3, 'c', LTS_STATE_u_42 , LTS_STATE_u_603 , 3, 'f', LTS_STATE_u_46 , LTS_STATE_u_604 , 4, 'd', LTS_STATE_u_28 , LTS_STATE_u_27 , 4, 'c', LTS_STATE_u_27 , LTS_STATE_u_605 , 3, 'z', LTS_STATE_u_27 , LTS_STATE_u_606 , 6, '#', LTS_STATE_u_102 , LTS_STATE_u_189 , 3, 'r', LTS_STATE_u_608 , LTS_STATE_u_607 , 3, 's', LTS_STATE_u_85 , LTS_STATE_u_609 , 5, '#', LTS_STATE_u_611 , LTS_STATE_u_610 , 4, 'l', LTS_STATE_u_27 , LTS_STATE_u_4 , 4, 'l', LTS_STATE_u_46 , LTS_STATE_u_4 , 3, 'd', LTS_STATE_u_50 , LTS_STATE_u_34 , 5, 'l', LTS_STATE_u_613 , LTS_STATE_u_612 , 4, 'c', LTS_STATE_u_615 , LTS_STATE_u_614 , 5, 'r', LTS_STATE_u_4 , LTS_STATE_u_616 , 4, 'n', LTS_STATE_u_617 , LTS_STATE_u_28 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_618 , 6, 'i', LTS_STATE_u_27 , LTS_STATE_u_619 , 6, 'e', LTS_STATE_u_102 , LTS_STATE_u_28 , 3, 'r', LTS_STATE_u_620 , LTS_STATE_u_28 , 3, 'm', LTS_STATE_u_46 , LTS_STATE_u_621 , 3, 'c', LTS_STATE_u_50 , LTS_STATE_u_28 , 5, 'y', LTS_STATE_u_27 , LTS_STATE_u_622 , 6, 'o', LTS_STATE_u_27 , LTS_STATE_u_28 , 6, 'o', LTS_STATE_u_50 , LTS_STATE_u_623 , 6, 'i', LTS_STATE_u_50 , LTS_STATE_u_624 , 6, 'a', LTS_STATE_u_626 , LTS_STATE_u_625 , 4, 'c', LTS_STATE_u_85 , LTS_STATE_u_28 , 4, 's', LTS_STATE_u_85 , LTS_STATE_u_627 , 5, 'm', LTS_STATE_u_85 , LTS_STATE_u_628 , 6, 'e', LTS_STATE_u_630 , LTS_STATE_u_629 , 3, 'd', LTS_STATE_u_46 , LTS_STATE_u_631 , 5, 't', LTS_STATE_u_85 , LTS_STATE_u_632 , 6, 'a', LTS_STATE_u_4 , LTS_STATE_u_42 , 3, 't', LTS_STATE_u_46 , LTS_STATE_u_633 , 3, 'b', LTS_STATE_u_46 , LTS_STATE_u_634 , 6, 'g', LTS_STATE_u_28 , LTS_STATE_u_635 , 6, 'l', LTS_STATE_u_27 , LTS_STATE_u_636 , 3, 'p', LTS_STATE_u_28 , LTS_STATE_u_637 , 4, 'n', LTS_STATE_u_28 , LTS_STATE_u_638 , 3, 'h', LTS_STATE_u_85 , LTS_STATE_u_28 , 6, 'a', LTS_STATE_u_27 , LTS_STATE_u_639 , 4, 'd', LTS_STATE_u_4 , LTS_STATE_u_27 , 5, 'r', LTS_STATE_u_641 , LTS_STATE_u_640 , 4, 'h', LTS_STATE_u_27 , LTS_STATE_u_642 , 3, 'b', LTS_STATE_u_643 , LTS_STATE_u_28 , 6, 'i', LTS_STATE_u_645 , LTS_STATE_u_644 , 3, 'i', LTS_STATE_u_85 , LTS_STATE_u_646 , 3, 'f', LTS_STATE_u_28 , LTS_STATE_u_647 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_213 , 3, 'b', LTS_STATE_u_649 , LTS_STATE_u_648 , 6, 'e', LTS_STATE_u_28 , LTS_STATE_u_27 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_650 , 3, 'h', LTS_STATE_u_28 , LTS_STATE_u_651 , 6, 'i', LTS_STATE_u_28 , LTS_STATE_u_652 , 6, 'o', LTS_STATE_u_50 , LTS_STATE_u_653 , 5, 'h', LTS_STATE_u_28 , LTS_STATE_u_654 , 4, 's', LTS_STATE_u_85 , LTS_STATE_u_655 , 6, 'o', LTS_STATE_u_85 , LTS_STATE_u_656 , 6, 'o', LTS_STATE_u_85 , LTS_STATE_u_657 , 4, 's', LTS_STATE_u_102 , LTS_STATE_u_658 , 4, 'g', LTS_STATE_u_102 , LTS_STATE_u_85 , 6, 't', LTS_STATE_u_46 , LTS_STATE_u_659 , 5, 'b', LTS_STATE_u_660 , LTS_STATE_u_85 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_661 , 3, 'm', LTS_STATE_u_46 , LTS_STATE_u_662 , 4, 'm', LTS_STATE_u_664 , LTS_STATE_u_663 , 6, 'r', LTS_STATE_u_102 , LTS_STATE_u_665 , 3, 'h', LTS_STATE_u_28 , LTS_STATE_u_666 , 4, 't', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'e', LTS_STATE_u_578 , LTS_STATE_u_667 , 4, 'z', LTS_STATE_u_669 , LTS_STATE_u_668 , 4, 'h', LTS_STATE_u_50 , LTS_STATE_u_670 , 4, 'c', LTS_STATE_u_27 , LTS_STATE_u_671 , 4, 'n', LTS_STATE_u_28 , LTS_STATE_u_672 , 6, 'o', LTS_STATE_u_27 , LTS_STATE_u_46 , 3, 'b', LTS_STATE_u_46 , LTS_STATE_u_27 , 3, 'p', LTS_STATE_u_674 , LTS_STATE_u_673 , 3, 'l', LTS_STATE_u_85 , LTS_STATE_u_675 , 3, 'd', LTS_STATE_u_28 , LTS_STATE_u_676 , 6, 'a', LTS_STATE_u_189 , LTS_STATE_u_28 , 3, 'r', LTS_STATE_u_46 , LTS_STATE_u_27 , 5, 'f', LTS_STATE_u_678 , LTS_STATE_u_677 , 5, 't', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'l', LTS_STATE_u_50 , LTS_STATE_u_679 , 4, 'f', LTS_STATE_u_681 , LTS_STATE_u_680 , 4, 'm', LTS_STATE_u_85 , LTS_STATE_u_28 , 6, 'r', LTS_STATE_u_85 , LTS_STATE_u_252 , 5, 'v', LTS_STATE_u_85 , LTS_STATE_u_682 , 6, 'a', LTS_STATE_u_27 , LTS_STATE_u_683 , 3, 'r', LTS_STATE_u_27 , LTS_STATE_u_684 , 6, 'e', LTS_STATE_u_28 , LTS_STATE_u_85 , 5, 'l', LTS_STATE_u_46 , LTS_STATE_u_685 , 4, 'k', LTS_STATE_u_46 , LTS_STATE_u_686 , 3, 's', LTS_STATE_u_46 , LTS_STATE_u_687 , 6, 'n', LTS_STATE_u_27 , LTS_STATE_u_46 , 4, 'l', LTS_STATE_u_689 , LTS_STATE_u_688 , 3, 'c', LTS_STATE_u_28 , LTS_STATE_u_690 , 4, 'l', LTS_STATE_u_4 , LTS_STATE_u_691 , 4, 's', LTS_STATE_u_693 , LTS_STATE_u_692 , 6, 'l', LTS_STATE_u_28 , LTS_STATE_u_694 , 3, 'n', LTS_STATE_u_46 , LTS_STATE_u_695 , 4, 'p', LTS_STATE_u_697 , LTS_STATE_u_696 , 4, 's', LTS_STATE_u_28 , LTS_STATE_u_50 , 5, 'l', LTS_STATE_u_28 , LTS_STATE_u_698 , 5, 's', LTS_STATE_u_50 , LTS_STATE_u_28 , 3, 'm', LTS_STATE_u_85 , LTS_STATE_u_28 , 3, 'r', LTS_STATE_u_28 , LTS_STATE_u_699 , 6, 'a', LTS_STATE_u_652 , LTS_STATE_u_700 , 3, 'g', LTS_STATE_u_28 , LTS_STATE_u_85 , 6, '#', LTS_STATE_u_50 , LTS_STATE_u_28 , 5, 'd', LTS_STATE_u_28 , LTS_STATE_u_701 , 6, 'i', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'l', LTS_STATE_u_85 , LTS_STATE_u_702 , 4, 'b', LTS_STATE_u_85 , LTS_STATE_u_703 , 4, 's', LTS_STATE_u_85 , LTS_STATE_u_704 , 3, 's', LTS_STATE_u_42 , LTS_STATE_u_705 , 4, 'n', LTS_STATE_u_707 , LTS_STATE_u_706 , 6, 'l', LTS_STATE_u_709 , LTS_STATE_u_708 , 6, '#', LTS_STATE_u_102 , LTS_STATE_u_710 , 3, 'c', LTS_STATE_u_102 , LTS_STATE_u_711 , 3, 'l', LTS_STATE_u_713 , LTS_STATE_u_712 , 6, 'e', LTS_STATE_u_27 , LTS_STATE_u_4 , 4, 'h', LTS_STATE_u_715 , LTS_STATE_u_714 , 5, 's', LTS_STATE_u_717 , LTS_STATE_u_716 , 6, 'e', LTS_STATE_u_719 , LTS_STATE_u_718 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_720 , 4, 'g', LTS_STATE_u_722 , LTS_STATE_u_721 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_476 , 5, 'z', LTS_STATE_u_609 , LTS_STATE_u_723 , 3, 'h', LTS_STATE_u_28 , LTS_STATE_u_724 , 6, '#', LTS_STATE_u_28 , LTS_STATE_u_725 , 5, 's', LTS_STATE_u_727 , LTS_STATE_u_726 , 6, 'r', LTS_STATE_u_85 , LTS_STATE_u_728 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_729 , 6, 'n', LTS_STATE_u_731 , LTS_STATE_u_730 , 3, 'p', LTS_STATE_u_42 , LTS_STATE_u_27 , 4, 's', LTS_STATE_u_46 , LTS_STATE_u_732 , 3, 'd', LTS_STATE_u_28 , LTS_STATE_u_27 , 4, 'l', LTS_STATE_u_734 , LTS_STATE_u_733 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_102 , 4, 'g', LTS_STATE_u_102 , LTS_STATE_u_735 , 3, 'b', LTS_STATE_u_102 , LTS_STATE_u_189 , 3, 'g', LTS_STATE_u_737 , LTS_STATE_u_736 , 4, 'b', LTS_STATE_u_28 , LTS_STATE_u_85 , 6, 'o', LTS_STATE_u_28 , LTS_STATE_u_738 , 6, 'e', LTS_STATE_u_27 , LTS_STATE_u_28 , 5, 't', LTS_STATE_u_739 , LTS_STATE_u_28 , 3, 'r', LTS_STATE_u_592 , LTS_STATE_u_28 , 5, 'z', LTS_STATE_u_740 , LTS_STATE_u_28 , 3, 'b', LTS_STATE_u_28 , LTS_STATE_u_46 , 6, 'i', LTS_STATE_u_28 , LTS_STATE_u_741 , 6, 'e', LTS_STATE_u_743 , LTS_STATE_u_742 , 3, 'g', LTS_STATE_u_46 , LTS_STATE_u_28 , 5, 'm', LTS_STATE_u_28 , LTS_STATE_u_744 , 6, '#', LTS_STATE_u_85 , LTS_STATE_u_28 , 6, 'y', LTS_STATE_u_85 , LTS_STATE_u_745 , 4, 'l', LTS_STATE_u_746 , LTS_STATE_u_28 , 4, 's', LTS_STATE_u_28 , LTS_STATE_u_737 , 5, 't', LTS_STATE_u_28 , LTS_STATE_u_747 , 6, 'r', LTS_STATE_u_85 , LTS_STATE_u_28 , 4, 'l', LTS_STATE_u_85 , LTS_STATE_u_748 , 3, 'l', LTS_STATE_u_46 , LTS_STATE_u_27 , 4, 'v', LTS_STATE_u_46 , LTS_STATE_u_749 , 3, 'j', LTS_STATE_u_27 , LTS_STATE_u_750 , 3, 'j', LTS_STATE_u_27 , LTS_STATE_u_751 , 6, 's', LTS_STATE_u_102 , LTS_STATE_u_752 , 3, 't', LTS_STATE_u_28 , LTS_STATE_u_85 , 4, 'n', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 'c', LTS_STATE_u_754 , LTS_STATE_u_753 , 6, 'r', LTS_STATE_u_756 , LTS_STATE_u_755 , 6, 'i', LTS_STATE_u_27 , LTS_STATE_u_592 , 3, 'd', LTS_STATE_u_713 , LTS_STATE_u_28 , 6, 'a', LTS_STATE_u_757 , LTS_STATE_u_28 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_28 , 4, 'm', LTS_STATE_u_759 , LTS_STATE_u_758 , 5, 'c', LTS_STATE_u_28 , LTS_STATE_u_760 , 6, 'o', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'j', LTS_STATE_u_85 , LTS_STATE_u_761 , 6, 's', LTS_STATE_u_27 , LTS_STATE_u_762 , 6, 'y', LTS_STATE_u_46 , LTS_STATE_u_763 , 4, 's', LTS_STATE_u_27 , LTS_STATE_u_764 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_765 , 4, 'n', LTS_STATE_u_102 , LTS_STATE_u_766 , 3, 'p', LTS_STATE_u_28 , LTS_STATE_u_767 , 4, 'm', LTS_STATE_u_768 , LTS_STATE_u_28 , 6, 'a', LTS_STATE_u_769 , LTS_STATE_u_28 , 3, 'l', LTS_STATE_u_85 , LTS_STATE_u_28 , 4, 'n', LTS_STATE_u_28 , LTS_STATE_u_27 , 4, 't', LTS_STATE_u_771 , LTS_STATE_u_770 , 5, 'p', LTS_STATE_u_28 , LTS_STATE_u_772 , 5, 't', LTS_STATE_u_28 , LTS_STATE_u_773 , 5, 's', LTS_STATE_u_681 , LTS_STATE_u_28 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_445 , 3, 'r', LTS_STATE_u_775 , LTS_STATE_u_774 , 3, 'd', LTS_STATE_u_27 , LTS_STATE_u_776 , 3, 't', LTS_STATE_u_46 , LTS_STATE_u_27 , 6, 'd', LTS_STATE_u_102 , LTS_STATE_u_27 , 5, 'z', LTS_STATE_u_778 , LTS_STATE_u_777 , 5, 's', LTS_STATE_u_85 , LTS_STATE_u_779 , 3, 'g', LTS_STATE_u_28 , LTS_STATE_u_780 , 3, 'j', LTS_STATE_u_28 , LTS_STATE_u_781 , 5, 's', LTS_STATE_u_28 , LTS_STATE_u_782 , 5, 'b', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 'c', LTS_STATE_u_28 , LTS_STATE_u_783 , 3, 't', LTS_STATE_u_27 , LTS_STATE_u_784 , 6, 'l', LTS_STATE_u_46 , LTS_STATE_u_27 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_785 , 3, 'i', LTS_STATE_u_85 , LTS_STATE_u_786 , 6, 'i', LTS_STATE_u_787 , LTS_STATE_u_28 , 5, 'v', LTS_STATE_u_85 , LTS_STATE_u_28 , 3, 'b', LTS_STATE_u_28 , LTS_STATE_u_788 , 5, 'n', LTS_STATE_u_28 , LTS_STATE_u_789 , 3, 'c', LTS_STATE_u_85 , LTS_STATE_u_28 , 3, 'v', LTS_STATE_u_28 , LTS_STATE_u_790 , 6, 'r', LTS_STATE_u_792 , LTS_STATE_u_791 , 6, 's', LTS_STATE_u_27 , LTS_STATE_u_793 , 4, 'k', LTS_STATE_u_85 , LTS_STATE_u_794 , 4, 'd', LTS_STATE_u_28 , LTS_STATE_u_795 , 3, 'm', LTS_STATE_u_28 , LTS_STATE_u_85 , 3, 'b', LTS_STATE_u_28 , LTS_STATE_u_796 , 3, 'g', LTS_STATE_u_28 , LTS_STATE_u_797 , 4, 'd', LTS_STATE_u_27 , LTS_STATE_u_798 , 3, 'l', LTS_STATE_u_27 , LTS_STATE_u_46 , 6, 'c', LTS_STATE_u_27 , LTS_STATE_u_799 , 3, 'l', LTS_STATE_u_801 , LTS_STATE_u_800 , 3, 'n', LTS_STATE_u_46 , LTS_STATE_u_28 , 3, 'g', LTS_STATE_u_28 , LTS_STATE_u_802 , 5, 'g', LTS_STATE_u_28 , LTS_STATE_u_803 , 6, 'l', LTS_STATE_u_27 , LTS_STATE_u_804 , 3, 't', LTS_STATE_u_27 , LTS_STATE_u_805 , 4, 'm', LTS_STATE_u_28 , LTS_STATE_u_806 , 5, 'n', LTS_STATE_u_85 , LTS_STATE_u_807 , 4, 'g', LTS_STATE_u_28 , LTS_STATE_u_808 , 5, 's', LTS_STATE_u_28 , LTS_STATE_u_809 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_810 , 4, 'b', LTS_STATE_u_27 , LTS_STATE_u_811 , 3, 'r', LTS_STATE_u_28 , LTS_STATE_u_812 , 6, 'a', LTS_STATE_u_814 , LTS_STATE_u_813 , 3, 'd', LTS_STATE_u_28 , LTS_STATE_u_815 , 5, 'k', LTS_STATE_u_28 , LTS_STATE_u_816 , 3, 'd', LTS_STATE_u_85 , LTS_STATE_u_331 , 6, 'n', LTS_STATE_u_27 , LTS_STATE_u_817 , 6, 'a', LTS_STATE_u_819 , LTS_STATE_u_818 , 5, 'w', LTS_STATE_u_28 , LTS_STATE_u_820 , 4, 'n', LTS_STATE_u_85 , LTS_STATE_u_28 , 5, 'g', LTS_STATE_u_822 , LTS_STATE_u_821 , 6, 'o', LTS_STATE_u_28 , LTS_STATE_u_788 , 6, 'a', LTS_STATE_u_27 , LTS_STATE_u_46 , 6, 's', LTS_STATE_u_675 , LTS_STATE_u_28 , 5, 't', LTS_STATE_u_28 , LTS_STATE_u_823 , 5, 't', LTS_STATE_u_824 , LTS_STATE_u_28 , 3, 'f', LTS_STATE_u_28 , LTS_STATE_u_825 , 3, 't', LTS_STATE_u_85 , LTS_STATE_u_28 , 3, 'n', LTS_STATE_u_85 , LTS_STATE_u_28 , 4, 't', LTS_STATE_u_28 , LTS_STATE_u_530 , 4, 'p', LTS_STATE_u_826 , LTS_STATE_u_28 , 5, 'p', LTS_STATE_u_28 , LTS_STATE_u_827 , 3, 'r', LTS_STATE_u_85 , LTS_STATE_u_28 , /** letter v **/ 4, 'v', LTS_STATE_v_2 , LTS_STATE_v_1 , 255, 68, 0,0 , 0,0 , 255, 0, 0,0 , 0,0 , /** letter w **/ 3, 'o', LTS_STATE_w_2 , LTS_STATE_w_1 , 3, 'e', LTS_STATE_w_4 , LTS_STATE_w_3 , 5, 'k', LTS_STATE_w_6 , LTS_STATE_w_5 , 3, 'a', LTS_STATE_w_8 , LTS_STATE_w_7 , 5, 'k', LTS_STATE_w_10 , LTS_STATE_w_9 , 6, 'z', LTS_STATE_w_12 , LTS_STATE_w_11 , 6, 'i', LTS_STATE_w_10 , LTS_STATE_w_13 , 4, 'r', LTS_STATE_w_13 , LTS_STATE_w_14 , 4, 'a', LTS_STATE_w_16 , LTS_STATE_w_15 , 6, 'z', LTS_STATE_w_18 , LTS_STATE_w_17 , 255, 37, 0,0 , 0,0 , 4, 'a', LTS_STATE_w_21 , LTS_STATE_w_20 , 5, 'c', LTS_STATE_w_18 , LTS_STATE_w_22 , 255, 0, 0,0 , 0,0 , 5, 'o', LTS_STATE_w_24 , LTS_STATE_w_23 , 5, 'k', LTS_STATE_w_10 , LTS_STATE_w_25 , 5, 'l', LTS_STATE_w_13 , LTS_STATE_w_22 , 4, 'o', LTS_STATE_w_16 , LTS_STATE_w_26 , 255, 68, 0,0 , 0,0 , 6, 'l', LTS_STATE_w_28 , LTS_STATE_w_27 , 5, 'y', LTS_STATE_w_22 , LTS_STATE_w_29 , 255, 53, 0,0 , 0,0 , 3, 'u', LTS_STATE_w_31 , LTS_STATE_w_30 , 4, 'h', LTS_STATE_w_32 , LTS_STATE_w_22 , 4, 'o', LTS_STATE_w_22 , LTS_STATE_w_33 , 4, 'a', LTS_STATE_w_35 , LTS_STATE_w_34 , 4, 'o', LTS_STATE_w_22 , LTS_STATE_w_13 , 5, 'l', LTS_STATE_w_22 , LTS_STATE_w_13 , 1, 'c', LTS_STATE_w_22 , LTS_STATE_w_13 , 5, 'r', LTS_STATE_w_37 , LTS_STATE_w_36 , 1, '#', LTS_STATE_w_22 , LTS_STATE_w_38 , 6, 'l', LTS_STATE_w_13 , LTS_STATE_w_39 , 4, 'h', LTS_STATE_w_22 , LTS_STATE_w_40 , 4, 'i', LTS_STATE_w_42 , LTS_STATE_w_41 , 5, 'y', LTS_STATE_w_22 , LTS_STATE_w_43 , 4, 'e', LTS_STATE_w_22 , LTS_STATE_w_44 , 3, 's', LTS_STATE_w_45 , LTS_STATE_w_22 , 4, 'e', LTS_STATE_w_22 , LTS_STATE_w_13 , 6, 'o', LTS_STATE_w_22 , LTS_STATE_w_13 , 4, 'i', LTS_STATE_w_47 , LTS_STATE_w_46 , 4, 'e', LTS_STATE_w_49 , LTS_STATE_w_48 , 6, 'd', LTS_STATE_w_22 , LTS_STATE_w_50 , 1, '#', LTS_STATE_w_13 , LTS_STATE_w_51 , 5, 's', LTS_STATE_w_53 , LTS_STATE_w_52 , 6, 't', LTS_STATE_w_22 , LTS_STATE_w_54 , 4, 'e', LTS_STATE_w_56 , LTS_STATE_w_55 , 6, 'g', LTS_STATE_w_13 , LTS_STATE_w_57 , 4, 'h', LTS_STATE_w_57 , LTS_STATE_w_13 , 6, 'l', LTS_STATE_w_57 , LTS_STATE_w_58 , 6, 'e', LTS_STATE_w_22 , LTS_STATE_w_59 , 6, 'e', LTS_STATE_w_22 , LTS_STATE_w_60 , 3, 'i', LTS_STATE_w_61 , LTS_STATE_w_22 , 6, 'i', LTS_STATE_w_18 , LTS_STATE_w_22 , 1, 'a', LTS_STATE_w_13 , LTS_STATE_w_62 , 5, 'o', LTS_STATE_w_63 , LTS_STATE_w_13 , 1, '#', LTS_STATE_w_64 , LTS_STATE_w_13 , 1, '#', LTS_STATE_w_13 , LTS_STATE_w_22 , 5, 'd', LTS_STATE_w_13 , LTS_STATE_w_65 , 1, 'e', LTS_STATE_w_22 , LTS_STATE_w_66 , 6, 'k', LTS_STATE_w_22 , LTS_STATE_w_67 , 1, 's', LTS_STATE_w_18 , LTS_STATE_w_22 , 6, 'd', LTS_STATE_w_13 , LTS_STATE_w_22 , 1, '#', LTS_STATE_w_68 , LTS_STATE_w_13 , 6, '#', LTS_STATE_w_13 , LTS_STATE_w_18 , 5, 'l', LTS_STATE_w_13 , LTS_STATE_w_69 , 5, 's', LTS_STATE_w_13 , LTS_STATE_w_70 , 6, '#', LTS_STATE_w_13 , LTS_STATE_w_71 , 6, 'n', LTS_STATE_w_13 , LTS_STATE_w_18 , 5, 'r', LTS_STATE_w_13 , LTS_STATE_w_72 , 5, 'n', LTS_STATE_w_13 , LTS_STATE_w_73 , 1, 's', LTS_STATE_w_13 , LTS_STATE_w_74 , 5, 's', LTS_STATE_w_13 , LTS_STATE_w_75 , 6, 't', LTS_STATE_w_13 , LTS_STATE_w_76 , 5, 'r', LTS_STATE_w_22 , LTS_STATE_w_28 , 5, 'y', LTS_STATE_w_13 , LTS_STATE_w_77 , 6, '#', LTS_STATE_w_13 , LTS_STATE_w_22 , 6, 't', LTS_STATE_w_13 , LTS_STATE_w_78 , 5, 'n', LTS_STATE_w_13 , LTS_STATE_w_79 , 5, '#', LTS_STATE_w_13 , LTS_STATE_w_22 , /** letter x **/ 3, 'u', LTS_STATE_x_2 , LTS_STATE_x_1 , 2, '0', LTS_STATE_x_4 , LTS_STATE_x_3 , 4, '#', LTS_STATE_x_6 , LTS_STATE_x_5 , 3, 'e', LTS_STATE_x_7 , LTS_STATE_x_5 , 255, 60, 0,0 , 0,0 , 255, 69, 0,0 , 0,0 , 2, 'l', LTS_STATE_x_5 , LTS_STATE_x_9 , 4, 'a', LTS_STATE_x_11 , LTS_STATE_x_10 , 255, 0, 0,0 , 0,0 , 4, 'u', LTS_STATE_x_13 , LTS_STATE_x_12 , 2, '#', LTS_STATE_x_15 , LTS_STATE_x_14 , 4, 'h', LTS_STATE_x_15 , LTS_STATE_x_16 , 2, 's', LTS_STATE_x_17 , LTS_STATE_x_15 , 2, 'l', LTS_STATE_x_15 , LTS_STATE_x_5 , 255, 70, 0,0 , 0,0 , 4, 'e', LTS_STATE_x_19 , LTS_STATE_x_18 , 255, 71, 0,0 , 0,0 , 4, 'i', LTS_STATE_x_21 , LTS_STATE_x_20 , 2, '#', LTS_STATE_x_15 , LTS_STATE_x_5 , 4, 'o', LTS_STATE_x_15 , LTS_STATE_x_5 , 2, 'l', LTS_STATE_x_5 , LTS_STATE_x_22 , 2, 'm', LTS_STATE_x_5 , LTS_STATE_x_19 , /** letter y **/ 4, '#', LTS_STATE_y_2 , LTS_STATE_y_1 , 2, '0', LTS_STATE_y_4 , LTS_STATE_y_3 , 3, 'a', LTS_STATE_y_6 , LTS_STATE_y_5 , 3, 'a', LTS_STATE_y_8 , LTS_STATE_y_7 , 5, 'a', LTS_STATE_y_10 , LTS_STATE_y_9 , 3, 'o', LTS_STATE_y_6 , LTS_STATE_y_11 , 255, 0, 0,0 , 0,0 , 3, 'o', LTS_STATE_y_14 , LTS_STATE_y_13 , 4, 'a', LTS_STATE_y_16 , LTS_STATE_y_15 , 255, 41, 0,0 , 0,0 , 4, 'e', LTS_STATE_y_9 , LTS_STATE_y_17 , 3, 'f', LTS_STATE_y_19 , LTS_STATE_y_18 , 3, 'e', LTS_STATE_y_21 , LTS_STATE_y_20 , 4, 'o', LTS_STATE_y_23 , LTS_STATE_y_22 , 4, 'u', LTS_STATE_y_6 , LTS_STATE_y_24 , 5, 'm', LTS_STATE_y_9 , LTS_STATE_y_25 , 255, 31, 0,0 , 0,0 , 3, 'e', LTS_STATE_y_27 , LTS_STATE_y_26 , 2, 'i', LTS_STATE_y_29 , LTS_STATE_y_28 , 1, '0', LTS_STATE_y_31 , LTS_STATE_y_30 , 4, 'e', LTS_STATE_y_33 , LTS_STATE_y_32 , 5, 'm', LTS_STATE_y_9 , LTS_STATE_y_6 , 2, 't', LTS_STATE_y_9 , LTS_STATE_y_6 , 4, 'o', LTS_STATE_y_6 , LTS_STATE_y_34 , 2, 'b', LTS_STATE_y_6 , LTS_STATE_y_35 , 3, 'u', LTS_STATE_y_29 , LTS_STATE_y_36 , 2, 'l', LTS_STATE_y_17 , LTS_STATE_y_37 , 2, 'f', LTS_STATE_y_17 , LTS_STATE_y_29 , 255, 19, 0,0 , 0,0 , 4, 'a', LTS_STATE_y_39 , LTS_STATE_y_38 , 3, 's', LTS_STATE_y_41 , LTS_STATE_y_40 , 1, '#', LTS_STATE_y_6 , LTS_STATE_y_42 , 2, 'm', LTS_STATE_y_44 , LTS_STATE_y_43 , 5, 'v', LTS_STATE_y_29 , LTS_STATE_y_6 , 2, 'r', LTS_STATE_y_6 , LTS_STATE_y_45 , 2, 'f', LTS_STATE_y_46 , LTS_STATE_y_17 , 2, 'n', LTS_STATE_y_17 , LTS_STATE_y_47 , 1, '#', LTS_STATE_y_49 , LTS_STATE_y_48 , 1, '#', LTS_STATE_y_51 , LTS_STATE_y_50 , 5, 'e', LTS_STATE_y_29 , LTS_STATE_y_52 , 5, 'o', LTS_STATE_y_54 , LTS_STATE_y_53 , 2, 'n', LTS_STATE_y_17 , LTS_STATE_y_55 , 5, 'r', LTS_STATE_y_57 , LTS_STATE_y_56 , 1, '#', LTS_STATE_y_29 , LTS_STATE_y_58 , 2, 'k', LTS_STATE_y_29 , LTS_STATE_y_59 , 3, 'l', LTS_STATE_y_29 , LTS_STATE_y_17 , 2, 's', LTS_STATE_y_17 , LTS_STATE_y_60 , 5, 'e', LTS_STATE_y_62 , LTS_STATE_y_61 , 2, 'a', LTS_STATE_y_64 , LTS_STATE_y_63 , 3, 'i', LTS_STATE_y_66 , LTS_STATE_y_65 , 3, 'i', LTS_STATE_y_9 , LTS_STATE_y_29 , 4, 'o', LTS_STATE_y_68 , LTS_STATE_y_67 , 4, 'r', LTS_STATE_y_70 , LTS_STATE_y_69 , 4, 'n', LTS_STATE_y_71 , LTS_STATE_y_70 , 5, '#', LTS_STATE_y_17 , LTS_STATE_y_72 , 5, 'd', LTS_STATE_y_6 , LTS_STATE_y_29 , 2, 'b', LTS_STATE_y_29 , LTS_STATE_y_6 , 255, 13, 0,0 , 0,0 , 5, 'n', LTS_STATE_y_6 , LTS_STATE_y_73 , 2, 'v', LTS_STATE_y_74 , LTS_STATE_y_17 , 4, 'n', LTS_STATE_y_76 , LTS_STATE_y_75 , 3, 'r', LTS_STATE_y_17 , LTS_STATE_y_77 , 2, 'o', LTS_STATE_y_79 , LTS_STATE_y_78 , 3, 'n', LTS_STATE_y_17 , LTS_STATE_y_70 , 5, 'n', LTS_STATE_y_80 , LTS_STATE_y_9 , 5, '#', LTS_STATE_y_6 , LTS_STATE_y_9 , 4, 'u', LTS_STATE_y_9 , LTS_STATE_y_81 , 3, 'k', LTS_STATE_y_9 , LTS_STATE_y_82 , 5, 'e', LTS_STATE_y_29 , LTS_STATE_y_70 , 255, 12, 0,0 , 0,0 , 255, 5, 0,0 , 0,0 , 2, 'l', LTS_STATE_y_17 , LTS_STATE_y_6 , 2, 'p', LTS_STATE_y_6 , LTS_STATE_y_29 , 1, 'a', LTS_STATE_y_17 , LTS_STATE_y_83 , 5, 'n', LTS_STATE_y_85 , LTS_STATE_y_84 , 5, 'a', LTS_STATE_y_58 , LTS_STATE_y_86 , 1, 'p', LTS_STATE_y_88 , LTS_STATE_y_87 , 2, 'e', LTS_STATE_y_90 , LTS_STATE_y_89 , 4, 'm', LTS_STATE_y_70 , LTS_STATE_y_71 , 2, 'e', LTS_STATE_y_9 , LTS_STATE_y_91 , 4, 'a', LTS_STATE_y_93 , LTS_STATE_y_92 , 5, 'n', LTS_STATE_y_29 , LTS_STATE_y_94 , 1, 'o', LTS_STATE_y_17 , LTS_STATE_y_95 , 4, 'k', LTS_STATE_y_97 , LTS_STATE_y_96 , 4, 'i', LTS_STATE_y_98 , LTS_STATE_y_91 , 2, 'a', LTS_STATE_y_100 , LTS_STATE_y_99 , 2, 'g', LTS_STATE_y_70 , LTS_STATE_y_101 , 4, 'm', LTS_STATE_y_71 , LTS_STATE_y_17 , 3, 's', LTS_STATE_y_29 , LTS_STATE_y_102 , 3, 'g', LTS_STATE_y_71 , LTS_STATE_y_70 , 3, 'n', LTS_STATE_y_9 , LTS_STATE_y_17 , 4, 'e', LTS_STATE_y_29 , LTS_STATE_y_103 , 5, 'n', LTS_STATE_y_58 , LTS_STATE_y_29 , 3, 'm', LTS_STATE_y_29 , LTS_STATE_y_9 , 1, 'l', LTS_STATE_y_17 , LTS_STATE_y_6 , 4, 'l', LTS_STATE_y_105 , LTS_STATE_y_104 , 5, '#', LTS_STATE_y_106 , LTS_STATE_y_70 , 3, 'f', LTS_STATE_y_29 , LTS_STATE_y_107 , 2, 'e', LTS_STATE_y_71 , LTS_STATE_y_108 , 3, 'r', LTS_STATE_y_106 , LTS_STATE_y_70 , 4, 'l', LTS_STATE_y_110 , LTS_STATE_y_109 , 5, 'e', LTS_STATE_y_29 , LTS_STATE_y_111 , 4, 'r', LTS_STATE_y_113 , LTS_STATE_y_112 , 4, 'e', LTS_STATE_y_115 , LTS_STATE_y_114 , 5, '#', LTS_STATE_y_71 , LTS_STATE_y_116 , 255, 16, 0,0 , 0,0 , 3, 'l', LTS_STATE_y_118 , LTS_STATE_y_117 , 5, 's', LTS_STATE_y_70 , LTS_STATE_y_119 , 3, 'd', LTS_STATE_y_29 , LTS_STATE_y_120 , 2, 's', LTS_STATE_y_29 , LTS_STATE_y_71 , 4, 'e', LTS_STATE_y_29 , LTS_STATE_y_121 , 3, 'h', LTS_STATE_y_123 , LTS_STATE_y_122 , 5, 'o', LTS_STATE_y_29 , LTS_STATE_y_124 , 4, 'o', LTS_STATE_y_126 , LTS_STATE_y_125 , 3, 'u', LTS_STATE_y_6 , LTS_STATE_y_127 , 3, 'r', LTS_STATE_y_129 , LTS_STATE_y_128 , 2, 'r', LTS_STATE_y_17 , LTS_STATE_y_130 , 2, 'l', LTS_STATE_y_17 , LTS_STATE_y_29 , 1, 'r', LTS_STATE_y_71 , LTS_STATE_y_131 , 4, 'n', LTS_STATE_y_29 , LTS_STATE_y_132 , 3, 'k', LTS_STATE_y_29 , LTS_STATE_y_133 , 4, 'n', LTS_STATE_y_135 , LTS_STATE_y_134 , 5, 'n', LTS_STATE_y_70 , LTS_STATE_y_136 , 5, 'a', LTS_STATE_y_29 , LTS_STATE_y_137 , 4, 'u', LTS_STATE_y_9 , LTS_STATE_y_138 , 5, '#', LTS_STATE_y_9 , LTS_STATE_y_17 , 5, '#', LTS_STATE_y_29 , LTS_STATE_y_139 , 2, 'a', LTS_STATE_y_71 , LTS_STATE_y_140 , 1, 'm', LTS_STATE_y_71 , LTS_STATE_y_17 , 3, 'r', LTS_STATE_y_29 , LTS_STATE_y_17 , 5, 'i', LTS_STATE_y_70 , LTS_STATE_y_141 , 4, 'p', LTS_STATE_y_29 , LTS_STATE_y_142 , 4, 'o', LTS_STATE_y_144 , LTS_STATE_y_143 , 5, 'o', LTS_STATE_y_146 , LTS_STATE_y_145 , 3, 'd', LTS_STATE_y_29 , LTS_STATE_y_70 , 5, 't', LTS_STATE_y_70 , LTS_STATE_y_29 , 3, 'l', LTS_STATE_y_70 , LTS_STATE_y_147 , 4, 'r', LTS_STATE_y_149 , LTS_STATE_y_148 , 3, 'm', LTS_STATE_y_17 , LTS_STATE_y_150 , 3, 'b', LTS_STATE_y_70 , LTS_STATE_y_71 , 3, 'w', LTS_STATE_y_70 , LTS_STATE_y_151 , 1, 'e', LTS_STATE_y_153 , LTS_STATE_y_152 , 3, 'u', LTS_STATE_y_29 , LTS_STATE_y_154 , 3, 'r', LTS_STATE_y_29 , LTS_STATE_y_6 , 3, 'c', LTS_STATE_y_156 , LTS_STATE_y_155 , 4, 'c', LTS_STATE_y_58 , LTS_STATE_y_29 , 3, 'm', LTS_STATE_y_6 , LTS_STATE_y_157 , 5, 't', LTS_STATE_y_159 , LTS_STATE_y_158 , 2, 'o', LTS_STATE_y_17 , LTS_STATE_y_6 , 3, 'l', LTS_STATE_y_160 , LTS_STATE_y_9 , 3, 's', LTS_STATE_y_70 , LTS_STATE_y_161 , 2, 'a', LTS_STATE_y_29 , LTS_STATE_y_162 , 2, 'n', LTS_STATE_y_29 , LTS_STATE_y_17 , 4, 'n', LTS_STATE_y_70 , LTS_STATE_y_163 , 5, 'a', LTS_STATE_y_165 , LTS_STATE_y_164 , 4, 'c', LTS_STATE_y_29 , LTS_STATE_y_166 , 5, 'i', LTS_STATE_y_29 , LTS_STATE_y_70 , 4, 'c', LTS_STATE_y_168 , LTS_STATE_y_167 , 3, 'l', LTS_STATE_y_71 , LTS_STATE_y_70 , 5, 'a', LTS_STATE_y_9 , LTS_STATE_y_17 , 2, 'r', LTS_STATE_y_70 , LTS_STATE_y_169 , 1, 'c', LTS_STATE_y_17 , LTS_STATE_y_170 , 5, 'n', LTS_STATE_y_29 , LTS_STATE_y_171 , 3, 'm', LTS_STATE_y_70 , LTS_STATE_y_172 , 3, 'l', LTS_STATE_y_29 , LTS_STATE_y_173 , 4, 'p', LTS_STATE_y_29 , LTS_STATE_y_70 , 4, 'i', LTS_STATE_y_126 , LTS_STATE_y_174 , 3, 'c', LTS_STATE_y_176 , LTS_STATE_y_175 , 1, 'e', LTS_STATE_y_71 , LTS_STATE_y_70 , 3, 'l', LTS_STATE_y_17 , LTS_STATE_y_177 , 4, 'l', LTS_STATE_y_29 , LTS_STATE_y_178 , 4, 'm', LTS_STATE_y_70 , LTS_STATE_y_179 , 3, 'b', LTS_STATE_y_29 , LTS_STATE_y_180 , 3, 'l', LTS_STATE_y_182 , LTS_STATE_y_181 , 3, 'z', LTS_STATE_y_70 , LTS_STATE_y_183 , 2, 'i', LTS_STATE_y_106 , LTS_STATE_y_29 , 2, 'o', LTS_STATE_y_29 , LTS_STATE_y_184 , 5, 'o', LTS_STATE_y_29 , LTS_STATE_y_185 , 3, 'r', LTS_STATE_y_70 , LTS_STATE_y_186 , 4, 'l', LTS_STATE_y_70 , LTS_STATE_y_187 , 3, 'z', LTS_STATE_y_189 , LTS_STATE_y_188 , 2, 'l', LTS_STATE_y_191 , LTS_STATE_y_190 , 2, 'o', LTS_STATE_y_192 , LTS_STATE_y_70 , 4, 'r', LTS_STATE_y_29 , LTS_STATE_y_193 , 2, 'f', LTS_STATE_y_29 , LTS_STATE_y_194 , 4, 'i', LTS_STATE_y_29 , LTS_STATE_y_195 , 4, 'b', LTS_STATE_y_70 , LTS_STATE_y_29 , 4, 'd', LTS_STATE_y_197 , LTS_STATE_y_196 , 4, 'b', LTS_STATE_y_71 , LTS_STATE_y_29 , 4, 't', LTS_STATE_y_199 , LTS_STATE_y_198 , 4, 's', LTS_STATE_y_71 , LTS_STATE_y_17 , 1, 'p', LTS_STATE_y_106 , LTS_STATE_y_17 , 3, 'h', LTS_STATE_y_29 , LTS_STATE_y_58 , 2, 's', LTS_STATE_y_201 , LTS_STATE_y_200 , 5, 'u', LTS_STATE_y_70 , LTS_STATE_y_202 , 1, 'o', LTS_STATE_y_70 , LTS_STATE_y_203 , 3, 'h', LTS_STATE_y_29 , LTS_STATE_y_17 , 5, 'i', LTS_STATE_y_71 , LTS_STATE_y_204 , 2, 'a', LTS_STATE_y_70 , LTS_STATE_y_71 , 2, 'p', LTS_STATE_y_70 , LTS_STATE_y_205 , 3, 'z', LTS_STATE_y_70 , LTS_STATE_y_29 , 3, 'z', LTS_STATE_y_70 , LTS_STATE_y_206 , 1, 'r', LTS_STATE_y_70 , LTS_STATE_y_207 , 1, 'p', LTS_STATE_y_208 , LTS_STATE_y_70 , 4, 'p', LTS_STATE_y_70 , LTS_STATE_y_209 , 5, 'h', LTS_STATE_y_29 , LTS_STATE_y_210 , 4, 'p', LTS_STATE_y_70 , LTS_STATE_y_211 , 4, 'g', LTS_STATE_y_70 , LTS_STATE_y_212 , 5, 'h', LTS_STATE_y_70 , LTS_STATE_y_213 , 3, 'd', LTS_STATE_y_70 , LTS_STATE_y_214 , 3, 's', LTS_STATE_y_71 , LTS_STATE_y_215 , 5, 'a', LTS_STATE_y_71 , LTS_STATE_y_17 , 3, 'h', LTS_STATE_y_29 , LTS_STATE_y_216 , 5, 's', LTS_STATE_y_70 , LTS_STATE_y_217 , 3, 'n', LTS_STATE_y_218 , LTS_STATE_y_17 , 2, 'c', LTS_STATE_y_70 , LTS_STATE_y_219 , 3, 'b', LTS_STATE_y_29 , LTS_STATE_y_220 , 2, 'o', LTS_STATE_y_71 , LTS_STATE_y_17 , 3, 'r', LTS_STATE_y_70 , LTS_STATE_y_29 , 4, 'd', LTS_STATE_y_70 , LTS_STATE_y_221 , 5, 'i', LTS_STATE_y_29 , LTS_STATE_y_222 , 3, 'l', LTS_STATE_y_29 , LTS_STATE_y_223 , 3, 'w', LTS_STATE_y_29 , LTS_STATE_y_70 , /** letter z **/ 3, 't', LTS_STATE_z_2 , LTS_STATE_z_1 , 4, 'z', LTS_STATE_z_4 , LTS_STATE_z_3 , 4, '#', LTS_STATE_z_6 , LTS_STATE_z_5 , 3, 'c', LTS_STATE_z_4 , LTS_STATE_z_7 , 255, 0, 0,0 , 0,0 , 4, 'e', LTS_STATE_z_10 , LTS_STATE_z_9 , 255, 24, 0,0 , 0,0 , 3, 's', LTS_STATE_z_4 , LTS_STATE_z_11 , 4, 's', LTS_STATE_z_4 , LTS_STATE_z_12 , 255, 60, 0,0 , 0,0 , 3, 'z', LTS_STATE_z_14 , LTS_STATE_z_13 , 4, 'i', LTS_STATE_z_10 , LTS_STATE_z_15 , 3, 'd', LTS_STATE_z_17 , LTS_STATE_z_16 , 4, 'l', LTS_STATE_z_10 , LTS_STATE_z_18 , 4, 'o', LTS_STATE_z_10 , LTS_STATE_z_6 , 4, 's', LTS_STATE_z_4 , LTS_STATE_z_19 , 4, 'i', LTS_STATE_z_4 , LTS_STATE_z_20 , 4, '#', LTS_STATE_z_10 , LTS_STATE_z_21 , 4, 'h', LTS_STATE_z_23 , LTS_STATE_z_22 , 4, 'e', LTS_STATE_z_10 , LTS_STATE_z_4 , 4, 'y', LTS_STATE_z_10 , LTS_STATE_z_24 , 3, 'r', LTS_STATE_z_10 , LTS_STATE_z_25 , 3, '#', LTS_STATE_z_26 , LTS_STATE_z_10 , 4, 'o', LTS_STATE_z_10 , LTS_STATE_z_27 , 4, '#', LTS_STATE_z_10 , LTS_STATE_z_28 , 255, 39, 0,0 , 0,0 , 4, 'e', LTS_STATE_z_10 , LTS_STATE_z_29 , 3, 'l', LTS_STATE_z_30 , LTS_STATE_z_10 , 255, 23, 0,0 , 0,0 , 4, 'b', LTS_STATE_z_29 , LTS_STATE_z_10 , 0, 0, 0,0, 0,0 }; static const char * const cmu6_lts_phone_table[73] = { "epsilon", "EH", "AA", "EY", "AW", "AH", "EY", "AO", "AE", "AW", "OW", "OW", "IH", "AY", "AO", "AA", "IH", "AE", "W-EY", "AY", "B", "CH", "K", "T-S", "S", "SH", "D", "T", "JH", "IY", "Y-UW", "IY", "EH", "UW", "OY", "Y-UW", "UW", "F", "G", "ZH", "HH", "Y", "L", "AH-L", "M", "AH-M", "M-AH", "M-AE", "NG", "N", "AH", "UH", "UH", "W", "OY", "W-AH", "P", "R", "ER", "ER", "Z", "TH", "DH", "Y-UH", "Y-ER", "Y-ER", "Y-AH", "AH-W", "V", "K-S", "G-Z", "K-SH", NULL }; static const cst_lts_addr cmu6_lts_letter_index[27] = { 0, /* a */ 2894, /* b */ 2915, /* c */ 3260, /* d */ 3363, /* e */ 5647, /* f */ 5650, /* g */ 5939, /* h */ 6050, /* i */ 7741, /* j */ 7762, /* k */ 7768, /* l */ 7953, /* m */ 7975, /* n */ 8061, /* o */ 9998, /* p */ 10018, /* q */ 10019, /* r */ 11018, /* s */ 11695, /* t */ 11916, /* u */ 12743, /* v */ 12746, /* w */ 12825, /* x */ 12847, /* y */ 13070, /* z */ 0 }; const cst_lts_rules cmu6_lts_rules = { "cmu6", cmu6_lts_letter_index, cmu6_lts_model, cmu6_lts_phone_table, 4, 1 }; <file_sep>/SphinxTrain/src/libs/libcep_feat/s2_feat.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_feat.c * * Description: * Compute standard SPHINX-II derived cepstrum features. * Takes the standard 13 component MFCC vector, MFCC, and computes 4 * independent feature streams: * * cep: MFCC[1..12] * dcep: < (cep[t + 2] - cep[t - 2]), (cep[t + 4] - cep[t - 4]) > * pow: < MFCC0[t], MFCC0[t+2] - MFCC0[t-2], pow[t+1][1] - pow[t-1][1]> * ddcep: < dcep[t+1] - dcep[t-1] > * * Optionally does the following transformations on MFCC before computing the * derived features above: * * 1. Cepstral mean normalization (based on current utt or prior * utterances). * 2. Automatic gain control: * - subtract utter max c[0] from all c[0] * - subtract estimated utter max (based on prior utterances) * from all c[0] of current utterances. * 3. Silence deletion * - based on c[0] histogram of current utterance * - based on c[0] histogram of prior utterance * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include "s2_feat.h" #include <s3/feat.h> #include "s2_cep.h" #include "s2_dcep.h" #include "s2_ddcep.h" #include <s3/agc.h> #include <s3/cmn.h> #include <s3/silcomp.h> #include <s3/s2_param.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <assert.h> #include <string.h> #include <stdio.h> static uint32 n_feat = S2_N_FEATURE; static uint32 in_veclen = 0; static uint32 vecsize[S2_N_FEATURE] = { 0, 0, 0, 0 }; const char * s2_feat_doc() { return "SPHINX-II 4 stream (12 cep, 24 dcep, 3 pow, 12 ddcep)"; } uint32 s2_feat_id() { return FEAT_ID_SPHINX_II_STD; } uint32 s2_feat_n_stream() { return S2_N_FEATURE; } void s2_feat_set_in_veclen(uint32 veclen) { in_veclen = veclen; vecsize[0] = in_veclen - 1; vecsize[1] = 2*vecsize[0]; vecsize[2] = 3; vecsize[3] = vecsize[0]; cmn_set_veclen(veclen); agc_set_veclen(veclen); s2_cep_set_veclen(veclen); s2_dcep_set_veclen(veclen); s2_ddcep_set_veclen(veclen); } uint32 s2_feat_blksize() { int i; uint32 size; for (i = 0, size = 0; i < s2_feat_n_stream(); i++) { size += vecsize[i]; } return size; } const uint32 * s2_feat_vecsize() { return vecsize; } vector_t ** s2_feat_compute(vector_t *mfcc, uint32 *inout_n_frame) { vector_t **out; uint32 svd_n_frame, n_frame; const char *comp_type = cmd_ln_access("-silcomp"); n_frame = svd_n_frame = *inout_n_frame; if (strcmp(comp_type, "none") != 0) { n_frame = sil_compression(comp_type, mfcc, n_frame); } cmn(&mfcc[0][0], n_frame); agc(&mfcc[0][0], n_frame); if (svd_n_frame - n_frame > 0) { fprintf(stdout, "(del %d frames) ", svd_n_frame - n_frame); fflush(stdout); } out = feat_alloc(n_frame); s2_cep_feat(out, mfcc, n_frame); /* see s2_cep.c */ s2_short_dcep_feat(out, mfcc, n_frame); /* see s2_dcep.c */ s2_long_dcep_feat(out, mfcc, n_frame); /* see s2_dcep.c */ s2_sec_ord_dcep_feat(out, mfcc, n_frame); /* see s2_ddcep.c */ *inout_n_frame = n_frame; return out; } void s2_feat_print(const char *label, vector_t **f, uint32 n_frames) { uint32 i; int32 j; uint32 k; char *name[] = { " cep", " dcep", " pow", "ddcep" }; vector_t *frame; vector_t stream; for (i = 0; i < n_frames; i++) { frame = f[i]; for (j = 0; j < S2_N_FEATURE; j++) { stream = frame[j]; printf("%s%s[%04u]: ", label, name[j], i); for (k = 0; k < vecsize[j]; k++) { printf("%.3e ", stream[k]); } printf("\n"); } printf("\n"); } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.5 1996/03/25 15:36:31 eht * Changes to allow for settable input feature length * * Revision 1.4 1996/01/26 18:04:51 eht * *** empty log message *** * * Revision 1.3 1995/12/14 20:12:58 eht * SPHINX-II feature extractor * * Revision 1.2 1995/12/07 19:44:22 eht * Added some comments and changed the interface name to s2_*() * * Revision 1.1 1995/12/07 19:29:27 eht * Initial revision * * Revision 1.8 1995/12/07 19:20:09 eht * Added a function to return the total size of a frames worth of * features * * Revision 1.7 1995/12/04 14:59:55 eht * Added a feat_n_stream() function so that callers of this * module can know how many feature streams it computes. * * Revision 1.6 1995/10/12 17:39:31 eht * Use memcpy rather than bcopy since memcpy is a part * of the ANSI-C specification. * * Revision 1.5 1995/10/10 17:38:24 eht * Include some prototypes for called functions * Make some unsigned values consistent * * Revision 1.4 1995/10/09 20:56:36 eht * Changes needed for prim_type.h * * Revision 1.3 1995/10/09 15:02:03 eht * Changed ckd_alloc interface to get rid of __FILE__, __LINE__ arguments * * Revision 1.2 1995/09/07 19:04:37 eht * Fixed latent bug in argument passing to the silence * compression stuff. * * Revision 1.1 95/06/02 14:52:54 14:52:54 eht (<NAME>) * Initial revision * * */ <file_sep>/sphinx4/tests/linguist/language/ngram/large/MemoryTest.java /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package tests.linguist.language.ngram.large; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import edu.cmu.sphinx.linguist.WordSequence; import edu.cmu.sphinx.linguist.dictionary.Dictionary; import edu.cmu.sphinx.linguist.dictionary.FastDictionary; import edu.cmu.sphinx.linguist.dictionary.Word; import edu.cmu.sphinx.linguist.language.ngram.large.LargeTrigramModel; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.TimerPool; import edu.cmu.sphinx.util.props.ConfigurationManager; /** * Reads in a file of n-grams, with each utterance bounded by <START_UTT> * and <END_UTT> markers. A sample test file looks like: * * <code> * <START_UTT> * ngram_0 * ngram_1 * ... * <END_UTT> * <START_UTT> * ngram_0 * ngram_1 * <END_UTT> * ... * </code> * * This test will then query the dynamic language model loader for all * the ngrams in an utterance, and clears the language model cache * after the utterance. This is intended to simulate what happens during * a real decoding. * * To run this test: * <code> * java MemoryTest <propertiesFile> <testFile> <outputFile> * </code> */ public class MemoryTest { private BufferedReader reader; private Dictionary dictionary; private LargeTrigramModel lm; private Timer timer; private PrintStream outStream = System.out; private int totalQueries; private boolean printScores; /** * Constructs an MemoryTest. * * @param context the context to use * @param configPath the properties file to use * @param testFile the N-gram test file * @param outFile the output file */ public MemoryTest(String context, String configPath, String testFile, String outFile) throws IOException { ConfigurationManager cm = new ConfigurationManager (configPath); dictionary = (FastDictionary) cm.lookup("dictionary"); lm = (LargeTrigramModel) cm.lookup("trigramModel"); printScores = Boolean.getBoolean("printScores"); InputStream stream = new FileInputStream(testFile); reader = new BufferedReader(new InputStreamReader(stream)); if (outFile != null) { outStream = new PrintStream(new FileOutputStream(outFile)); } timer = TimerPool.getTimer(this, "lmLookup"); } /** * Close the results output stream */ public void close() { // outStream.close(); } /** * Returns true if there are more utterances to test. * * @return true if there are more utterances to test */ public boolean hasMoreUtterances() throws IOException { String input = reader.readLine(); return (input != null && input.trim().equals("<START_UTT>")); } /** * Test the next available utterance. */ public void testUtterance() throws IOException { String input; timer.start(); lm.start(); while ((input = reader.readLine()) != null && !input.equals("<END_UTT>")) { input = input.toLowerCase(); StringTokenizer st = new StringTokenizer(input); List<Word> list = new ArrayList<Word>(); while (st.hasMoreTokens()) { String tok = st.nextToken(); list.add(dictionary.getWord(tok)); } WordSequence ws = new WordSequence(list); lm.getProbability(ws); totalQueries++; } lm.stop(); timer.stop(); } /** * Prints out statistics */ public void printStats() { long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("Total queries: " + totalQueries + " ngrams"); System.out.println("Used memory: " + usedMemory + " bytes"); System.out.println("Bigram misses: " + lm.getBigramMisses()); System.out.println("Trigram misses: " + lm.getTrigramMisses()); System.out.println("Trigram hits: " + lm.getTrigramHits()); TimerPool.dumpAll(); } /** * The main program */ public static void main(String[] args) throws Exception { String propsPath; String testFile = null; String outFile = null; if (args.length == 0) { System.out.println ("Usage: java MemoryTest <props_file> " + "<testFile> <output_file>"); } propsPath = args[0]; if (args.length >= 2) { testFile = args[1]; } if (args.length >= 3) { outFile = args[2]; } try { MemoryTest test = new MemoryTest ("test", propsPath, testFile, outFile); while (test.hasMoreUtterances()) { test.testUtterance(); } test.printStats(); test.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } <file_sep>/SphinxTrain/include/s3/profile.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * profile.h -- For timing and event counting. * * HISTORY * * 27-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created from Sphinx-II version. */ #ifndef _LIBUTIL_PROFILE_H_ #define _LIBUTIL_PROFILE_H_ #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include "prim_type.h" #include <stdio.h> /* Event counter functions */ int32 counter_new (char *name); void counter_increment (int32 id, int32 count); /* Increment counter by count */ void counter_print_all (FILE *fp); void counter_reset_all ( void ); /* * Timing structures and functions for coarse-grained performance measurements. * Using standard system calls. */ typedef struct timing_s { float64 t_cpu; /* CPU time for most recent start-stop operation */ float64 t_elapsed; /* Elapsed time for most recent start-stop operation */ float64 t_tot_cpu; /* Accumulated CPU time */ float64 t_tot_elapsed; /* Accumulated elapsed time */ float64 start_cpu; /* FOR INTERNAL USE ONLY */ float64 start_elapsed; /* FOR INTERNAL USE ONLY */ } timing_t; timing_t *timing_new ( void ); /* Obtain and initialize a new timing module */ /* Start timing */ void timing_start (timing_t *tm); /* Stop timing and accumulate t_cpu, t_elapsed, t_tot_cpu, t_tot_elapsed */ void timing_stop (timing_t *tm); /* Reset t_cpu, t_elapsed to 0.0 */ void timing_reset (timing_t *tm); /* Register a timing_t structure under a name */ void timing_bind_name(const char *name, timing_t *tmr); /* Given a name, return the timing_t structure associated with it. Returns NULL if no such structure */ timing_t *timing_get(const char *name); #ifdef __cplusplus } #endif #endif <file_sep>/archive_s3/s3.0/src/libmain/wnet2pnet.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * wnet2pnet.h -- Generic phone-net data structure, build from a wordnet data structure. * * * HISTORY * * 10-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _LIBMAIN_PNET_H_ #define _LIBMAIN_PNET_H_ #include <libutil/libutil.h> #include "s3types.h" #include "mdef.h" #include "dict.h" #include "hmm.h" #include "wnet.h" /* * Phonetic equivalent representation of wordnet. Another DAG with phone nodes and links. */ typedef struct pnode_s { s3wid_t wid; /* Parent word-id for this HMM node */ int32 pos; /* Phone position within word */ hmm_t hmm; /* Search HMM structure */ glist_t succ; /* List of links (plink_t) to successor phone nodes */ } pnode_t; typedef struct plink_s { pnode_t *dst; /* Target node for a link */ } plink_t; /* * Build a phone HMM net for the given word net. The given wnet has two dummy anchors * (wstart and wend) designating the start and end of the wordnet. They are ignored in * the phone net creation. Similar dummy anchors are added to the phone net instead. * Return value: glist of pnode_t in the constructed phone net. */ glist_t wnet2pnet (mdef_t *mdef, /* In: Model definition for building phone net */ dict_t *dict, /* In: Pronunciation dictionary */ glist_t wnet, /* In: Word net */ wnode_t *wstart, /* In: Dummy anchors at the start and end of the word net; ignored in the phone net */ wnode_t *wend, pnode_t **pstart, /* Out: Dummy anchors at the start and end of the phone net; they should be ignored. Successors to pstart are the real start of the net, and predecessors to pend are the real end. */ pnode_t **pend); /* * Free and destroy the given phone net. */ void pnet_free (glist_t pnet); /* * Flag the set of senones in the given pnode list plist in the given bitvector. */ void pnet_set_senactive (mdef_t *m, /* In: HMM model definition */ glist_t plist, /* In: List of pnodes active */ bitvec_t active, /* Out: Bit-vector for the active flags; active[i] set iff senone i is active */ int32 n_sen); /* In: Size of bit-vector */ /* * Dump for debugging. */ void pnet_dump (mdef_t *mdef, dict_t *dict, glist_t pnet); #endif <file_sep>/SphinxTrain/src/libs/libio/swap.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: swap.c * * Description: * Reads the byte-order magic number from a binary file header. * Determines whether swapping should be done given the value. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/bo_magic.h> #include <s3/swap.h> #include <s3/fread_retry.h> #include <assert.h> #include <string.h> int32 swap_stamp(FILE *fp) { uint32 magic = BYTE_ORDER_MAGIC; if (fwrite(&magic, sizeof(uint32), 1, fp) != 1) { E_ERROR("error while writing bo_magic\n"); return S3_ERROR; } return S3_SUCCESS; } int32 swap_check(FILE *fp) { uint32 magic; uint32 ret = -1; if (fread_retry(&magic, sizeof(uint32), 1, fp) != 1) { E_ERROR("error while reading bo_magic\n"); ret = -1; return ret; } if (magic != BYTE_ORDER_MAGIC) { /* either need to swap or got bogus magic number */ SWAP_INT32(&magic); if (magic == BYTE_ORDER_MAGIC) { ret = 1; } else { /* could not get magic number by swapping, so it is bogus */ E_ERROR("Expected to read 0x%x (or byte permuted) byte order indicator. Instead read 0x%x\n", BYTE_ORDER_MAGIC, SWAP_INT32(&magic)); ret = -1; } } else { /* BYTE_ORDER_MAGIC was read; so no need to swap */ ret = 0; } return ret; } int swap_little_endian() { uint32 l; char *c; l = 1; c = (char *)&l; if (*c) { return TRUE; } else { return FALSE; } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/misc/cb.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * cb.c -- Printing and looking at S3-format codebooks in various ways. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 21-Aug-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. * */ /* * To compile: * cc -O2 -o cb -I$S3/include -I$S3/src -L$S3/lib/alpha cb.c -lutil -lio * where, $S3 is the s3 root directory. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <libutil/libutil.h> #include <libio/libio.h> /* * gauden_param_read taken from s3/src/libfbs. */ #define GAUDEN_PARAM_VERSION "0.1" static int32 gauden_param_read(float32 *****out_param, int32 *out_n_mgau, int32 *out_n_feat, int32 *out_n_density, int32 **out_veclen, const char *file_name) { char version[1024], tmp; FILE *fp; int32 i, j, k, l, blk, n; int32 n_mgau; int32 n_feat; int32 n_density; int32 *veclen; int32 needs_reorder; float32 ****out; float32 *buf; fprintf (stderr, "Reading mixture gaussian parameter: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); if (fscanf(fp, "%s", version) != 1) E_FATAL("Unable to read version id\n"); if (strcmp(version, GAUDEN_PARAM_VERSION) != 0) E_FATAL("Version mismatch: %s, expecting %s\n", version, GAUDEN_PARAM_VERSION); if (bcomment_read(fp) != S3_SUCCESS) E_FATAL("bcomment_read() failed\n"); if ((needs_reorder = swap_check(fp)) < 0) E_FATAL("swap_check() failed\n"); /* #Codebooks */ if (fread_retry(&n_mgau, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #codebooks\n"); if (needs_reorder) { SWAP_INT32(&n_mgau); } *out_n_mgau = n_mgau; /* #Features/codebook */ if (fread_retry(&n_feat, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #features/codebook\n"); if (needs_reorder) { SWAP_INT32(&n_feat); } *out_n_feat = n_feat; /* #Gaussian densities/feature in each codebook */ if (fread_retry(&n_density, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #densities/codebook-feature\n"); if (needs_reorder) { SWAP_INT32(&n_density); } *out_n_density = n_density; /* #Dimensions in each feature stream */ veclen = ckd_calloc(n_feat, sizeof(uint32)); *out_veclen = veclen; if (fread_retry(veclen, sizeof(uint32), n_feat, fp) != n_feat) E_FATAL("Error reading feature vector lengths\n"); if (needs_reorder) { for (i = 0; i < n_feat; i++) SWAP_INT32(&veclen[i]); } /* blk = total vector length of all feature streams */ for (i = 0, blk = 0; i < n_feat; i++) blk += veclen[i]; /* #Floats to follow; for the ENTIRE SET of CODEBOOKS */ if (fread_retry(&n, sizeof(uint32), 1, fp) != 1) E_FATAL("Error reading #floats\n"); if (needs_reorder) { SWAP_INT32(&n); } assert(n == n_mgau * n_density * blk); /* Allocate memory for mixture gaussian densities */ out = (float32 ****) ckd_calloc_3d (n_mgau, n_feat, n_density, sizeof(float32 *)); buf = (float32 *) ckd_calloc (n, sizeof(float)); for (i = 0, l = 0; i < n_mgau; i++) { for (j = 0; j < n_feat; j++) { for (k = 0; k < n_density; k++) { out[i][j][k] = &buf[l]; l += veclen[j]; } } } /* Read mixture gaussian densities data */ if (fread_retry (buf, sizeof(float32), n, fp) != n) E_FATAL("Error reading gaussian data\n"); if (needs_reorder) for (i = 0; i < n; i++) SWAP_FLOAT32(&buf[i]); if (fread (&tmp, 1, 1, fp) == 1) E_WARN("Non-empty file beyond end of data\n"); *out_param = out; fclose(fp); return 0; } /* * Read mean and variance S3-format files and cluster them as follows: * assume single feature vector * for each dimension of feature vector { * create list of <mean,var> pairs in the entire codebook set (for that dimension); * // HACK!! 0 vectors omitted from the above list * VQ cluster this list into the given number of vqsize points; * replace codebook entries with nearest clustered values (for that dimension); * // HACK!! 0 vectors remain untouched * } * write remapped codebooks to files "mean-vq" and "var-vq"; */ main (int32 argc, char *argv[]) { float32 ****mean, ****var; int32 n_cb, n_feat, n_den, *featlen; FILE *fp; int32 i, c, w, dim; if ((argc < 4) || (sscanf (argv[3], "%d", &dim) != 1)) E_FATAL("Usage: %s meanfile varfile dimension\n", argv[0]); gauden_param_read (&mean, &n_cb, &n_feat, &n_den, &featlen, argv[1]); fprintf (stderr, "%s: %d x %d x %d x %d\n", argv[2], n_cb, n_feat, n_den, featlen[0]); gauden_param_read (&var, &n_cb, &n_feat, &n_den, &featlen, argv[2]); fprintf (stderr, "%s: %d x %d x %d x %d\n", argv[2], n_cb, n_feat, n_den, featlen[0]); assert (n_feat == 1); for (c = 0; c < n_cb; c++) { for (w = 0; w < n_den; w++) { /* printf ("%5d %3d %12.5e %12.5e\n", c, w, mean[c][0][w][dim], var[c][0][w][dim]); */ printf ("%12.5e %12.5e\n", mean[c][0][w][dim], var[c][0][w][dim]); } } exit(0); } <file_sep>/archive_s3/s3.0/pgm/timealign/align.c /* * align.c -- Time alignment module. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 11-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * The main time-alignment routines. Actually, this module is quite generic since it is * basically performing a Viterbi search over a generic phone net. The only thing specific to * time-alignment is the amount of backtrace information gathered during the search: at the * finest granularity of states traversed per frame. So with a little effort we could perhaps * build a generic "pnet_search" out of this module... * * The 32-bit IDs in the Viterbi history constructed by the search are built as follows: * 20-bit word-id, * 8-bit phone-position within word, * 4-bit state-position within phone. * This places somewhat smaller limits on the dictionary and HMM sizes than might be otherwise * available, but it is still quite sufficient for the foreseeable future. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include <libio/libio.h> #include <libmain/hyp.h> #include "align.h" /* * Convert a <word-id, phone-position, state-position> triple to a Viterbi history ID. * ppos is the phone position within the word pronunciation. * spos is the state position within the phone HMM. */ #define VITHIST_WIDSIZE 20 /* #Bits for word-id */ #define VITHIST_PPOSSIZE 8 /* #Bits for phone-position */ #define VITHIST_SPOSSIZE 4 /* #Bits for state-position */ #define VITHIST_ID(wid,ppos,spos) ( ((wid)<<12) | ((ppos)<<4) | (spos) ) /* Extract the word-id from a Viterbi history ID */ #define VITHIST_ID2WID(vid) ( ((vid) >> 12) & 0x000fffff ) /* Extract the phone-position from a Viterbi history ID */ #define VITHIST_ID2PPOS(vid) ( ((vid) >> 4) & 0x000000ff ) /* Extract the state-position from a Viterbi history ID */ #define VITHIST_ID2SPOS(vid) ( (vid) & 0x0000000f ) int32 align_start (kb_t *kb, char *uttid) { gnode_t *gn; pnode_t *pn; plink_t *pl; kb->pactive = NULL; kb->hist = NULL; if (dict_size(kb->dict) >= (1 << VITHIST_WIDSIZE)) E_FATAL("Cannot handle dictionary size >= %d\n", (1 << VITHIST_WIDSIZE)); if (mdef_n_ciphone(kb->mdef) >= (1 << VITHIST_PPOSSIZE)) E_FATAL("Cannot handle #ciphones >= %d\n", (1 << VITHIST_PPOSSIZE)); if (mdef_n_emit_state(kb->mdef) >= (1 << VITHIST_SPOSSIZE)) E_FATAL("Cannot handle #HMMstates >= %d\n", (1 << VITHIST_SPOSSIZE)); /* Initialize all HMMs to the inactive state */ for (gn = kb->pnet; gn; gn = gn->next) { pn = (pnode_t *) gnode_ptr(gn); hmm_clear (kb->mdef, &(pn->hmm)); } /* Activate the initial HMMs, and mark active senones */ for (gn = kb->pstart->succ; gn; gn = gn->next) { pl = (plink_t *) gnode_ptr(gn); pn = pl->dst; assert (pn->hmm.active == -1); /* Check against multiple activation */ hmm_enter (&(pn->hmm), 0, 0, NULL, 0); kb->pactive = glist_add_ptr (kb->pactive, (void *)pn); } /* Mark the active senones */ pnet_set_senactive (kb->mdef, kb->pactive, kb->am->sen_active, kb->am->sen->n_sen); return 0; } int32 align_frame (kb_t *kb, int32 beam, int32 frm, char *uttid) { gnode_t *gn, *gn2; pnode_t *pn, *pn2; int32 bestscore, hmmscore, thresh; glist_t cur_active, next_active; hmm_t *hmm, *hmm2; plink_t *pl; int32 i; int32 vid; cur_active = kb->pactive; /* Step the active HMMs through this frame */ bestscore = (int32)0x80000000; for (gn = cur_active; gn; gn = gn->next) { pn = (pnode_t *) gnode_ptr(gn); assert (pn->hmm.active == frm); hmmscore = hmm_vit_eval (kb->mdef, kb->tmat, &(pn->hmm), kb->am->senscr); if (bestscore < hmmscore) bestscore = hmmscore; } if (bestscore <= LOGPROB_ZERO) { E_ERROR("%s: Best HMM score (%d) underflowed at frame %d\n", uttid, bestscore, frm); glist_free (cur_active); kb->pactive = NULL; return -1; } if (bestscore > 0) E_WARN("%s: Best HMM score > 0 (%d) at frame %d; overflow??\n", uttid, bestscore, frm); /* Note current state scores; propagate scores across HMMs; prune poor HMMs */ thresh = bestscore + beam; next_active = NULL; for (gn = cur_active; gn; gn = gn->next) { pn = (pnode_t *) gnode_ptr(gn); hmm = &(pn->hmm); if (hmm->bestscore < thresh) { if (hmm->active <= frm) /* Not activated for the next frame */ hmm_clear (kb->mdef, hmm); } else { /* Note Viterbi history for each state */ for (i = 0; i < kb->mdef->n_emit_state; i++) { if (hmm->state[i].score >= thresh) { vid = VITHIST_ID(pn->wid, pn->pos, i); kb->hist = vithist_append (kb->hist, vid, frm, hmm->state[i].score, hmm->state[i].hist, NULL); /* * Update the exit history with the history node just created * (for propagation). */ hmm->state[i].hist = (vithist_t *) gnode_ptr(kb->hist); } } /* Transition to exit state, and note its Viterbi history */ hmm_vit_eval_exit (kb->mdef, kb->tmat, &(pn->hmm)); if (hmm->out.score >= thresh) { vid = VITHIST_ID(pn->wid, pn->pos, kb->mdef->n_emit_state); kb->hist = vithist_append (kb->hist, vid, frm, hmm->out.score, hmm->out.hist, NULL); /* * Update the exit history with the history node just created * (for propagation). */ hmm->out.hist = (vithist_t *) gnode_ptr(kb->hist); } /* Activate for next frame if not already activated */ if (hmm->active <= frm) { next_active = glist_add_ptr (next_active, (void *)pn); hmm->active = frm+1; } /* Transition to successor pnodes if exited */ if (hmm->out.score >= thresh) { for (gn2 = pn->succ; gn2; gn2 = gn2->next) { pl = (plink_t *) gnode_ptr(gn2); pn2 = pl->dst; hmm2 = &(pn2->hmm); if (hmm_vit_trans (hmm, hmm2, frm+1)) next_active = glist_add_ptr (next_active, (void *)pn2); } } } } glist_free (cur_active); kb->pactive = next_active; /* Mark the active senones */ pnet_set_senactive (kb->mdef, next_active, kb->am->sen_active, kb->am->sen->n_sen); return 0; } void align_hypfree (glist_t hyp) { glist_myfree (hyp, sizeof(hyp_t)); } glist_t align_end (kb_t *kb, int32 frm, char *uttid) { hmm_t *hmm; glist_t hyplist; glist_free (kb->pactive); kb->pactive = NULL; hmm = &(kb->pend->hmm); if (hmm->active == frm) hyplist = vithist_backtrace (hmm->in.hist, kb->am->senscale); else hyplist = NULL; glist_myfree (kb->hist, sizeof(vithist_t)); kb->hist = NULL; return hyplist; } void align_write_s2stseg (kb_t *kb, glist_t hyp, char *file, char *uttid) { FILE *fp; static int32 byterev = -1; /* Whether to byte reverse output data */ int32 k; gnode_t *gn; hyp_t *h; int32 wid, ppos, spos, phonebegin; int16 s2_info; if (byterev < 0) { if ((byterev = host_endian()) < 0) { E_ERROR("Couldn't figure out host byte ordering, using native mode\n"); byterev = 0; } } /* Write #frames; this should be the end-frame of the last hypnode +1 */ if ((gn = glist_tail (hyp)) == NULL) { E_ERROR("%s: Empty hypothesis\n", uttid); return; } h = (hyp_t *) gnode_ptr(gn); k = h->ef + 1; if ((fp = fopen(file, "wb")) == NULL) { E_ERROR("%s: fopen(%s,wb) failed\n", uttid, file); return; } if (byterev) SWAP_INT32(&k); if (fwrite (&k, sizeof(int32), 1, fp) != 1) goto write_error; /* Write state info for each frame */ phonebegin = 1; for (gn = hyp; gn; gn = gn->next) { h = (hyp_t *) gnode_ptr(gn); wid = VITHIST_ID2WID(h->id); ppos = VITHIST_ID2PPOS(h->id); spos = VITHIST_ID2SPOS(h->id); if (spos == kb->mdef->n_emit_state) phonebegin = 1; else { s2_info = dict_pron(kb->dict, wid, ppos) * kb->mdef->n_emit_state + spos; if (phonebegin) s2_info |= 0x8000; if (byterev) SWAP_INT16(&s2_info); if (fwrite (&s2_info, sizeof(int16), 1, fp) != 1) goto write_error; phonebegin = 0; } } fclose (fp); return; write_error: E_ERROR("%s: fwrite(%s) failed\n", uttid, file); fclose (fp); } glist_t align_st2wdseg (kb_t *kb, glist_t stseg) { glist_t wdseg; int32 wid, ppos, spos, wordbegin; gnode_t *gn; hyp_t *h, *wh; wdseg = NULL; wordbegin = 1; for (gn = stseg; gn; gn = gn->next) { h = (hyp_t *) gnode_ptr(gn); wid = VITHIST_ID2WID(h->id); ppos = VITHIST_ID2PPOS(h->id); spos = VITHIST_ID2SPOS(h->id); if (wordbegin) { wh = (hyp_t *) mymalloc (sizeof(hyp_t)); wh->id = wid; wh->sf = h->sf; wh->ascr = h->ascr; wh->lscr = 0; wdseg = glist_add_ptr (wdseg, (void *) wh); wordbegin = 0; } else { assert (wh->id == wid); wh->ascr += h->ascr; } /* If at non-emitting state of the final phone for this word, end of word */ if ((spos == kb->mdef->n_emit_state) && ((ppos+1) == dict_pronlen(kb->dict,wid))) { wh->ef = h->ef; wh->scr = wh->ascr; wordbegin = 1; } } assert (wordbegin); /* The word segmentation list is actually reversed; get it right */ wdseg = glist_reverse (wdseg); return wdseg; } void align_write_wdseg (kb_t *kb, glist_t wdseg, char *file, char *uttid) { FILE *fp; int32 uttscore; gnode_t *gn; hyp_t *h; if ((fp = fopen(file, "w")) == NULL) { E_ERROR("%s: fopen(%s,w) failed; writing wdseg to stdout\n", uttid, file); fp = stdout; } if (fp == stdout) fprintf (fp, "WD:%s>", uttid); fprintf (fp, "\t%5s %5s %10s %s\n", "SFrm", "EFrm", "SegAScr", "Word"); uttscore = 0; for (gn = wdseg; gn; gn = gn->next) { h = (hyp_t *) gnode_ptr(gn); if (fp == stdout) fprintf (fp, "wd:%s>", uttid); fprintf (fp, "\t%5d %5d %10d %s\n", h->sf, h->ef, h->ascr, dict_wordstr (kb->dict, (s3wid_t)h->id)); uttscore += h->ascr; } if (fp == stdout) fprintf (fp, "WD:%s>", uttid); fprintf (fp, " Total score: %11d\n", uttscore); if (fp != stdout) fclose (fp); else { fprintf (fp, "\n"); fflush (fp); } } void align_write_outsent (kb_t *kb, glist_t wdseg, FILE *fp, char *uttid) { gnode_t *gn; hyp_t *h; for (gn = wdseg; gn; gn = gn->next) { h = (hyp_t *) gnode_ptr(gn); fprintf (fp, "%s ", dict_wordstr (kb->dict, (s3wid_t)h->id)); } fprintf (fp, "(%s)\n", uttid); fflush (fp); } <file_sep>/sphinx2/src/libsphinx2ad/Makefile.am # libsphinx2ad: Audio Device interface for Sphinx-II lib_LTLIBRARIES = libsphinx2ad.la libsphinx2ad_la_LDFLAGS = -version-info 0:6:0 libsphinx2ad_la_SOURCES = cont_ad_base.c EXTRA_libsphinx2ad_la_SOURCES = ad_base.c \ ad_oss.c \ ad_oss_bsd.c \ ad_alsa.c \ ad_osf.c \ ad_irix.c \ ad_sunos.c \ audio_utils_sunos.c \ play_win32.c \ rec_win32.c \ mulaw_base.c noinst_HEADERS = audio_utils_sunos.h libsphinx2ad_la_DEPENDENCIES = @ad_files@ libsphinx2ad_la_LIBADD = @ad_files@ @ad_libs@ INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include <file_sep>/archive_s3/s3/src/tests/rm1/Makefile # ==================================================================== # # Sphinx III # # ==================================================================== TOP=`(cd ../../..; pwd)` DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = # LIVEDECSRCS = # MAINSRCS = # OTHERSRCS = main.c # LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile LIBNAME= tests BINDIR = $(TOP)/bin/$(MACHINE) ifeq ($(MODE),quick) MODEAFFIX = _quick CTLFILE = rm1_quick.ctl REFFILE = rm1_quick.ref else MODE = CTLFILE = rm1.ctl REFFILE = rm1.ref endif rm1_unigram: rm -f gmake-rm1_unigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-lmfn /lab/speech/sphinx4/data/rm1/lists/RM.2845.unigram.arpa.DMP" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-langwt 13" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-beam 1e-120" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-nwbeam 1e-60" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-ctlfn $(CTLFILE)" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-matchfn rm1_unigram$(MODEAFFIX).match" >> ARGS.rm1_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.rm1_unigram$(MODEAFFIX) > gmake-rm1_unigram$(MODEAFFIX).results $(BINDIR)/align -ref $(REFFILE) -hyp rm1_unigram$(MODEAFFIX).match > rm1_unigram$(MODEAFFIX).align rm1_flat_unigram: rm -f gmake-rm1_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-lmfn /lab/speech/sphinx4/data/rm1/lists/RM.unigram.arpa.DMP" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-langwt 8" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-beam 1e-120" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-nwbeam 1e-40" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-ctlfn $(CTLFILE)" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-matchfn rm1_flat_unigram$(MODEAFFIX).match" >> ARGS.rm1_flat_unigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.rm1_flat_unigram$(MODEAFFIX) > gmake-rm1_flat_unigram$(MODEAFFIX).results $(BINDIR)/align -ref $(REFFILE) -hyp rm1_flat_unigram$(MODEAFFIX).match > rm1_flat_unigram$(MODEAFFIX).align rm1_bigram: rm -f gmake-rm1_bigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-lmfn /lab/speech/sphinx4/data/rm1/lists/RM.2845.bigram.arpa.DMP" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-langwt 17" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-beam 1e-140" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-nwbeam 1e-100" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-ctlfn $(CTLFILE)" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-matchfn rm1_bigram$(MODEAFFIX).match" >> ARGS.rm1_bigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.rm1_bigram$(MODEAFFIX) > gmake-rm1_bigram$(MODEAFFIX).results $(BINDIR)/align -ref $(REFFILE) -hyp rm1_bigram$(MODEAFFIX).match > rm1_bigram$(MODEAFFIX).align rm1_trigram: rm -f gmake-rm1_trigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-lmfn /lab/speech/sphinx4/data/rm1/lists/RM.2845.trigram.arpa.DMP" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-langwt 27" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-beam 1e-160" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-nwbeam 1e-120" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-ctlfn $(CTLFILE)" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-matchfn rm1_trigram$(MODEAFFIX).match" >> ARGS.rm1_trigram$(MODEAFFIX) $(BINDIR)/s3decode-anytopo ARGS.rm1_trigram$(MODEAFFIX) > gmake-rm1_trigram$(MODEAFFIX).results $(BINDIR)/align -ref $(REFFILE) -hyp rm1_trigram$(MODEAFFIX).match > rm1_trigram$(MODEAFFIX).align <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/heap.h /* ==================================================================== * Copyright (c) 2000 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* ------------------ HEAP.H ---------------------*/ #ifndef HEAP_H #define HEAP_H #include <stdlib.h> #include <s3/prim_type.h> #define MAXSWAPS 1000 /* Dont expect more than a 1000 swaps */ typedef struct heapelement_t { char *basephone; char *leftcontext; char *rightcontext; char *wordposition; int32 count; int32 heapid; } heapelement_t; #define PARENTID(X) ((int32)((X)-1)/2) #define LEFTCHILD(X) ((X)*2+1) #define RIGHTCHILD(X) ((X)*2+2) #define SWAP(A,B) {heapelement_t *tmp; int32 x,y; \ x = (A)->heapid; y = (B)->heapid; \ tmp = (A); A = B; B = tmp; \ (A)->heapid = x; (B)->heapid = y;} int32 insert (heapelement_t ***heap, int32 heapsize, heapelement_t *newelement); heapelement_t *yanktop (heapelement_t ***heap, int32 heapsize, int32 *newsize); void free_heap (heapelement_t **heap, int32 heapsize); void free_heapelement (heapelement_t *heapel); #endif <file_sep>/archive_s3/s3.0/src/libmain/gauden.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * gauden.c -- gaussian density module. * * * HISTORY * * 11-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added det_varinv argument to gauden_init(). * * 09-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added gauden_cbmean0(). * * 19-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started, based on original S3 version. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libmisc/libmisc.h> #include "gauden.h" #if _GAUDEN_TEST_ #include <libfeat/libfeat.h> #include "cmn.h" #include "agc.h" #endif #define GAUDEN_PARAM_VERSION "1.0" #undef M_PI #define M_PI 3.1415926535897932385e0 #define GAUDEN_MEAN 1 #define GAUDEN_VAR 2 #if _GAUDEN_TEST_ static void gauden_dump (const gauden_t *g) { int32 c, f, d, i; mgau_t *mg; for (c = 0; c < g->n_mgau; c++) { for (f = 0; f < g->n_feat; f++) { mg = &(g->mgau[c][f]); E_INFO ("Codebook %d, Feature %d (%dx%d):\n", c, f, mg->n_mean, g->featlen[f]); if (mg->n_var == mg->n_mean) { for (d = 0; d < mg->n_mean; d++) { printf ("m[%3d]", d); for (i = 0; i < g->featlen[f]; i++) printf (" %7.4f", mg->mean[d][i]); printf ("\n"); printf ("v[%3d]", d); for (i = 0; i < g->featlen[f]; i++) printf (" %7.4f", mg->var[d][i]); printf (" det %7.4f\n", mg->det[d]); } } else { for (d = 0; d < mg->n_mean; d++) { printf ("m[%3d]", d); for (i = 0; i < g->featlen[f]; i++) printf (" %7.4f", mg->mean[d][i]); printf ("\n"); } if (mg->n_var == 1) { printf ("v[%3d]", 0); for (i = 0; i < g->featlen[f]; i++) printf (" %7.4f", mg->var[0][i]); printf (" det %7.4f\n", mg->det[0]); } } printf ("\n"); fflush (stdout); } } } #endif static int32 chk_cbmean0 (gauden_t *g, int32 m, int32 f) { int32 c; for (c = 0; (c < gauden_n_mean(g, m, f)) && vector_is_zero(g->mgau[m][f].mean[c], g->featlen[f]); c++); return (c == gauden_n_mean(g, m, f)); /* TRUE iff all vectors are 0.0 */ } static void gauden_cbmean0 (gauden_t *g) { int32 m, f, n; n = 0; for (m = 0; m < gauden_n_mgau(g); m++) { for (f = 0; f < g->n_feat; f++) { if (chk_cbmean0 (g, m, f)) { g->mgau[m][f].cb0 = 1; n++; } else g->mgau[m][f].cb0 = 0; } } E_INFO("%d codebook means are all 0\n", n); } static void gauden_var_floor (gauden_t *g, float64 floor) { int32 i, m, f, d, flen; float32 *var; E_INFO("Applying variance floor\n"); for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { flen = g->featlen[f]; for (d = 0; d < g->mgau[m][f].n_var; d++) { var = g->mgau[m][f].var[d]; for (i = 0; i < flen; i++) { if (var[i] < floor) var[i] = (float32) floor; } } } } } void gauden_var_nzvec_floor (gauden_t *g, float64 floor) { int32 i, m, f, d, flen; float32 *var; E_INFO("Applying variance floor\n"); for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { flen = g->featlen[f]; for (d = 0; d < g->mgau[m][f].n_var; d++) { var = g->mgau[m][f].var[d]; if (! vector_is_zero(var, flen)) { for (i = 0; i < flen; i++) { if (var[i] < floor) var[i] = (float32) floor; } } } } } } /* * At the moment, S3 models have the same #means in each codebook and 1 var/mean. * If g->mgau already allocated (non-NULL) simply verify the various dimensions. */ static int32 gauden_param_read(const char *file_name, gauden_t *g, int32 type) { char tmp; FILE *fp; int32 i, j, k, n, blk; int32 n_mgau; int32 n_feat; int32 n_density; int32 *veclen; int32 byteswap, chksum_present; float32 *buf; vector_t *pbuf; char **argname, **argval; uint32 chksum; E_INFO("Reading mixture gaussian parameter: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], GAUDEN_PARAM_VERSION) != 0) E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], GAUDEN_PARAM_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* #Codebooks */ if (bio_fread (&n_mgau, sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#codebooks) failed\n", file_name); if (n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, n_mgau, MAX_MGAUID); if (g->mgau && (n_mgau != g->n_mgau)) E_FATAL("#Codebooks conflict: %d allocated, %d in file\n", g->n_mgau, n_mgau); g->n_mgau = n_mgau; /* #Features/codebook */ if (bio_fread (&n_feat, sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#features) failed\n", file_name); if (g->mgau && (n_feat != g->n_feat)) E_FATAL("#Features conflict: %d allocated, %d in file\n", g->n_feat, n_feat); g->n_feat = n_feat; /* #Gaussian densities/feature in each codebook */ if (bio_fread (&n_density, sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#density/codebook) failed\n", file_name); if (g->mgau && (n_density != g->mgau[0][0].n_mean)) E_FATAL("#Densities conflict: %d allocated, %d in file\n", g->mgau[0][0].n_mean, n_density); /* Vector length of each feature stream */ veclen = ckd_calloc(n_feat, sizeof(uint32)); if (bio_fread (veclen, sizeof(int32), n_feat, fp, byteswap, &chksum) != n_feat) E_FATAL("fread(%s) (feature-lengths) failed\n", file_name); if (g->featlen) { /* Verify feature lengths */ for (i = 0; i < n_feat; i++) if (veclen[i] != g->featlen[i]) E_FATAL("Feature[%d] length conflict: %d allocated, %d in file\n", i, g->featlen[i], veclen[i]); ckd_free (veclen); veclen = g->featlen; } else g->featlen = veclen; /* blk = total vector length of all feature streams */ for (i = 0, blk = 0; i < n_feat; i++) blk += veclen[i]; /* #Floats to follow; for the ENTIRE SET of CODEBOOKS */ if (bio_fread (&n, sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (total #floats) failed\n", file_name); if (n != n_mgau * n_density * blk) { E_FATAL("%s: #float32s(%d) doesn't match dimensions: %d x %d x %d\n", file_name, n, n_mgau, n_density, blk); } /* Allocate memory for mixture gaussian densities if not already allocated */ if (! g->mgau) { g->mgau = (mgau_t **) ckd_calloc_2d (n_mgau, n_feat, sizeof(mgau_t)); g->max_n_mean = n_density; } else assert (g->max_n_mean == n_density); if (type == GAUDEN_MEAN) { if (! g->mgau[0][0].mean) { /* Means can be reloaded multiple times */ buf = (float32 *) ckd_calloc (n, sizeof(float)); pbuf = (vector_t *) ckd_calloc (n_mgau * n_feat * n_density, sizeof(vector_t)); for (i = 0; i < n_mgau; i++) { for (j = 0; j < n_feat; j++) { g->mgau[i][j].mean = pbuf; g->mgau[i][j].n_mean = n_density; for (k = 0; k < n_density; k++) { g->mgau[i][j].mean[k] = buf; buf += veclen[j]; } pbuf += n_density; } } } else assert (g->mgau[0][0].n_mean == n_density); buf = g->mgau[0][0].mean[0]; } else { assert (type == GAUDEN_VAR); assert (! g->mgau[0][0].var); /* Can only load variance once */ buf = (float32 *) ckd_calloc (n, sizeof(float)); pbuf = (vector_t *) ckd_calloc (n_mgau * n_feat * n_density, sizeof(vector_t)); for (i = 0; i < n_mgau; i++) { for (j = 0; j < n_feat; j++) { g->mgau[i][j].var = pbuf; g->mgau[i][j].n_var = n_density; for (k = 0; k < n_density; k++) { g->mgau[i][j].var[k] = buf; buf += veclen[j]; } pbuf += n_density; } } buf = g->mgau[0][0].var[0]; } /* Read mixture gaussian densities data */ if (bio_fread (buf, sizeof(float32), n, fp, byteswap, &chksum) != n) E_FATAL("fread(%s) (densitydata) failed\n", file_name); if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&tmp, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("%d codebook, %d feature, size", n_mgau, n_feat); for (i = 0; i < n_feat; i++) fprintf (stderr, " %dx%d", n_density, veclen[i]); fprintf (stderr, "\n"); if (type == GAUDEN_MEAN) gauden_cbmean0 (g); fflush (stderr); return 0; } /* * Some of the gaussian density computation can be carried out in advance: * log(determinant) calculation, * 1/(2*var) in the exponent, * NOTE; The density computation is performed in log domain. */ static int32 gauden_dist_precompute (gauden_t *g) { int32 i, m, n, f, d, flen; float32 *var, *det; E_INFO("Precomputing co-variance determinants, variance reciprocals\n"); /* Allocate space for determinants */ assert (! g->mgau[0][0].det); n = 0; for (m = 0; m < g->n_mgau; m++) for (f = 0; f < g->n_feat; f++) n += g->mgau[m][f].n_var; det = (float32 *) ckd_calloc (n, sizeof(float32)); for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { g->mgau[m][f].det = det; det += g->mgau[m][f].n_var; } } /* Precompute invariant portion of density function */ for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { flen = g->featlen[f]; det = g->mgau[m][f].det; /* Determinants for all variance vectors in g->mgau[m][f] */ for (d = 0; d < g->mgau[m][f].n_var; d++) { var = g->mgau[m][f].var[d]; det[d] = (float32) 0.0; for (i = 0; i < flen; i++) { det[d] += (float32) (log(var[i])); /* Precompute this part of the exponential */ var[i] = (float32) (1.0 / (var[i] * 2.0)); } /* 2 pi */ det[d] += (float32) (flen * log(2.0 * M_PI)); /* Sqrt */ det[d] *= (float32) 0.5; } } } return 0; } /* At the moment, S3 models have the same #means in each codebook and 1 var/mean */ gauden_t *gauden_init (char *meanfile, char *varfile, float64 varfloor, int32 det_varinv) { gauden_t *g; assert (meanfile != NULL); assert (varfile != NULL); assert (varfloor >= 0.0); g = (gauden_t *) ckd_calloc (1, sizeof(gauden_t)); g->min_density = logs3_to_log (LOGPROB_ZERO); /* Floor for density values */ /* Read means and (diagonal) variances for all mixture gaussians */ gauden_param_read (meanfile, g, GAUDEN_MEAN); gauden_param_read (varfile, g, GAUDEN_VAR); gauden_var_floor (g, varfloor); if (det_varinv) gauden_dist_precompute (g); return g; } int32 gauden_mean_reload (gauden_t *g, char *meanfile) { assert ((g->mgau != NULL) && (g->mgau[0][0].mean != NULL)); gauden_param_read (meanfile, g, GAUDEN_MEAN); return 0; } int32 gauden_dist (gauden_t *g, int32 m, int32 f, vector_t obs, int32 *dist) { int32 i, d, featlen, n_mean; vector_t m1, m2, v1, v2; float64 dval1, dval2, diff1, diff2; vector_t *mean, *var; float32 *det; assert ((m >= 0) && (m < g->n_mgau)); assert ((f >= 0) && (f < g->n_feat)); featlen = g->featlen[f]; mean = g->mgau[m][f].mean; var = g->mgau[m][f].var; det = g->mgau[m][f].det; n_mean = g->mgau[m][f].n_mean; assert (g->mgau[m][f].n_var == n_mean); /* For now n_var==1/0 not handled */ /* Interleave two iterations for speed */ for (d = 0; d < n_mean-1; d += 2) { m1 = mean[d]; m2 = mean[d+1]; v1 = var[d]; v2 = var[d+1]; dval1 = det[d]; dval2 = det[d+1]; for (i = 0; i < featlen; i++) { diff1 = obs[i] - m1[i]; dval1 += diff1 * diff1 * v1[i]; diff2 = obs[i] - m2[i]; dval2 += diff2 * diff2 * v2[i]; } dval1 = -dval1; /* log(numerator) = -log(denominator) */ dval2 = -dval2; if (dval1 < g->min_density) /* Floor */ dval1 = g->min_density; if (dval2 < g->min_density) dval2 = g->min_density; dist[d] = log_to_logs3(dval1); dist[d+1] = log_to_logs3(dval2); } /* Remaining iteration if n_mean odd */ if (d < n_mean) { m1 = mean[d]; v1 = var[d]; dval1 = det[d]; for (i = 0; i < featlen; i++) { diff1 = obs[i] - m1[i]; dval1 += diff1 * diff1 * v1[i]; } dval1 = -dval1; if (dval1 < g->min_density) dval1 = g->min_density; dist[d] = log_to_logs3(dval1); } return n_mean; } #if (_GAUDEN_TEST_) main (int32 argc, char *argv[]) { gauden_t *g; float64 flr; float32 **feat, **mfc; int32 i, w, m, f, d, k, nfr, sf, ef, th, max, maxid; int32 *dist; char *cepfile; feat_t *fcb; FILE *fp, *fp2; char str[4096]; if ((argc != 5) && (argc != 7)) E_FATAL("Usage: %s meanfile varfile varfloor cepfile [sf ef]\n", argv[0]); if (sscanf (argv[3], "%lf", &flr) != 1) E_FATAL("Usage: %s meanfile varfile varfloor cepfile [sf ef]\n", argv[0]); cepfile = argv[4]; if (argc > 5) { if ((sscanf (argv[5], "%d", &sf) != 1) || (sscanf (argv[6], "%d", &ef) != 1)) E_FATAL("Usage: %s meanfile varfile varfloor cepfile [sf ef]\n", argv[0]); } else { sf = 0; ef = 10000000; } logs3_init ((float64) 1.0003); fcb = feat_init ("s3_1x39"); feat = feat_vector_alloc(fcb); mfc = (float32 **) ckd_calloc_2d (S3_MAX_FRAMES, feat_cepsize(fcb), sizeof(float32)); th = logs3(1.0e-160); E_INFO("Threshold: %d\n", th); g = gauden_init (argv[1], argv[2], flr, TRUE); #if 0 gauden_dump (g); #endif dist = (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); w = feat_window_size (fcb); nfr = s2mfc_read (cepfile, sf, ef, w, mfc, S3_MAX_FRAMES); E_INFO("%d frames\n", nfr); cmn (mfc, nfr, feat_cepsize(fcb)); agc_max (mfc, nfr); for (i = w; i < nfr-w-1; i++) { if ((fp = fopen("gauden.out", "w")) == NULL) E_FATAL("fopen(gauden.out,w) failed\n"); if ((fp2 = fopen("gauden-top1.out", "w")) == NULL) E_FATAL("fopen(gauden-top1.out,w) failed\n"); fcb->compute_feat (fcb, mfc+i, feat); for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { k = gauden_dist (g, m, f, feat[f], dist); #if 0 printf ("[%5d %3d]", m, f); for (d = 0; d < k; d++) printf (" %11d", dist[d]); printf ("\n"); fflush (stdout); #else maxid = -1; for (d = 0; d < k; d++) { if (dist[d] >= th) fprintf (fp, "%6d %2d %6d %12d\n", i, f, m*g->max_n_mean + d, dist[d]); if ((maxid < 0) || (dist[d] > dist[maxid])) { maxid = d; max = dist[d]; } } if (max >= th) fprintf (fp2, "%6d %2d %6d %12d\n", i, f, m*g->max_n_mean + maxid, max); #endif } } #if 0 #else fclose (fp); fclose (fp2); printf ("[%d %d %d] continue?", i, m, f); scanf ("%s", str); #endif } } #endif <file_sep>/archive_s3/s3.2/src/libutil/unlimit.h /* * unlimit.h -- "unlimit" the memory usage of program. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 03-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Copied from Sphinx-II sources. */ #ifndef _LIBUTIL_UNLIMIT_H_ #define _LIBUTIL_UNLIMIT_H_ /* To remove resource (memory) usage restrictions */ void unlimit ( void ); #endif <file_sep>/SphinxTrain/test/Makefile test: perl ./scripts/test_cp_parm.pl perl ./scripts/test_dict2tri.pl perl ./scripts/test_init_gau.pl perl ./scripts/test_init_gau_lda.pl perl ./scripts/test_printp.pl perl ./scripts/test_prunetree.pl perl ./scripts/test_norm.pl perl ./scripts/test_make_topology.pl perl ./scripts/test_mk_flat.pl perl ./scripts/test_mk_mdef_gen.pl perl ./scripts/test_bugcase1.pl perl ./scripts/test_bugcase2.pl clean: rm -f dict2tri.no_triphones rm -f dict2tri.triphones rm -f printp.mean.txt rm -f printp.mixw.txt rm -f printp.tmat.txt rm -f printp.var.txt<file_sep>/sphinx_fsttools/sphinx_am_fst.cc /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2008 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file sphinx_am_fst.cc * * Build finite-state transducers from Sphinx acoustic model definition files. */ #include <fst/fstlib.h> namespace sphinxbase { #include <cmd_ln.h> #include <hash_table.h> #include <err.h> #include <ckd_alloc.h> #include "mdef.h" }; #include "fstprinter.h" using namespace fst; using namespace sphinxbase; typedef VectorFst<LogArc> LogVectorFst; typedef StdArc::StateId StateId; typedef StdArc::Label Label; static const arg_t args[] = { { "-mdef", ARG_STRING, NULL, "Model definition input file" }, { "-binfst", ARG_STRING, NULL, "Binary FST output file" }, { "-txtfst", ARG_STRING, NULL, "Text FST output file" }, { NULL, 0, NULL, NULL } }; int main(int argc, char *argv[]) { return 0; } <file_sep>/misc_scripts/align_PP.sh #!/bin/bash # collate error and perplexities for a specific run # store results in the specific log folder if [ $# -ne 2 ] ; then echo "usage: align_PP full|speaker <logroot>" ; exit ; fi if [ $1 = "full" ] ; then spkr="" ; elif [ $1 = "speaker" ] ; then spkr="f2caa01 f2uaa01 f3uba01 m2faa01 m2nba01 m3dca01" else echo "first argument must be 'full' or 'speaker'"; exit fi log=$2 map=traveler_1046.pp_map echo "using $map" if [ -e logdir/$log.wer ] ; then rm logdir/$log.wer ; fi if [ -z $spkr ] ; then scripts/split_align_file.pl logdir/$log/$log.align logdir/$log/$log.wer else # extract data from .align file, merge into one file for s in $spkr ; do scripts/split_align_file.pl logdir/${log}_$s/${log}_$s.align logdir/${log}_$s/${log}_$s.wer cat logdir/${log}_$s/${log}_$s.wer >>logdir/$log/$log.wer done fi # merge PP and WER data scripts/merge_wer_PP.pl etc/$map logdir/$log/$log.wer logdir/$log/$log.merged #<file_sep>/archive_s3/s3/src/libmisc/Makefile # ==================================================================== # Copyright (c) 1995-2002 Carnegie Mellon University. All rights # reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # # S3ROOT = /net/alf20/usr/rkm/s3 include $(S3ROOT)/Makefile.defines VPATH = .:.. TARGET = libmisc.a OBJS = corpus.o CFLAGS = $(S3DEBUG) ${$(MACHINE)_CFLAGS} $(TARGET): $(OBJS) ${$(MACHINE)_OBJS} $(AR) crv $@ $? ranlib $@ install: $(TARGET) mv $(TARGET) $(LIBDIR) corpus_test: corpus.c $(CC) -g -D_CORPUS_TEST_=1 $(CFLAGS) -L$(LIBDIR) -o corpus_test corpus.c -lutil -lm clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/util/FinderSelectionPanel.java /* * Created by JFormDesigner on Wed Jun 13 23:41:26 CEST 2007 */ package edu.cmu.sphinx.tools.confdesigner.util; import edu.cmu.sphinx.tools.confdesigner.ConfNode; import javax.swing.*; import javax.swing.border.MatteBorder; import java.awt.*; import java.awt.event.*; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** @author <NAME> */ public class FinderSelectionPanel extends JDialog { private ConfNode selectedNode; Map<String, ConfNode> inverseMap; public FinderSelectionPanel(Frame owner, Collection<ConfNode> matches) { super(owner); initComponents(); DefaultListModel listModel = (DefaultListModel) matchList.getModel(); inverseMap = new HashMap<String, ConfNode>(); for (ConfNode node : matches) { listModel.addElement(node.getInstanceName()); inverseMap.put(node.getInstanceName(), node); } matchList.validate(); setFocusable(true); matchList.setSelectedIndex(0); matchList.requestFocus(); matchList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { selectEntry(); } } }); KeyAdapter keyAdapter = new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { selectNull(); } if (e.getKeyCode() == KeyEvent.VK_ENTER) { selectEntry(); } } }; addKeyListener(keyAdapter); matchList.addKeyListener(keyAdapter); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectEntry(); } }); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectNull(); } }); } private void selectNull() { selectedNode = null; dispose(); } private void selectEntry() { selectedNode = inverseMap.get(matchList.getSelectedValue()); dispose(); } public ConfNode getSelectedNode() { return selectedNode; } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents // Generated using JFormDesigner Open Source Project license - Sphinx-4 (cmusphinx.sourceforge.net/sphinx4/) dialogPane = new JPanel(); contentPanel = new JPanel(); scrollPane1 = new JScrollPane(); matchList = new JList(new DefaultListModel()); buttonBar = new JPanel(); okButton = new JButton(); cancelButton = new JButton(); //======== this ======== Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== dialogPane ======== { dialogPane.setBorder(new MatteBorder(1, 1, 1, 1, Color.black)); dialogPane.setLayout(new BorderLayout()); //======== contentPanel ======== { contentPanel.setLayout(new BorderLayout()); //======== scrollPane1 ======== { //---- matchList ---- matchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane1.setViewportView(matchList); } contentPanel.add(scrollPane1, BorderLayout.CENTER); //======== buttonBar ======== { buttonBar.setBorder(null); buttonBar.setLayout(new GridBagLayout()); ((GridBagLayout) buttonBar.getLayout()).columnWidths = new int[]{0, 85, 80, 0}; ((GridBagLayout) buttonBar.getLayout()).rowHeights = new int[]{0, 0}; ((GridBagLayout) buttonBar.getLayout()).columnWeights = new double[]{1.0, 0.0, 0.0, 1.0E-4}; ((GridBagLayout) buttonBar.getLayout()).rowWeights = new double[]{0.0, 1.0E-4}; //---- okButton ---- okButton.setText("OK"); buttonBar.add(okButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0)); //---- cancelButton ---- cancelButton.setText("Cancel"); buttonBar.add(cancelButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } contentPanel.add(buttonBar, BorderLayout.SOUTH); } dialogPane.add(contentPanel, BorderLayout.CENTER); } contentPane.add(dialogPane, BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables // Generated using JFormDesigner Open Source Project license - Sphinx-4 (cmusphinx.sourceforge.net/sphinx4/) private JPanel dialogPane; private JPanel contentPanel; private JScrollPane scrollPane1; private JList matchList; private JPanel buttonBar; private JButton okButton; private JButton cancelButton; // JFormDesigner - End of variables declaration //GEN-END:variables } <file_sep>/sphinx4/src/apps/edu/cmu/sphinx/demo/raw/RawHelloNGram.java package edu.cmu.sphinx.demo.raw; import edu.cmu.sphinx.recognizer.Recognizer; import edu.cmu.sphinx.frontend.util.AudioFileDataSource; import edu.cmu.sphinx.result.Result; import edu.cmu.sphinx.util.props.ConfigurationManagerUtils; import java.net.URISyntaxException; import java.net.URL; import java.net.MalformedURLException; /** * User: peter * Date: Nov 6, 2009 * Time: 8:49:32 AM * <p/> * Copyright 1999-2004 Carnegie Mellon University. * Portions Copyright 2004 Sun Microsystems, Inc. * Portions Copyright 2004 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. */ public class RawHelloNGram extends RawBase { public static void main(String[] args) throws MalformedURLException, URISyntaxException, ClassNotFoundException { new RawHelloNGram().run(args); } protected CommonConfiguration getConfiguration() throws MalformedURLException, URISyntaxException, ClassNotFoundException { HelloNGramConfiguration config = new HelloNGramConfiguration(); return config; } } <file_sep>/archive_s3/s3.2/src/libutil/str2words.c /* * str2words.c -- Convert a string to an array of words * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 21-Oct-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include "str2words.h" int32 str2words (char *line, char **ptr, int32 max_ptr) { int32 i, n; n = 0; /* #words found so far */ i = 0; /* For scanning through the input string */ for (;;) { /* Skip whitespace before next word */ for (; line[i] && (isspace(line[i])); i++); if (! line[i]) break; if (n >= max_ptr) { /* * Pointer array size insufficient. Restore NULL chars inserted so far * to space chars. Not a perfect restoration, but better than nothing. */ for (; i >= 0; --i) if (line[i] == '\0') line[i] = ' '; return -1; } /* Scan to end of word */ ptr[n++] = line+i; for (; line[i] && (! isspace(line[i])); i++); if (! line[i]) break; line[i++] = '\0'; } return n; } <file_sep>/archive_s3/s3/include/s3.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * s3.h -- Some basic Sphinx-3 related definitions. * * HISTORY * * 30-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created from Eric Thayer's S3 trainer version. */ /********************************************************************* * * $Header$ * * Carnegie Mellon ARPA Speech Group * * Copyright (c) 1995 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: s3.h * * Traceability: * * Description: * * Author: * $Author$ *********************************************************************/ #ifndef S3_H #define S3_H #define S3_SUCCESS 0 #define S3_ERROR -1 #define S3_WARNING -2 /* These belong in libutil/prim_type.h */ #define MAX_IEEE_NORM_POS_FLOAT32 3.4e+38 #define MIN_IEEE_NORM_POS_FLOAT32 1.2e-38 #define MAX_IEEE_NORM_POS_FLOAT64 1.8e+307 #define MIN_IEEE_NORM_POS_FLOAT64 2.2e-308 #define START_WORD "<s>" #define FINISH_WORD "</s>" #define SILENCE_WORD "<sil>" #define SILENCE_CIPHONE "SIL" #define BEGIN_SILENCE_CIPHONE "SILb" #define END_SILENCE_CIPHONE "SILe" #define LOGPROB_ZERO ((int32) 0xc8000000) /* Approx -infinity */ #define RENORM_THRESH ((int32) ((LOGPROB_ZERO)>>1)) /* Bestscore getting close to 0 */ #define S3_MAX_FRAMES 30000 /* Utterance size: 60sec long (@10ms/frame) */ /* The maximum # of states for any given acoustic model */ #define MAX_N_STATE 20 /* The maximum # of attributes associated with any given acoustic model */ #define MAX_N_ATTRIB 5 #ifndef TRUE #define TRUE 1 #define FALSE 0 /* assume that true is never defined w/o false */ #endif #define TYING_NON_EMITTING (0xffffffff) #define TYING_NO_ID (0xffffffff) #endif /* S3_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.2 2002/12/03 23:02:31 egouvea * Updated slow decoder with current working version. * Added copyright notice to Makefiles, *.c and *.h files. * Updated some of the documentation. * * Revision 1.1 2000/04/24 09:39:41 lenzo * s3 import. * * Revision 1.2 1995/10/10 12:25:04 eht * Add TYING_NO_ID to the set of symbolic constants defined. * * Revision 1.1 1995/10/09 21:17:24 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/gauden.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * gauden.h -- gaussian density module. * * * HISTORY * * 11-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added det_varinv argument to gauden_init(). * * 09-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added mgau_t.cb0. * * 19-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started, based on original S3 version. */ #ifndef _LIBMAIN_GAUDEN_H_ #define _LIBMAIN_GAUDEN_H_ #include "s3types.h" #include <libmisc/libmisc.h> /* A single mixture-Gaussian; each has its own size (#means) and variance sharing */ typedef struct { int32 n_mean; /* #mean vectors (#component Gaussians) */ int32 n_var; /* #var vectors; must be == n_mean, 1, or 0, meaning: unshared, shared (within this codebook), or none (euclidean) */ vector_t *mean; /* Mean vectors (centroids) for this mixture density codebook */ vector_t *var; /* Variance vectors */ float32 *det; /* log(sqrt(2*pi*det)) for each variance vector */ int32 cb0; /* TRUE iff all mean vectors in this codebook are 0.0; meaning a potentially uninitialized codebook */ } mgau_t; /* * The set of mixture-Gaussians in an acoustic model. The model consists of a collection * of (possibly shared) CODEBOOKs. Each codebook has one mgau_t for each feature stream. */ typedef struct { int32 n_mgau; /* #codebooks (perhaps n_mgau is a misnomer) */ int32 n_feat; /* #input feature streams */ int32 *featlen; /* Vector length of each feature stream */ mgau_t **mgau; /* mgau[n_mgau][n_feat]; each one can have a different #means */ int32 max_n_mean; /* Max(mgau[][].n_mean); useful for clients to allocate memory */ float64 min_density; /* Gaussian density values in (int32)logs3 domain can underflow; Use this floor value if they underflow */ } gauden_t; /* Some access macros */ #define gauden_n_mgau(g) ((g)->n_mgau) #define gauden_max_n_mean(g) ((g)->max_n_mean) #define gauden_n_stream(g) ((g)->n_feat) #define gauden_stream_len(g,i) ((g)->featlen[i]) #define gauden_n_mean(g,m,f) ((g)->mgau[m][f].n_mean) #define gauden_n_var(g,m,f) ((g)->mgau[m][f].n_var) #define gauden_cb0(g,m,f) ((g)->mgau[m][f].cb0) /* * Read mixture gaussian codebooks from the given files. Allocate memory space needed * for them. Apply the specified variance floor value. Optionally, precompute the * log(determinants) for the (diagonal) variances and transform variances to 1/(2*var) * (these are optimizations for Mahalanobis distance computation). * Return value: ptr to the model created; NULL if error. * (See Sphinx3 model file-format documentation.) */ gauden_t * gauden_init (char *meanfile, /* In: File containing means of mixture gaussians */ char *varfile, /* In: File containing variances of mixture gaussians */ float64 varfloor, /* In: Floor value to be applied to variances; usually 0.0001 */ int32 det_varinv); /* In: Boolean, whether to precompute determinants and transform var to 1/(2*var) for distance computation */ /* * Reload mixture Gaussian means from the given file. The means must have already * been loaded at least once (using gauden_init). * Return value: 0 if successful, -1 otherwise. */ int32 gauden_mean_reload (gauden_t *g, /* In/Out: g->mean to be reloaded */ char *meanfile); /* In: File to reload means from */ /* * Compute gaussian density values for the given input vector wrt the specified mixture * gaussian codebook. Density values are unnormalized and in logs3 domain. * Return value: #densities computed and returned in dist. */ int32 gauden_dist (gauden_t *g, /* In: handle to entire ensemble of codebooks */ int32 m, /* In: <codebook,feature> specifying the mgau */ int32 f, vector_t obs, /* In: Input observation vector */ int32 *dist /* Out: "Distance" of obs wrt each density in g->mgau[m][f]. Caller must allocate sufficient space for all densities (e.g. g->max_n_mean) */ ); /* Floor the values of non-zero variance vectors */ void gauden_var_nzvec_floor (gauden_t *g, /* In: Gaussian density to be operated on */ float64 floor); /* In: Floor value */ #endif <file_sep>/share/acoustic/tidigits/make-bin-zip #!/bin/sh # Copyright 1999-2002 Carnegie Mellon University. # Portions Copyright 2002 Sun Microsystems, Inc. # Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. # All Rights Reserved. Use is subject to license terms. # # See the file "license.terms" for information on usage and # redistribution of this file, and for a DISCLAIMER OF ALL # WARRANTIES. # # Creates the binary form of the WSJ acoustic model suitable # for use with Sphinx 3 and 3.3 # # "NIST CD-ROM Version of the Texas Instruments-developed Studio Quality # Speaker-Independent Connected-Digit Corpus" # BIN_ZIP=tidigits_8gau_13dCep_16k_40mel_130Hz_6800Hz.bin.zip # where the WSJ acoustic model directory is, modify as you need MODEL_DIR=/lab/speech/sphinx4/data/tidigits_model PWD=`pwd` rm -f ${BIN_ZIP} cd $MODEL_DIR zip -r ${BIN_ZIP} README am.props license.terms unigram.lm unigram.lm.DMP dictionary fillerdict wd_dependent_phone.500.mdef wd_dependent_phone.cd_continuous_8gau/means.LittleEndian wd_dependent_phone.cd_continuous_8gau/mixture_weights.LittleEndian wd_dependent_phone.cd_continuous_8gau/transition_matrices.LittleEndian wd_dependent_phone.cd_continuous_8gau/variances.LittleEndian mv $BIN_ZIP $PWD<file_sep>/archive_s3/s3.0/src/libutil/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # VPATH = .:.. include ../../Makefile.defines TARGET = libutil.a OBJS = bitvec.o \ case.o \ ckd_alloc.o \ cmd_ln.o \ err.o \ filename.o \ glist.o \ hash.o \ heap.o \ io.o \ profile.o \ str2words.o \ unlimit.o alpha_OBJS = rpcc.o CFLAGS = $(DEBUG) ${$(MACHINE)_CFLAGS} $(TARGET): $(OBJS) ${$(MACHINE)_OBJS} ar crv $@ $? ranlib $@ install: (cd $(MACHINE); make -f ../Makefile) clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# (cd $(MACHINE); rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~) <file_sep>/archive_s3/s3.2/src/ascr.c /* * ascr.c -- Acoustic (senone) scores * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 09-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "ascr.h" ascr_t *ascr_init (int32 n_sen, int32 n_comsen) { ascr_t *ascr; ascr = (ascr_t *) ckd_calloc (1, sizeof(ascr_t)); ascr->sen = (int32 *) ckd_calloc (n_sen + n_comsen, sizeof(int32)); ascr->comsen = ascr->sen + n_sen; return ascr; } <file_sep>/archive_s3/s3.0/exp/gauden/gautest.c /* * gautest.c -- Gaussian density tests * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 05-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libfeat/libfeat.h> #include <libmain/gauden.h> #include "subvq.h" static void usagemsg (char *pgm) { E_INFO("Usage: %s meanfile varfile vqfile featfile beam\n", pgm); exit(0); } static int32 chk_mean0 (float32 *mean, int32 len) { int32 i; for (i = 0; (i < len) && (mean[i] == 0.0); i++); return (i == len); /* TRUE iff all mean values are 0.0 */ } /* Create and return a bitvector marking codebooks (mixture Gaussians) whose means are all 0.0 */ static bitvec_t chk_cb0 (gauden_t *g) { int32 m, c, n; bitvec_t bv; E_INFO("Checking codebooks with all 0.0 means\n"); bv = bitvec_alloc (gauden_n_mgau(g)); bitvec_clear_all (bv, gauden_n_mgau(g)); n = 0; for (m = 0; m < gauden_n_mgau(g); m++) { for (c = 0; c < gauden_n_mean(g, m, 0); c++) { if (! chk_mean0(g->mgau[m][0].mean[c], g->featlen[0])) break; } if (c == gauden_n_mean(g, m, 0)) { bitvec_set (bv, m); n++; printf (" %d", m); } } printf ("\n"); E_INFO("%d codebooks are all 0.0\n", n); return bv; } main (int32 argc, char *argv[]) { gauden_t *g; float32 **feat; float64 fbeam; int32 nfr, beam, best; int32 *dist; char *meanfile, *varfile, *vqfile, *featfile, *beamarg; feat_t *fcb; int32 i, j, k, f, m; int32 n_match, n_match_tot, n_cand, n_cand_tot; int32 bv, bc, bv2, bc2, *v2; char str[4096]; bitvec_t cb0; subvq_t *vq; int32 **vqdist; ptmr_t *tm; FILE *fp; if (argc != 6) usagemsg (argv[0]); meanfile = argv[1]; varfile = argv[2]; vqfile = argv[3]; featfile = argv[4]; beamarg = argv[5]; if (sscanf (beamarg, "%lf", &fbeam) != 1) usagemsg (argv[0]); E_INFO("Assuming single feature-stream\n"); logs3_init ((float64) 1.0003); fcb = feat_init ("s3_1x39"); feat = feat_vector_alloc(fcb); assert (feat_n_stream(fcb) == 1); fp = myfopen(featfile, "r"); beam = logs3(fbeam); E_INFO("logs3(beam)= %d\n", beam); g = gauden_init (meanfile, varfile, 0.0001 /* varfloor */, TRUE); assert (g->n_feat == 1); cb0 = chk_cb0 (g); vq = subvq_init (vqfile); for (i = 0; i < vq->n_sv; i++) { vector_print (stdout, vq->mean[i][0], vq->svsize[i]); vector_print (stdout, vq->var[i][0], vq->svsize[i]); printf (" %e\n", vq->idet[i][0]); } dist = (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); v2 = (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); vqdist = (int32 **) ckd_calloc_2d (vq->n_sv, vq->vqsize, sizeof(int32)); tm = (ptmr_t *) ckd_calloc (1, sizeof(ptmr_t)); ptmr_init (tm); n_match_tot = 0; /* #Times best VQ codeword and original codeword same */ n_cand_tot = 0; /* #Best VQ codeword candidates (i.e., within beam of best) */ nfr = 0; for (f = 0;; f++) { for (i = 0; i < feat_stream_len(fcb,0); i++) if (fscanf (fp, "%f", &(feat[0][i])) != 1) break; if (i < feat_stream_len(fcb,0)) break; nfr++; subvq_dist_eval (vq, feat[0], vqdist); for (i = 0; i < vq->n_sv; i++) printf (" %11d\n", vqdist[i][0]); n_match = 0; n_cand = 0; for (m = 0; m < g->n_mgau; m++) { if (bitvec_is_set(cb0, m)) continue; k = gauden_dist (g, m, 0, feat[0], dist); /* Find the best density in this codebook */ bv = dist[0]; bc = 0; for (i = 1; i < k; i++) { if (dist[i] > bv) { bv = dist[i]; bc = i; } } /* Find the best density according to subvq */ for (i = 0; i < k; i++) { v2[i] = 0; for (j = 0; j < vq->n_sv; j++) v2[i] += vqdist[j][vq->map[m][i][j]]; if ((i == 0) || (v2[i] > bv2)) { bv2 = v2[i]; bc2 = i; } } /* Find all densities within beam */ for (i = 0; i < k; i++) { if (v2[i] >= bv2 + beam) { n_cand++; if (bc == i) n_match++; } } #if 1 printf ("Fr[%3d]St[%4d]: Best-Orig: %2d %11d; SVQ: %11d; Best-SVQ: %2d %11d; Orig: %11d\n", f, m, bc, bv, v2[bc], bc2, bv2, dist[bc2]); #endif } #if 1 printf ("\n"); vector_print (stderr, feat[0], 39); fprintf (stderr, "Fr %d: #Matches %d, #Candidates %d; Continue? ", f, n_match, n_cand); fgets (str, sizeof(str), stdin); if ((str[0] == 'n') || (str[0] == 'N') || (str[0] == 'q') || (str[0] == 'Q')) break; #else printf ("Fr %d: #Matches %5d, #Candidates %7d\n", f, n_match, n_cand); #endif n_match_tot += n_match; n_cand_tot += n_cand; /* Repeat, just for timing */ ptmr_start (tm); for (m = 0; m < g->n_mgau; m++) { if (bitvec_is_set(cb0, m)) continue; /* Find the best density according to subvq */ for (i = 0; i < g->max_n_mean; i++) { v2[i] = 0; for (j = 0; j < vq->n_sv; j++) v2[i] += vqdist[j][vq->map[m][i][j]]; if ((i == 0) || (v2[i] > bv2)) { bv2 = v2[i]; bc2 = i; } } } ptmr_stop (tm); } if (nfr > 0) { printf ("%5d frames; %d match/fr, %d cand/fr; %.1fs CPU, %.2f xRT; %.1fs Elapsed, %.2f xRT\n", nfr, n_match_tot/nfr, n_cand_tot/nfr, tm->t_cpu, tm->t_cpu*100.0/nfr, tm->t_elapsed, tm->t_elapsed*100.0/nfr); } } <file_sep>/SphinxTrain/src/libs/libio/s3_open.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3_open.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3_open.h> #include <s3/bcomment_io.h> #include <s3/swap.h> #include <s3/s3.h> #include <string.h> FILE * s3_open_bin_read(const char *file_name, const char *in_version, const char **out_comment) { FILE *fp; char version[MAX_VERSION_LEN]; fp = fopen(file_name, "rb"); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for reading", file_name); return NULL; } if (fscanf(fp, "%s", version) != 1) { E_ERROR("Premature EOF while reading %s\n", file_name); goto error; } if (strcmp(version, in_version) != 0) { E_ERROR("version mismatch. %s != %s (expected)\n", __FILE__, __LINE__, version, in_version); goto error; } if (bcomment_read(out_comment, fp) != S3_SUCCESS) { goto error; } if (swap_check(fp) != S3_SUCCESS) { goto error; } return fp; error: fclose(fp); return NULL; } FILE * s3_open_bin_write(const char *file_name, const char *version, const char *comment) { FILE *fp; fp = fopen(file_name, "wb"); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s for writing", file_name); goto error; } if ((unsigned)fprintf(fp, "%s\n", version) != strlen(version)+1) { E_ERROR("unable to write version id in %s", file_name); goto error; } if (bcomment_write(fp, comment) != S3_SUCCESS) { goto error; } if (swap_stamp(fp) != S3_SUCCESS) { goto error; } return fp; error: fclose(fp); return NULL; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/param_cnt/enum_corpus.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: enum_corpus.c * * Description: * * Author: * <NAME> *********************************************************************/ #include "enum_corpus.h" #include "cnt_fn.h" #include "mk_sseq.h" /* BHIKSHA FIX */ #include "phone_cnt.h" /* END BHIKSHA FIX */ #include <s3/ck_seg.h> #include <s3/prim_type.h> #include <s3/corpus.h> #include <s3/mk_wordlist.h> #include <s3/mk_phone_list.h> #include <s3/vector.h> #include <s3/feat.h> #include <s3/ckd_alloc.h> #include <s3/s3.h> #include <stdio.h> int enum_corpus(lexicon_t *lex, model_def_t *mdef, uint32 *cnt, cnt_fn_t cnt_fn) { uint32 tick_cnt = 0; char *trans = NULL; uint16 *seg = NULL; uint32 n_frame; char **word = NULL; uint32 n_word; acmod_id_t *phone = NULL; uint32 n_phone; char *btw_mark = NULL; while (corpus_next_utt()) { if (trans) { free(trans); trans = NULL; } if (seg) { free(seg); seg = NULL; } if (word) { ckd_free(word); word = NULL; } if (phone) { ckd_free(phone); phone = NULL; } if (btw_mark) { ckd_free(btw_mark); btw_mark = NULL; } if ((++tick_cnt % 1000) == 0) { fprintf(stderr, "[%u] ", tick_cnt); fflush(stderr); } if (corpus_get_sent(&trans) != S3_SUCCESS) { E_FATAL("Unable to read word transcript for %s\n", corpus_utt_brief_name()); } /* BHIKSHA FIX; IF ONLY PHONE COUNTS WANTED DONT NEED STATE SEGS */ if (cnt_fn != phone_cnt){ if (corpus_get_seg(&seg, &n_frame) != S3_SUCCESS) { E_FATAL("Unable to read Viterbi state segmentation for %s\n", corpus_utt_brief_name()); } } /* END BHIKSHA FIX */ word = mk_wordlist(trans, &n_word); phone = mk_phone_list(&btw_mark, &n_phone, word, n_word, lex); if (phone == NULL) { E_WARN("Unable to produce phone sequence; skipping utt %s\n", corpus_utt()); continue; } /* BHIKSHA FIX; THIS STEP ONLY IF WE NEED STATE COUNTS */ if (cnt_fn != phone_cnt){ /* check to see whether the word transcript and dictionary entries agree with the state segmentation */ if (ck_seg(mdef->acmod_set, phone, n_phone, seg, n_frame, corpus_utt()) != S3_SUCCESS) { continue; } } (*cnt_fn)(cnt, /* observation counts */ mdef, /* model definitions */ seg, n_frame, /* Viterbi state segmentation */ phone, btw_mark, n_phone); /* list of phones */ } /* free the per utterance data structures from the last utt */ if (trans) { free(trans); trans = NULL; } if (seg) { free(seg); seg = NULL; } if (word) { ckd_free(word); word = NULL; } if (phone) { ckd_free(phone); phone = NULL; } if (btw_mark) { ckd_free(btw_mark); btw_mark = NULL; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 19:17:26 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:32 awb * *** empty log message *** * * Revision 1.1 97/03/07 08:40:21 eht * Initial revision * * Revision 1.1 1996/03/25 15:21:20 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/v4_feat.c /* ==================================================================== * Copyright (c) 1995-2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: v4_feat.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include "v4_feat.h" #include <s3/feat.h> #include "cep_frame.h" #include "dcep_frame.h" #include "ddcep_frame.h" #include <s3/agc.h> #include <s3/cmn.h> #include <s3/silcomp.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <assert.h> #include <string.h> #include <stdio.h> #define N_FEAT 1 static uint32 n_feat = N_FEAT; static uint32 vecsize[1]; static uint32 mfcc_len; static int32 window_size; const char * v4_feat_doc() { return "1 stream :== < input feature vector >"; } uint32 v4_feat_id() { return FEAT_ID_V4; } uint32 v4_feat_n_stream() { return n_feat; } uint32 v4_feat_blksize() { return vecsize[0]; } const uint32 * v4_feat_vecsize() { return vecsize; } void v4_feat_set_in_veclen(uint32 veclen) { mfcc_len = veclen; window_size = cmd_ln_int32("-cepwin"); vecsize[0] = veclen * (window_size * 2 + 1); cmn_set_veclen(veclen); agc_set_veclen(veclen); } vector_t ** v4_feat_compute(vector_t *mfcc, uint32 *inout_n_frame) { vector_t **out; uint32 svd_n_frame; uint32 n_frame; const char *comp_type = cmd_ln_access("-silcomp"); int32 i, j; uint32 mfcc_len; void v4_mfcc_print(vector_t *mfcc, uint32 n_frame); mfcc_len = feat_mfcc_len(); /* # of coefficients c[0..MFCC_LEN-1] per frame */ n_frame = svd_n_frame = *inout_n_frame; if (strcmp(comp_type, "none") != 0) { n_frame = sil_compression(comp_type, mfcc, n_frame); } cmn(&mfcc[0][0], n_frame); agc(&mfcc[0][0], n_frame); out = feat_alloc(n_frame); for (i = 0; i < n_frame; ++i) { uint32 spos = 0; for (j = -window_size; j <= window_size; ++j) { int32 ii; /* Duplicate the first and last frames for out-of-bounds window indices. */ if (i + j < 0) ii = -j; else if (i + j >= n_frame) ii = n_frame - j - 1; else ii = i; memcpy(out[i][0] + spos, mfcc[(int32)ii + j], mfcc_len * sizeof(float32)); spos += mfcc_len; } } *inout_n_frame = n_frame; return out; } void v4_mfcc_print(vector_t *mfcc, uint32 n_frame) { uint32 i, k; uint32 mfcc_len; mfcc_len = feat_mfcc_len(); for (i = 0; i < n_frame; i++) { printf("mfcc[%04u]: ", i); for (k = 0; k < mfcc_len; k++) { printf("%6.3f ", mfcc[i][k]); } printf("\n"); } } void v4_feat_print(const char *label, vector_t **f, uint32 n_frames) { uint32 i; int32 j; uint32 k; char *name[] = { "" }; vector_t *frame; vector_t stream; for (i = 0; i < n_frames; i++) { frame = f[i]; for (j = 0; j < n_feat; j++) { stream = frame[j]; printf("%s%s[%04u]: ", label, name[j], i); for (k = 0; k < vecsize[j]; k++) { printf("%6.3f ", stream[k]); } printf("\n"); } printf("\n"); } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * */ <file_sep>/SphinxTrain/src/programs/bw/backward.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: backward.c * * Description: * The routine in this file compute the beta variable in the * forward backward algorithm. The routine also updates the * reestimation sums for mixing weights, transition matrices, * means and variances. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/model_inventory.h> #include <s3/vector.h> #include <s3/ckd_alloc.h> #include <s3/state.h> #include <s3/profile.h> #include <s3/s2_param.h> #include <s3/gauden.h> #include <s3/feat.h> #include <s3/s3.h> #include "accum.h" #include <assert.h> #include <math.h> #include <string.h> void partial_op(float64 *p_op, float64 op, float64 **den, uint32 **den_idx, float32 **mixw, uint32 n_feat, uint32 n_top) { uint32 j, k, kk; float64 f_op; for (j = 0; j < n_feat; j++) { /* over all feature streams */ /* Evaluate the mixture density for feature stream j * gvn. component density values */ k = den_idx[j][0]; f_op = mixw[j][k] * den[j][0]; for (kk = 1; kk < n_top; kk++) { k = den_idx[j][kk]; f_op += mixw[j][k] * den[j][kk]; } /* Figure out partial output probability excluding * the given feature stream j. */ /* That is technically correct but quite confusing, because * actually what we are trying to achieve here is a * normalization by f_op when we go to compute the mixture * posteriors. See below. */ p_op[j] = op / f_op; } } void partial_ci_op(float64 *p_ci_op, float64 **den, uint32 **den_idx, float32 **mixw, uint32 n_feat, uint32 n_top) { uint32 j, k, kk; float64 f_op; for (j = 0; j < n_feat; j++) { /* over all feature streams */ /* Evaluate the mixture density for feature stream j * gvn. component density values */ k = den_idx[j][0]; f_op = mixw[j][k] * den[j][0]; for (kk = 1; kk < n_top; kk++) { k = den_idx[j][kk]; f_op += mixw[j][k] * den[j][kk]; } /* Oh look, and we do it the opposite way for CI models... */ p_ci_op[j] = f_op; } } void den_terms_ci(float64 **d_term, float64 post_j, float64 *p_ci_op, float64 **den, uint32 **den_idx, float32 **mixw, uint32 n_feat, uint32 n_top) { uint32 j, k, kk; float64 inv_ci_op; for (j = 0; j < n_feat; j++) { if (p_ci_op[j] != 0) { inv_ci_op = 1.0 / p_ci_op[j]; for (kk = 0; kk < n_top; kk++) { /* density index k for one of the n_top density values */ k = den_idx[j][kk]; d_term[j][kk] = mixw[j][k] * den[j][kk] * inv_ci_op * post_j; } } else { for (kk = 0; kk < n_top; kk++) { d_term[j][kk] = 0; } } } } void den_terms(float64 **d_term, float64 p_reest_term, float64 *p_op, float64 **den, uint32 **den_idx, float32 **mixw, uint32 n_feat, uint32 n_top) { uint32 j, k, kk; for (j = 0; j < n_feat; j++) { for (kk = 0; kk < n_top; kk++) { /* density index k for one of the n_top density values */ k = den_idx[j][kk]; /* Remember that p_reest_term is equal to the posterior * probability of transition (i,j) divided by the output * density of state j (i.e. post_j / op). Thus, in the * single-stream case, this equation works out to: * * dt[k] = post * (mixw[k] * density[k]) / output_density * = post * (mixw[k] * density[k]) / sum_k(mixw[k] * density[k]) * * in other words, the transition posterior times the * mixture posterior. * * In the multi-stream case, where p_op[j] = (output / * output[j]), we get this: * * dt[j][k] * = (post / output) * (mixw[j][k] * density[j][k] * output) / (output[j]) * = post * (mixw[j][k] * density[j][k]) / sum_k(mixw[j][k] * density[j][k]) * * in other words the transition posterior times the * mixture posterior for stream j. * * It probably has to be this way in order to accomodate * the single and multi-stream cases with the same code, * but it's kind of confusing. */ d_term[j][kk] = mixw[j][k] * den[j][kk] * p_op[j] * p_reest_term; } } } /********************************************************************* * * Function: * backward_update * * Description: * The routine in this file compute the beta variable in the * forward backward algorithm. The routine also updates the * reestimation sums for mixing weights, transition matrices, * means and variances. * * Function Inputs: * float64 **alpha - * A 2-d array containing the scaled alpha variable. * alpha[t][s] is scaled alpha at time t for state s. * * float64 *scale - * The scale factor for each time frame. * * float64 ****den - * The top N component mixture density values for * all time. * * den[t][d][f][i] addresses the the Ith density of * the top N densities for acoustic feature stream f, * density d at time t. * * uint32 ****den_idx - * The top N component mixture density indices for * all time. * * den[t][d][f][i] addresses the the Ith density index * of the top N densities for acoustic feature stream f, * density d at time t. * * vector_t **feature - * The feature streams for all time within the * utterance. * * feature[t][f][c] addresses component c of the feature * vector for feature f at time t. * * uint32 n_obs - * Number of observations (i.e. frames) in this observation * sequence (i.e. utterance) * * state_t *state_seq - * The sequence of sentence HMM states for the utterance. * * uint32 n_state - * The number of states in the sentence HMM. * * model_inventory_t *inv - * A pointer to a structure which contains references to * all model parameters and reestimation sum accumulators. * * float64 beam - * Pruning beam width. * * float32 spthresh - * State posterior probability threshold for reestimation. * State posterior prob must be greater than this value * for the state to be included in the reestimation counts. * * int32 mixw_reest - * A boolean indicating whether or not to do mixing weight * reestimation. * * int32 tmat_reest - * A boolean indicating whether or not to do transition probability matrix * reestimation. * * int32 mean_reest - * A boolean indicating whether or not to do mean * reestimation. * * int32 var_reest * A boolean indicating whether or not to do variance * reestimation. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - * No errors found; Local accumulators updated. * S3_ERROR - * Error found; Ignore local accumulator values. * * Global Outputs: * None * * Errors: * *********************************************************************/ int32 backward_update(float64 **active_alpha, uint32 **active_astate, uint32 *n_active_astate, float64 *scale, float64 **dscale, vector_t **feature, uint32 n_obs, state_t *state_seq, uint32 n_state, model_inventory_t *inv, float64 beam, float32 spthresh, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 pass2var, int32 var_is_full, FILE *pdumpfh, float32 ***lda) { void *tt; /* temp variable used to do pointer swapping */ uint32 i, j=0, s, u, q, q_f; /* various variables of iteration */ int32 t; /* time */ uint32 *active_a; /* an active state list */ uint32 *active_b; /* another active state list */ uint32 *non_emit; /* list of active non-emitting states */ uint32 n_non_emit; /* the # of non-emitting states on the active list */ uint32 *tmp_non_emit; /* list of active non-emitting states after pruning */ uint32 n_tmp_non_emit; uint32 *active; /* the active list for time t */ uint32 n_active; /* the # of active states */ uint32 *active_cb; uint32 *next_active; /* the active list for time t-1 */ uint32 n_next_active; /* the # of next active states */ unsigned char *asf_a; /* active state flag array a */ unsigned char *asf_b; /* active state flag array b */ unsigned char *asf; /* active state flag current frame */ unsigned char *asf_next; /* active state flag next frame */ uint32 *prior; /* prior state list */ float32 *tprob; /* transition probabilities for an (i, j) */ float32 ***mixw; /* all mixing weights */ float64 pthresh; /* pruning threshold */ float64 pprob; /* pruned posterior probability */ float64 t_pprob; /* total pruned posterior probability */ float64 sum_alpha_beta; /* sum of the product of all alpha and beta values for some time t */ float64 *beta_a; /* storage for source or destination beta */ float64 *beta_b; /* storage for source or destination beta */ float64 *beta; /* source beta (set to either beta_a or beta_b) */ float64 *prior_beta; /* destination beta (set to either beta_a or beta_b) */ gauden_t *g; /* Gaussian density parameters and reestimation sums */ float64 ***now_den; /* Short for den[t] */ uint32 ***now_den_idx; /* Short for den_idx[t] */ float32 **tacc; /* Transition matrix reestimation sum accumulators for the utterance. */ float32 *a_tacc; /* The reestimation accumulator for a particular transition */ float32 ***wacc; /* mixing weight reestimation sum accumulators for the utterance. */ float32 ***denacc; /* mean/var reestimation accumulators for time t */ size_t denacc_size; /* Total size of data references in denacc. Allows for quick clears between time frames */ float64 recip_final_alpha; /* Reciprocal of the final alpha value (i.e. last frame final HMM state */ int retval = S3_SUCCESS; /* use to exit gracefully */ uint32 n_lcl_cb; uint32 *cb_inv; float64 p_reest_term; float64 post_j; float64 sum_reest_post_j = 0.0; static float64 *p_op = NULL; static float64 *p_ci_op = NULL; float64 op; static float64 **d_term = NULL; static float64 **d_term_ci = NULL; uint32 n_feat; uint32 n_density; uint32 n_top; uint32 n_reest_tot = 0; uint32 n_active_tot = 0; int32 *acbframe; uint32 n_active_cb; timing_t *gau_timer = NULL; timing_t *rsts_timer = NULL; timing_t *rstf_timer = NULL; float64 ttt; uint32 max_n_next = 0; uint32 l_cb; uint32 l_ci_cb; uint32 n_cb; /* Get the Gaussian density evaluation CPU timer */ gau_timer = timing_get("gau"); /* Get the per state reestimation CPU timer */ rsts_timer = timing_get("rsts"); /* Get the per frame reestimation CPU timer */ rstf_timer = timing_get("rstf"); /* Look for the final state in the active states at the last frame */ for (q_f = 0; q_f < n_active_astate[n_obs-1] && active_astate[n_obs-1][q_f] != (n_state-1); q_f++); if (q_f == n_active_astate[n_obs-1]) { E_ERROR("final state not reached\n"); return S3_ERROR; } /* Set pruning threshold for such that all unpruned paths for some * time t and state i satisfy alpha[t][i]beta[t][i] > beam * alpha[T][F] */ pthresh = beam * active_alpha[n_obs-1][q_f]; g = inv->gauden; n_feat = gauden_n_feat(g); n_density = gauden_n_density(g); n_top = gauden_n_top(g); if (p_op == NULL) { p_op = ckd_calloc(n_feat, sizeof(float64)); p_ci_op = ckd_calloc(n_feat, sizeof(float64)); } if (d_term == NULL) { d_term = (float64 **)ckd_calloc_2d(n_feat, n_top, sizeof(float64)); d_term_ci = (float64 **)ckd_calloc_2d(n_feat, n_top, sizeof(float64)); } /* Allocate space for source/destination beta */ beta_a = ckd_calloc(n_state, sizeof(float64)); beta_b = ckd_calloc(n_state, sizeof(float64)); /* initialize locations for source/destination beta */ beta = beta_a; prior_beta = beta_b; /* Allocate space for the cur/next active state lists */ active_a = ckd_calloc(n_state, sizeof(uint32)); active_b = ckd_calloc(n_state, sizeof(uint32)); active_cb = ckd_calloc(2*n_state, sizeof(uint32)); /* count up the max possible number of active non-emitting states */ n_non_emit = 0; for (s = 0; s < n_state; s++) if (state_seq[s].mixw == TYING_NON_EMITTING) n_non_emit++; /* Allocate space for the active non-emitting state lists */ non_emit = ckd_calloc(n_non_emit, sizeof(uint32)); tmp_non_emit = ckd_calloc(n_non_emit, sizeof(uint32)); /* initialize locations for cur/next active state lists */ active = active_a; next_active = active_b; n_active = 0; n_next_active = 0; /* Allocate space for the cur/next active state flags */ asf_a = ckd_calloc(n_state, sizeof(unsigned char)); asf_b = ckd_calloc(n_state, sizeof(unsigned char)); /* Active state flags prevent states from being added to the active list more than once */ /* Initialize cur/next active state lists */ asf = asf_a; asf_next = asf_b; mixw = inv->mixw; if (mixw_reest) { /* Need to reallocate mixing accumulators for utt */ if (inv->l_mixw_acc) { ckd_free_3d((void ***)inv->l_mixw_acc); inv->l_mixw_acc = NULL; } inv->l_mixw_acc = (float32 ***)ckd_calloc_3d(inv->n_mixw_inverse, n_feat, n_density, sizeof(float32)); } wacc = inv->l_mixw_acc; n_lcl_cb = inv->n_cb_inverse; cb_inv = inv->cb_inverse; /* Allocate local accumulators for mean, variance or mllr matrix reestimation sums if necessary */ gauden_alloc_l_acc(g, n_lcl_cb, mean_reest, var_reest, var_is_full); if (tmat_reest) { if (inv->l_tmat_acc) { ckd_free_2d((void **)inv->l_tmat_acc); inv->l_tmat_acc = NULL; } for (i = 0; i < n_state; i++) { if (state_seq[i].n_next > max_n_next) max_n_next = state_seq[i].n_next; } inv->l_tmat_acc = (float32 **)ckd_calloc_2d(n_state, max_n_next, sizeof(float32)); } /* transition matrix reestimation sum accumulators for the utterance */ tacc = inv->l_tmat_acc; /* Initializing this with zero is okay since we start at the last frame... */ acbframe = ckd_calloc(n_lcl_cb, sizeof(int32)); n_active_cb = 0; now_den = (float64 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_top, sizeof(float64)); now_den_idx = (uint32 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_top, sizeof(uint32)); if (mean_reest || var_reest) { /* allocate space for the per frame density counts */ denacc = (float32 ***)ckd_calloc_3d(n_lcl_cb, n_feat, n_density, sizeof(float32)); /* # of bytes required to store all weighted vectors */ denacc_size = n_lcl_cb * n_feat * n_density * sizeof(float32); } else { denacc = NULL; denacc_size = 0; } recip_final_alpha = 1.0/active_alpha[n_obs-1][q_f]; /* Set the initial beta value */ prior_beta[n_state-1] = 1.0; /* Last state is non-emitting */ non_emit[0] = n_state-1; n_non_emit = 1; t = n_obs-1; if (scale[t] == 0) { E_ERROR("Scale factor at time == %u is zero\n", t); retval = S3_ERROR; goto free; } #if BACKWARD_DEBUG E_INFO("Before updating non-emitting states\n"); #endif /* Process non-emitting initial states first */ for (s = 0; s < n_non_emit; s++) { j = non_emit[s]; #if BACKWARD_DEBUG E_INFO("In time %d, processing non-emitting state %d\n",t,j); #endif prior = state_seq[j].prior_state; tprob = state_seq[j].prior_tprob; for (u = 0; u < state_seq[j].n_prior; u++) { i = prior[u]; #if BACKWARD_DEBUG E_INFO("Processing non-emitting state %d, prior %d\n",j, i); #endif for (q = 0; q < n_active_astate[t] && active_astate[t][q] != i; q++); if (q == n_active_astate[t]) { /* state i not active in forward pass; skip it */ continue; } /* accumulate before scaling so scale[t] doesn't appear * in the reestimation sums */ if (tmat_reest) { assert(tacc != NULL); a_tacc = &tacc[i][j-i]; } else { a_tacc = NULL; } if (a_tacc) *a_tacc += active_alpha[t][q] * tprob[u] * prior_beta[j] * recip_final_alpha; assert(tprob[u] > 0); prior_beta[i] += tprob[u] * prior_beta[j]; if (state_seq[i].mixw == TYING_NON_EMITTING){ non_emit[n_non_emit] = i; n_non_emit++; }else{ if (asf[i] != TRUE) { asf[i] = TRUE; active[n_active++] = i; } } } } for ( s = 0; s < n_active; s++) { i = active[s]; prior_beta[i] *= scale[t]; } n_non_emit = 0; n_tmp_non_emit = 0; t_pprob = 0; n_cb = gauden_n_mgau(g); #if BACKWARD_DEBUG E_INFO("Before beta update\n"); #endif for (t = n_obs-2; t >= 0; t--) { #if BACKWARD_DEBUG E_INFO("At time %d\n",t); #endif if (scale[t] == 0) { E_ERROR("Scale factor at time == %u is zero\n", t); retval = S3_ERROR; goto free; } n_active_cb = 0; /* zero beta at time t */ memset(beta, 0, n_state * sizeof(float64)); sum_alpha_beta = 0; n_active_tot += n_active; /* for all active emitting j states at time t+1, compute the log density values */ for (s = 0; s < n_active; s++) { sum_reest_post_j = 0.0; j = active[s]; #if BACKWARD_DEBUG E_INFO("In GMM Computation, state %d is active\n",j); E_INFO("state_seq[j].cb %d\n",state_seq[j].cb); #endif l_cb = state_seq[j].l_cb; l_ci_cb = state_seq[j].l_ci_cb; if (acbframe[l_cb] != t+1) { /* The top N densities for the observation at time t+1 and their indices */ if (gau_timer) timing_start(gau_timer); gauden_compute_log(now_den[l_cb], now_den_idx[l_cb], feature[t+1], g, state_seq[j].cb, /* Preinitializing topn only really makes a difference for semi-continuous (n_lcl_cb == 1) models. Also don't do it in the last frame. */ (t == n_obs-2 || n_lcl_cb > 1) ? NULL : now_den_idx[l_cb]); active_cb[n_active_cb++] = l_cb; acbframe[l_cb] = t+1; if (l_cb != l_ci_cb) { if (acbframe[l_ci_cb] != t+1) { gauden_compute_log(now_den[l_ci_cb], now_den_idx[l_ci_cb], feature[t+1], g, state_seq[j].ci_cb, /* See above. */ NULL); active_cb[n_active_cb++] = l_ci_cb; acbframe[l_ci_cb] = t+1; } } if (gau_timer) timing_stop(gau_timer); } } #if BACKWARD_DEBUG E_INFO("Before scaling\n"); #endif /* Scale densities by dividing all by max */ gauden_scale_densities_bwd(now_den, now_den_idx, &dscale[t+1], active_cb, n_active_cb, g); for (s = 0; s < n_active; s++) { #if BACKWARD_DEBUG E_INFO("In beta update, state %d is active for active state # %d\n",j,s); #endif j = active[s]; l_cb = state_seq[j].l_cb; l_ci_cb = state_seq[j].l_ci_cb; /* Output probability (actually a density) for state j at * timepoint t+1. */ op = gauden_mixture(now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], g); #if BACKWARD_DEBUG E_INFO("In beta update, state %d is active\n",j); #endif if (gau_timer) timing_stop(gau_timer); assert(asf[j] == TRUE); assert(state_seq[j].mixw != TYING_NON_EMITTING); asf[j] = FALSE; prior = state_seq[j].prior_state; tprob = state_seq[j].prior_tprob; /* for all states, i, prior to state j */ for (u = 0; u < state_seq[j].n_prior; u++) { i = prior[u]; #if BACKWARD_DEBUG E_INFO("For active state %d , state %d is its prior\n",j,i); #endif for (q = 0; q < n_active_astate[t] && active_astate[t][q] != i; q++); if (q == n_active_astate[t]) { /* state i not active in forward pass; skip it */ continue; } /* since survived pruning, this will be true for reasonable pruning thresholds */ assert(prior_beta[j] > 0); if (rsts_timer) timing_start(rsts_timer); /* NOTE!!! This is equivalent to post_j / op, a fact that is used in the calculation of mixture densities in the non-CI case (it's why p_reest_term is passed to den_terms() instead of post_j). This seems needlessly obscure, but there you have it. */ p_reest_term = active_alpha[t][q] * (float64) tprob[u] * prior_beta[j] * recip_final_alpha; post_j = p_reest_term * op; #if BACKWARD_DEBUG E_INFO("State %u, prior %u, post_j %e p_reest_term %e op %e\n",j,i,post_j,p_reest_term,op); #endif if (post_j < 0) { E_WARN("posterior of state %u @ time %u (== %.8e) < 0\n", j, post_j, t+1); retval = S3_ERROR; if (rsts_timer) timing_stop(rsts_timer); goto free; } #if BACKWARD_DEBUG E_INFO("post_j =%e, alpha == %e * tprob == %e * op == %e * beta == %e * 1 / falpha == %e q=%d state_of_q=%d at time %d\n", post_j, active_alpha[t][q], tprob[u], op, prior_beta[j], recip_final_alpha, q, i,t); #endif if (post_j > 1.0 + 1e-2) { E_ERROR("posterior of state %u (== %.8e) @ time %u > 1 + 1e-2\n", j, post_j, t+1); E_ERROR("alpha == %e * tprob == %e * op == %e * beta == %e * 1 / falpha == %e\n", active_alpha[t][q], tprob[u], op, prior_beta[j], recip_final_alpha); retval = S3_ERROR; if (rsts_timer) timing_stop(rsts_timer); goto free; } if ((post_j > MIN_POS_FLOAT32) && (post_j > spthresh)) { sum_reest_post_j += post_j; /* beta, alpha and outprob are non-zero, so we have all we need to accumulate another term for all reestimation sums */ ++n_reest_tot; /* Update the transition matrix accumulators if necessary */ if (tmat_reest) { /* post_j is the posterior probability of * state j followed by state i, a.k.a. the * fractional count of transitions i->j. */ tacc[i][j-i] += post_j; } /* Compute the output probability excluding the contribution * of each feature stream. i.e. p_op[0] is the output * probability excluding feature stream 0. For single-stream models, * p_op[0] = 1.0, and thus we don't actually need to do this. */ partial_op(p_op, op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], n_feat, n_top); /* Compute the posterior probability (also known as the fractional * occupation count) of each (of possibly topn) density. */ den_terms(d_term, p_reest_term, p_op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[j].mixw], n_feat, n_top); if (l_cb != l_ci_cb) { /* For each feature stream f, compute: * sum_k(mixw[f][k] den[f][k]) * and store the results in p_ci_op */ partial_ci_op(p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[j].ci_mixw], n_feat, n_top); /* For each feature stream and density compute the terms: * w[f][k] den[f][k] / sum_k(w[f][k] den[f][k]) * post_j * and store results in d_term_ci */ /* Summing over these gives us \gamma_t(f,k) */ den_terms_ci(d_term_ci, post_j, p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[j].ci_mixw], n_feat, n_top); } /* accumulate the probability for each density in the mixing * weight reestimation accumulators */ if (mixw_reest) { accum_den_terms(wacc[state_seq[j].l_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); /* check if mixw and ci_mixw are different to avoid * doubling the EM counts in a CI run. */ if (state_seq[j].mixw != state_seq[j].ci_mixw) { if (n_cb < inv->n_mixw) { /* semi-continuous, tied mixture, and discrete case */ accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); } else { /* continuous case */ accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } } /* accumulate the probability for each density in * the density reestimation accumulators (these * are the same values as the mixture weight * accumulators, we will use them to compute the * density accumulators below). */ if (mean_reest || var_reest) { accum_den_terms(denacc[l_cb], d_term, now_den_idx[l_cb], n_feat, n_top); if (l_cb != l_ci_cb) { accum_den_terms(denacc[l_ci_cb], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } } if (rsts_timer) timing_stop(rsts_timer); /* Add another term for \beta_t(i) */ beta[i] += tprob[u] * op * prior_beta[j]; if (asf_next[i] != TRUE) { /* not already on the active list for time t-1 */ asf_next[i] = TRUE; if (state_seq[i].mixw == TYING_NON_EMITTING) { non_emit[n_non_emit] = i; n_non_emit++; } else { next_active[n_next_active] = i; n_next_active++; } } } /* This should be the gamma variable */ #if BACKWARD_DEBUG E_INFO("gamma_%u(%u) = %e\n", t, j, sum_reest_post_j); #endif sum_reest_post_j = 0.0; } #if BACKWARD_DEBUG E_INFO("Before alpha beta consistency check\n"); #endif /* Do an alpha / beta consistency check */ for (s = 0, n_active = 0, pprob = 0; s < n_next_active; s++) { i = next_active[s]; for (q = 0; q < n_active_astate[t] && active_astate[t][q] != i; q++); if (q == n_active_astate[t]) { /* state i not active in forward pass; skip it */ continue; } ttt = active_alpha[t][q] * beta[i]; if (ttt > pthresh) { sum_alpha_beta += ttt; active[n_active++] = i; } else { asf_next[i] = FALSE; pprob += ttt; } } for (s = 0, n_tmp_non_emit = 0; s < n_non_emit; s++) { i = non_emit[s]; for (q = 0; q < n_active_astate[t] && active_astate[t][q] != i; q++); if (q == n_active_astate[t]) { /* state i not active in forward pass; skip it */ continue; } ttt = active_alpha[t][q] * beta[i]; if (ttt > pthresh) { sum_alpha_beta += ttt; tmp_non_emit[n_tmp_non_emit++] = i; } else { asf_next[i] = FALSE; pprob += ttt; } } n_non_emit = 0; pprob *= recip_final_alpha; t_pprob += pprob; /* check an invariant. Theoretically, * sum_alpha_beta - alpha[n_obs-1][n_state-1] must be zero, but * we're dealing with finite machine word length, pruning, etc. */ if (fabs(sum_alpha_beta - active_alpha[n_obs-1][q_f]) > (S2_ALPHA_BETA_EPSILON * active_alpha[n_obs-1][q_f])) { E_ERROR("alpha(%e) <> sum of alphas * betas (%e) in frame %d\n", active_alpha[n_obs-1][q_f], sum_alpha_beta, t); retval = S3_ERROR; goto free; } /* Update beta for all predecessors of the non-emitting * states encountered above */ #if BACKWARD_DEBUG E_INFO("Before updating beta for all predecessors state\n"); #endif for (s = 0; s < n_tmp_non_emit; s++) { j = tmp_non_emit[s]; /*assert(asf_next[j] == TRUE);*/ asf_next[j] = FALSE; prior = state_seq[j].prior_state; tprob = state_seq[j].prior_tprob; for (u = 0; u < state_seq[j].n_prior; u++) { i = prior[u]; for (q = 0; q < n_active_astate[t] && active_astate[t][q] != i; q++); if (q == n_active_astate[t]) { /* state i not active in forward pass; skip it */ continue; } /* accumulate before scaling so scale[t] doesn't appear * in the reestimation sums */ if (rsts_timer) timing_start(rsts_timer); if (tmat_reest) { tacc[i][j-i] += active_alpha[t][q] * tprob[u] * beta[j] * recip_final_alpha; } if (rsts_timer) timing_stop(rsts_timer); assert(tprob[u] > 0); beta[i] += tprob[u] * beta[j]; /*assert(state_seq[i].mixw != TYING_NON_EMITTING);*/ if (asf_next[i] != TRUE) { /* not already on the active list for time t-1 */ asf_next[i] = TRUE; if (state_seq[i].mixw == TYING_NON_EMITTING){ tmp_non_emit[n_tmp_non_emit] = i; n_tmp_non_emit++; }else{ active[n_active] = i; n_active++; } } } } n_next_active = 0; n_tmp_non_emit = 0; /* scale the resulting betas at time t now */ for (s = 0; s < n_active; s++) { i = active[s]; beta[i] *= scale[t]; } if (rstf_timer) timing_start(rstf_timer); if (mean_reest || var_reest) { /* Update the mean and variance reestimation accumulators */ if (pdumpfh) fprintf(pdumpfh, "time %d:\n", t+1); /* We accumulated the posterior probabilities * (a.k.a. fractional counts) for each density above - in * actual fact they are the same as the mixture weight * counts, which are the same as the "dnom" counts. So * now we just have to multiply them by the feature vector * to get the "mean" counts, and do one of two things for * the "variance" counts. */ accum_gauden(denacc, cb_inv, n_lcl_cb, feature[t+1], now_den_idx, g, mean_reest, var_reest, pass2var, inv->l_mixw_acc, var_is_full, pdumpfh, lda); } if (mean_reest || var_reest) memset(&denacc[0][0][0], 0, denacc_size); if (rstf_timer) timing_stop(rstf_timer); /* swap beta and prior beta */ tt = beta; beta = prior_beta; prior_beta = tt; /* swap active state flags and next active state flags */ tt = asf; asf = asf_next; asf_next = tt; } if (gau_timer) timing_start(gau_timer); gauden_compute_log(now_den[state_seq[0].l_cb], now_den_idx[state_seq[0].l_cb], feature[0], g, state_seq[0].cb, NULL); active_cb[0] = state_seq[0].l_cb; gauden_scale_densities_bwd(now_den, now_den_idx, &dscale[0], active_cb, 1, g); op = gauden_mixture(now_den[state_seq[0].l_cb], now_den_idx[state_seq[0].l_cb], mixw[state_seq[0].mixw], g); if (gau_timer) timing_stop(gau_timer); if (retval == S3_SUCCESS) { /* do a final alpha != beta consistency check */ beta[0] = prior_beta[0] * op; if (fabs(beta[0] - active_alpha[n_obs-1][q_f]) > (S2_ALPHA_BETA_EPSILON * active_alpha[n_obs-1][q_f])) { E_ERROR("alpha(%e) <> beta(%e)\n", active_alpha[n_obs-1][q_f], beta[0]); retval = S3_ERROR; } if (beta[0] == 0.0) { E_ERROR("beta underflow\n"); retval = S3_ERROR; } } if ((retval == S3_SUCCESS) && (asf[0] == TRUE)) { l_cb = state_seq[0].l_cb; l_ci_cb = state_seq[0].l_ci_cb; partial_op(p_op, op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[0].mixw], n_feat, n_top); den_terms(d_term, prior_beta[0] * recip_final_alpha, p_op, now_den[l_cb], now_den_idx[l_cb], mixw[state_seq[0].mixw], n_feat, n_top); if (state_seq[0].l_cb != state_seq[0].l_ci_cb) { partial_ci_op(p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[0].ci_mixw], n_feat, n_top); den_terms_ci(d_term_ci, 1.0, /* ASSUMPTION: 1 initial state */ p_ci_op, now_den[l_ci_cb], now_den_idx[l_ci_cb], mixw[state_seq[0].ci_mixw], n_feat, n_top); } if (mixw_reest) { accum_den_terms(wacc[state_seq[0].l_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); /* check if mixw and ci_mixw are different to avoid * doubling of counts in a CI run. Will not affect * final probabilities, but might affect algorithms * which rely on accurate EM counts */ if (state_seq[0].ci_mixw != state_seq[0].mixw) { if (n_cb < inv->n_mixw) { /* semi-continuous, tied mixture, and discrete case */ /* do the update of the CI accumulators as well */ accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term, now_den_idx[l_cb], n_feat, n_top); } else { accum_den_terms(wacc[state_seq[j].l_ci_mixw], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } } if (mean_reest || var_reest) { accum_den_terms(denacc[l_cb], d_term, now_den_idx[l_cb], n_feat, n_top); if (l_cb != l_ci_cb) { accum_den_terms(denacc[l_ci_cb], d_term_ci, now_den_idx[l_ci_cb], n_feat, n_top); } } if (rstf_timer) timing_start(rstf_timer); if (mean_reest || var_reest) { /* Update the mean and variance reestimation accumulators */ if (pdumpfh) fprintf(pdumpfh, "time %d:\n", t+1); accum_gauden(denacc, cb_inv, n_lcl_cb, feature[0], now_den_idx, g, mean_reest, var_reest, pass2var, wacc, var_is_full, pdumpfh, lda); } if (rstf_timer) timing_stop(rstf_timer); } printf(" %d", n_active_tot / n_obs); printf(" %d", n_reest_tot / n_obs); printf(" %e", t_pprob / n_obs); free: ckd_free(active_a); ckd_free(active_b); ckd_free(active_cb); ckd_free(non_emit); ckd_free(tmp_non_emit); ckd_free(asf_a); ckd_free(asf_b); ckd_free(acbframe); if (denacc != NULL) ckd_free_3d((void ***)denacc); ckd_free(beta_a); ckd_free(beta_b); ckd_free_3d((void ***)now_den); ckd_free_3d((void ***)now_den_idx); return (retval); } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.5 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/02/20 00:28:35 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.20 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.19 1996/08/22 10:27:05 eht * - Pruning added based on posterior state probabilities * - Fix some bugs for some combinations of reest(*) flags * - Removed unused vars * * Revision 1.18 1996/08/06 14:03:20 eht * Compute and print out average active emitting beta states * * Revision 1.17 1996/07/29 16:09:47 eht * - Make reestimation accumulation operation (hopefully) more clear. * - Go to (float64) throughout alpha and beta computations * - Scale[t] is now pre-divided for efficiency. * - Test for alpha[t][j] != 0 so that beta is constrained to paths * which existed in the computation of alpha[][]. Got rid of * unreasonable posterior probability errors. * - MLLR reestimation * * Revision 1.16 1996/03/26 13:48:16 eht * - Fixed bbeam bug when it was defined as float32 rather than float64 * - Deal w/ case where many fewer densities referenced by an utt than total # * of densities to train. * * Revision 1.15 1996/03/04 15:59:17 eht * Added more cpu time counters * * Revision 1.14 1996/02/02 17:37:36 eht * Enable pruning again. Need to consider better pruning in the future * * Revision 1.13 1996/01/26 18:23:49 eht * Deal w/ accumulating CI mixture Gaussian counts when only CD mixture Gaussians are present. * * Revision 1.12 1995/12/15 18:37:07 eht * Added some type cases for memory alloc/free * * Revision 1.11 1995/12/14 19:28:35 eht * Add another sanity check assert() * Add code to deal w/ not reestimating each class of parameter (tmat, mixw, mean, var). * * Revision 1.10 1995/12/01 20:54:46 eht * Fixed problem where gamma accumulators are freed when set * to NULL. * * Revision 1.9 1995/11/30 20:48:39 eht * Deal with non-allocation of accumulators when tmat_reest, * mixw_reest, mean_reest and var_reest are off. * * Revision 1.8 1995/10/18 11:18:04 eht * Replaced bcopy() with memset() for ANSI compatibility * * Revision 1.7 1995/10/12 18:30:22 eht * Made state.h a "local" header file * * Revision 1.6 1995/10/10 12:43:50 eht * Changed to use <s3/prim_type.h> * * Revision 1.5 1995/10/09 14:55:33 eht * Change interface to new ckd_alloc routines * * Revision 1.4 1995/09/14 14:19:36 eht * Do some error checking on scale[]. Essentially, the * only scale factor that is not involved in some normalization * in the alpha pass is scale[0], but it doesn't seem to cost * too much to be careful. * * Revision 1.3 1995/08/30 18:33:38 eht * Updated comments * * Revision 1.2 1995/08/09 20:16:19 eht * fix some off-by-one errors * * Revision 1.1 1995/06/02 20:41:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/gauden.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: gauden.h * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef GAUDEN_H #define GAUDEN_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/s3.h> #include <s3/vector.h> #include <stdio.h> typedef struct gauden_s { uint32 n_feat; #ifdef SWIG /* A bug in SWIG - it thinks "const" means "static const" inside a struct. */ uint32 *veclen; #else const uint32 *veclen; #endif uint32 n_mgau; uint32 n_density; uint32 n_top; float32 ***norm; vector_t ***mean; vector_t ***var; vector_t ****fullvar; vector_t ***macc; vector_t ***vacc; vector_t ****fullvacc; float32 ***dnom; vector_t ***l_macc; vector_t ***l_vacc; vector_t ****l_fullvacc; float32 ***l_dnom; } gauden_t; #define MAX_LOG_DEN 10.0 int gauden_set_min_var(float32 min); gauden_t * gauden_alloc(void); int gauden_set_feat(gauden_t *g, uint32 n_feat, const uint32 *veclen); int gauden_set_n_top(gauden_t *g, uint32 n_top); /* # of densities to compute for output prob */ int gauden_set_n_mgau(gauden_t *g, uint32 n); int gauden_set_n_density(gauden_t *g, uint32 n); vector_t *** gauden_mean(gauden_t *g); int gauden_set_mean(gauden_t *g, vector_t ***mean); vector_t *** gauden_var(gauden_t *g); int gauden_set_var(gauden_t *g, vector_t ***variance); vector_t **** gauden_fullvar(gauden_t *g); int gauden_set_fullvar(gauden_t *g, vector_t ****variance); vector_t *** gauden_alloc_param(uint32 n_cb, uint32 n_stream, uint32 n_density, const uint32 *veclen); vector_t **** gauden_alloc_param_full(uint32 n_cb, uint32 n_feat, uint32 n_density, const uint32 *veclen); int gauden_set_const_dim_mgau(gauden_t *g, uint32 n_mgau, /* # of mixture gaussians */ uint32 n_density); /* # of densities per mixture gaussian */ #define gauden_n_mgau(g) (g)->n_mgau #define gauden_n_top(g) (g)->n_top #define gauden_n_feat(g) (g)->n_feat #define gauden_n_density(g) (g)->n_density #define gauden_veclen(g) (g)->veclen int gauden_s2_set_mean(gauden_t *g, uint32 mgau, float32 **mean); int gauden_s2_set_var(gauden_t *g, uint32 mgau, float32 **var); int gauden_floor_variance(gauden_t *g); int gauden_compute(float64 **den, uint32 **den_idx, vector_t *obs, gauden_t *g, uint32 mgau, uint32 **prev_den_idx); /* Previous frame's top N densities (or NULL) */ int gauden_compute_log(float64 **den, uint32 **den_idx, vector_t *obs, gauden_t *g, uint32 mgau, uint32 **prev_den_idx); /* Previous frame's top N densities (or NULL) */ float64 * gauden_scale_densities_fwd(float64 ***den, uint32 ***den_idx, uint32 *cb, uint32 n_cb, gauden_t *g); int gauden_scale_densities_bwd(float64 ***den, uint32 ***den_idx, float64 **scale, uint32 *cb, uint32 n_cb, gauden_t *g); int gauden_compute_euclidean(float64 ***den, uint32 ***den_idx, vector_t *obs, gauden_t *g); int gauden_normalize(float64 ***den, gauden_t *g); /* normalize (n_mgau x n_feat x n_top) density values */ void gauden_print(FILE *fp, float64 ***den, uint32 ***den_idx, gauden_t *g, uint32 *inv, uint32 n_inv); float64 gauden_mixture(float64 **den, uint32 **den_idx, float32 **w, gauden_t *g); void gauden_free(gauden_t *g); void gauden_free_acc(gauden_t *g); int32 gauden_alloc_acc(gauden_t *g); void gauden_free_l_acc(gauden_t *g); int32 gauden_alloc_l_acc(gauden_t *g, uint32 n_lcl, int32 mean_reest, int32 var_reest, int32 fullvar); void gauden_free_param(vector_t ***p); void gauden_free_param_full(vector_t ****p); vector_t ***gauden_l_macc(gauden_t *g); vector_t ***gauden_l_vacc(gauden_t *g); float32 ***gauden_l_dnom(gauden_t *g); void gauden_accum_param(vector_t ***out, vector_t ***in, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen); void gauden_accum_param_full(vector_t ****out, vector_t ****in, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen); void gauden_norm_wt_mean(vector_t ***in_mean, vector_t ***wt_mean, float32 ***dnom, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen); void gauden_norm_wt_var(vector_t ***in_var, vector_t ***wt_var, int32 pass2var, float32 ***dnom, vector_t ***mean, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen, int32 tiedvar); void gauden_norm_wt_fullvar(vector_t ****in_var, vector_t ****wt_var, int32 pass2var, float32 ***dnom, vector_t ***mean, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen, int32 tiedvar); int gauden_eval_precomp(gauden_t *g); int gauden_var_thresh_percentile(vector_t ***var, float32 **var_thresh, uint32 n_mgau, uint32 n_stream, uint32 n_density, const uint32 *veclen, float32 percent); int gauden_smooth_var(vector_t ***var, float32 **var_thresh, uint32 n_mgau, uint32 n_stream, uint32 n_density, const uint32 *veclen); /* primitives */ float32 diag_norm(vector_t var, uint32 len); void diag_eval_precomp(vector_t var, uint32 len); float64 log_diag_eval(vector_t obs, float32 norm, vector_t mean, vector_t var_fact, /* 1 / (2 * sigma ^ 2) */ uint32 veclen); float64 log_full_eval(vector_t obs, float32 norm, vector_t mean, vector_t *var_inv, /* var^-1 */ uint32 veclen); int gauden_massage_var(vector_t ***var, float32 fudge_factor, uint32 n_mgau, uint32 n_stream, uint32 n_density, const uint32 *veclen); #ifdef __cplusplus } #endif #endif /* GAUDEN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2005/09/15 19:31:27 dhdfu * Correct signedness (also sneak in a secret change for a secret project) * * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.5 1996/07/29 16:49:12 eht * made call to gauden_compute() consistent w/ gauden_mixture() * * Revision 1.4 1996/03/25 15:53:14 eht * Changes to deal w/ case where # of densities referenced * by a single utterance is << # total densities * * Revision 1.3 1996/01/26 18:28:23 eht * Added 'const' specifier for veclen argument that is not modified * w/in. * * Revision 1.2 1995/10/10 13:10:34 eht * Changed to use <s3/prim_type.h> * * Revision 1.1 1995/09/08 15:21:06 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/am.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * am.h -- Acoustic model evaluation * * * HISTORY * * 22-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBMAIN_AM_H_ #define _LIBMAIN_AM_H_ #include <libfeat/libfeat.h> #include "gauden.h" #include "senone.h" /* * Data structures needed to evaluate acoustic models in each frame (for a given * acoustic model.) */ typedef struct acoustic_s { feat_t *fcb; /* Feature-type descriptor */ gauden_t *gau; /* READ-ONLY; FOR INTERNAL USE ONLY */ senone_t *sen; /* READ-ONLY; FOR INTERNAL USE ONLY */ float32 ***feat; /* Space for input speech feature vector */ float32 **mfc; /* Space for input speech MFC data */ int32 *dist; /* Density values in a single mixture Gaussian */ int32 mgaubeam; /* (base-logs3). Beamwidth for pruning low-scoring components within a mixture Gaussian. */ int32 *dist_valid; /* Indices of density values (in dist[]) that are above the pruning threshold (mgaubeam) */ int32 n_dist_valid; /* #Valid entries in dist_valid[] */ int32 *senscr; /* Senone score for each senone */ int32 *senscale; /* senscale[f] = scaling applied to senone scores in frame f */ bitvec_t sen_active; /* Boolean flags for senones active in current frame; set (TRUE) iff active */ bitvec_t gauden_active; /* Booleans for which mixtures active in current frame */ float64 tot_dist_valid; /* For active mgau statistics */ int32 tot_mgau_eval; /* For active mgau statistics */ } acoustic_t; /* * Initialize a structure containing intermediate data used in acoustic model evaluation. * Return value: created object if successful, NULL otherwise. */ acoustic_t *acoustic_init (feat_t *f, /* In: Feature-type descriptor */ gauden_t *g, /* In: Mixture Gaussian density codebooks */ senone_t *s, /* In: Senones */ float64 beam, /* In: (See acoustic_t.mgaubeam) Use 1.0 for top-1 and 0.0 for selecting all components (infinite beamwidth) */ int32 maxfr); /* In: Max #frames / utterance */ /* * Compute the normalized acoustic model (senone) scores for the given mfc data. * The normalization is done by subtracting the best raw score from all. * Return value: The best raw senone score, i.e. the normalization factor. * NOTE: am->senscale is NOT updated with this return value; the caller should do this. */ int32 acoustic_eval (acoustic_t *am, /* In/Out: On return am->senscr contains the senone scores (output likelihoods). */ int32 frm); /* In: Frame for which evaluation is to be done. NOTE: If this object needs to compute features from MFC cepstra, neighboring frames might be needed for that purpose. */ #endif <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/hash.h /* ==================================================================== * Copyright (c) 2000 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************** * Hash functions * Hash values are from the following set of "good" hash values * 101, 211, 307, 401, 503, 601, 701, 809, 907, 1009, 1201, 1601, 2003, * 2411, 3001, 4001, 5003, 6007, 7001, 8009, 9001, 10007, 12007, 16001, * 20011, 24001, 30011, 40009, 50021, 60013, 70001, 80021, 90001, 100003, * 120011, 160001, 200003, 240007, 300007, 400009, 500009, 600011, 700001, * 800011, 900001 * * Author: <NAME> *********************************************************************/ #ifndef HASH_H #define HASH_H #include <s3/prim_type.h> #define EOLN -1 #define HASHSIZE 24001 #define DICTHASHSIZE 10007 #define PHNHASHSIZE 101 typedef struct hashelement_t { char *basephone; char *leftcontext; char *rightcontext; char *wordposition; int32 dictcount; int32 count; struct hashelement_t *next; } hashelement_t; typedef struct dicthashelement_t { char *word; char **phones; int32 nphns; struct dicthashelement_t *next; } dicthashelement_t; typedef struct phnhashelement_t { char *phone; int32 count; struct phnhashelement_t *next; } phnhashelement_t; hashelement_t *lookup(char *basephone, char *lctxt, char *rctxt, char *wordposn, hashelement_t **tphnhash); hashelement_t *install(char *basephone, char *lctxt, char *rctxt, char *wordposn, hashelement_t **tphnhash); void freehash(hashelement_t **hash); dicthashelement_t *dictlookup(char *word, dicthashelement_t **dicthash); dicthashelement_t *dictinstall(char *dictword, dicthashelement_t **dicthash); void freedicthash(dicthashelement_t **dicthash); phnhashelement_t *phninstall(char *phone, phnhashelement_t **lhash); void freephnhash(phnhashelement_t **ephnhash); #endif <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/util/JNLPDemoStarter.java package edu.cmu.sphinx.tools.confdesigner.util; import edu.cmu.sphinx.tools.confdesigner.ClassPathParser; import edu.cmu.sphinx.tools.confdesigner.ConfDesigner; import edu.cmu.sphinx.util.props.PropertyException; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * DOCUMENT ME! * * @author <NAME> */ public class JNLPDemoStarter { public static void main(String[] args) throws IOException, PropertyException { ConfDesigner gui = new ConfDesigner(); assert System.getProperty("jnlpx.jvm") != null; List<String> ignoreList = Arrays.asList("jsapi.jar", "org-netbeans-modules-visual-examples.jar", "l2fprod-common-sheet.jar", "org-openide-util.jar", "org-netbeans-api-visual.jar", "xstream-1.2.jar"); gui.addConfigurables(ClassPathParser.getConfigurablesWhileWebstarting(ignoreList)); gui.setBounds(200, 100, 900, 700); gui.setVisible(true); } } <file_sep>/sphinx_fsttools/Makefile sphinxbase_CFLAGS = $(shell pkg-config --cflags sphinxbase) sphinxbase_LIBS = $(shell pkg-config --libs sphinxbase) CPPFLAGS = -I/usr/local/include $(sphinxbase_CFLAGS) CXXFLAGS = -Wno-deprecated -g -O2 -Wall CFLAGS = -g -O2 -Wall LIBS = -L/usr/local/lib -lfst -lpthread $(sphinxbase_LIBS) PROGRAMS = sphinx_am_fst sphinx_dict_fst sphinx_lm_fst ALL:: $(PROGRAMS) sphinx_am_fst: sphinx_am_fst.o mdef.o $(CXX) -o $@ sphinx_am_fst.o mdef.o $(LDFLAGS) $(LIBS) sphinx_dict_fst: sphinx_dict_fst.o mdef.o dict.o $(CXX) -o $@ sphinx_dict_fst.o mdef.o dict.o $(LDFLAGS) $(LIBS) sphinx_lm_fst: sphinx_lm_fst.o $(CXX) -o $@ sphinx_lm_fst.o $(LDFLAGS) $(LIBS) sphinx_dict_fst.o: sphinx_dict_fst.cc mdef.h dict.h sphinx_am_fst.o: sphinx_am_fst.cc mdef.h clean: $(RM) *.o $(PROGRAMS)<file_sep>/archive_s3/s3/src/libfeat/feat_1s_c_wd_dd.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * feat_1s_c_wd_dd.c -- Cepstral feature stream; Sphinx3 version: single vector of * 12 cep, 12 windowed dcep, 3 pow, 12 ddcep. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 10-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <assert.h> #include "feat_1s_c_wd_dd.h" #include <libutil/libutil.h> #include <libio/libio.h> #define N_FEAT 1 #define FEAT_DCEP_WIN 2 static int32 feat_size[1]; static int32 basefeatlen; int32 feat_1s_c_wd_dd_cepsize ( int32 veclen ) { basefeatlen = veclen; feat_size[0] = veclen+veclen+veclen; return (veclen); } int32 feat_1s_c_wd_dd_featsize (int32 **size) { *size = feat_size; return N_FEAT; } /* * Feature vectors computed from input mfc vectors using this window (+/- window). */ int32 feat_1s_c_wd_dd_window_size ( void ) { return (FEAT_DCEP_WIN+2); } void feat_1s_c_wd_dd_cep2feat (float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w, *aw, *_aw, *bw, *_bw; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; int32 i, j; /* CEP; skip C0 */ memcpy (feat[0], mfc[0], basefeatlen * sizeof(float32)); /* * DCEP: mfc[w] - mfc[-w], where w = FEAT_DCEP_WIN; */ f = feat[0] + basefeatlen; w = mfc[ FEAT_DCEP_WIN]; aw = mfc[3]; bw = mfc[4]; _w = mfc[-FEAT_DCEP_WIN]; _aw = mfc[-3]; _bw = mfc[-4]; for (i = 0; i < basefeatlen; i++) f[i] = (bw[i]+aw[i]+w[i] - _w[i]-_aw[i]-_bw[i])/3.0; /* * D2CEP: (mfc[w+1] - mfc[-w+1]) - (mfc[w-1] - mfc[-w-1]), * where w = FEAT_DCEP_WIN */ f += basefeatlen; w1 = mfc[ FEAT_DCEP_WIN+1]; _w1 = mfc[-FEAT_DCEP_WIN+1]; w_1 = mfc[ FEAT_DCEP_WIN-1]; _w_1 = mfc[-FEAT_DCEP_WIN-1]; for (i = 0; i < basefeatlen; i++) { d1 = w1[i] - _w1[i]; d2 = w_1[i] - _w_1[i]; f[i] = d1 - d2; } } <file_sep>/SphinxTrain/src/libs/libs2io/s2_read_tmat.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_read_tmat.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_read_tmat.h> #include <s3/s2_param.h> #include <s3/cmd_ln.h> #include <s3/vector.h> #include <s3/ckd_alloc.h> #include <s3/acmod_set.h> #include <s3/int32_io.h> #include <s3/s3.h> #include <s2/log.h> #include <s2/magic.h> #include <sys_compat/file.h> #include <assert.h> #include <stdio.h> static int premature_eof(FILE *fp) { if (feof(fp)) { E_ERROR("Premature eof found while extracting trans mat\n"); return TRUE; } else return FALSE; } static int read_transition(int32 *from, int32 *to, int32 *prob, int32 *opdf_index, FILE *fp) { if (premature_eof(fp)) return S3_ERROR; *from = read_int32(fp); if (premature_eof(fp)) return S3_ERROR; *to = read_int32(fp); if (premature_eof(fp)) return S3_ERROR; *prob = read_int32(fp); if (premature_eof(fp)) return S3_ERROR; *opdf_index = read_int32(fp); return S3_SUCCESS; } static int rummage_hmm(float **tmat, FILE *fp) { int32 opdf_index; int32 prob = 0; int32 from = 0, to = 0; int32 magic; int32 n_cw; int32 n_omatrix; int32 n_state; int32 n_initial; int32 n_final; int32 n_arc; int32 gbg; uint32 i; if (premature_eof(fp)) return S3_ERROR; magic = read_int32(fp); if (!IS_MAGIC(magic)) { E_ERROR("Invalid HMM magic number found. Byteorder problem? Not an HMM?\n"); return S3_ERROR; } if (premature_eof(fp)) return S3_ERROR; n_cw = read_int32(fp); assert(n_cw == S2_N_CODEWORD); if (premature_eof(fp)) return S3_ERROR; n_omatrix = read_int32(fp); assert(n_omatrix == S2_N_STATE-1); if ((magic == COUNT_F) || (magic == PROB_F)) { /* skip past stored output pdf's */ fseek(fp, (long)(4 * n_omatrix * n_cw * sizeof(int32)), SEEK_CUR); } if (premature_eof(fp)) return S3_ERROR; n_state = read_int32(fp); assert(n_state == S2_N_STATE); if (premature_eof(fp)) return S3_ERROR; n_initial = read_int32(fp); assert(n_initial == 1); if (premature_eof(fp)) return S3_ERROR; gbg = read_int32(fp); assert(gbg == 0); if (premature_eof(fp)) return S3_ERROR; n_final = read_int32(fp); assert(n_final == 1); if (premature_eof(fp)) return S3_ERROR; gbg = read_int32(fp); /* last state is final */ assert(gbg == (S2_N_STATE-1)); if (premature_eof(fp)) return S3_ERROR; n_arc = read_int32(fp); assert(n_arc == 14); for (i = 0; i < n_arc; i++) { read_transition(&from, &to, &prob, &opdf_index, fp); tmat[from][to] = EXP(prob); } return S3_SUCCESS; } static int extract_tmat(float **tmat, const char *in_dir_name, const char *ci_name) { const char *hmm_ext; char ci_hmm_filename[MAXPATHLEN]; FILE *fp; hmm_ext = cmd_ln_access("-hmmext"); sprintf(ci_hmm_filename, "%s/%s.%s", in_dir_name, ci_name, hmm_ext); fp = fopen(ci_hmm_filename, "rb"); if (fp == NULL) { fflush(stdout); fprintf(stderr, "%s(%d): can't open %s for reading to extract tmat\n", __FILE__, __LINE__, ci_hmm_filename); fflush(stderr); return S3_ERROR; } if (rummage_hmm(tmat, fp) != S3_SUCCESS) return S3_ERROR; fclose(fp); return S3_SUCCESS; } int normalize_floor_tmat(float **tmat, float32 tprob_floor, int n_state) { uint32 i; int32 r, ret_val; ret_val = S3_SUCCESS; for (i = 0; i < n_state-1; i++) { vector_normalize(tmat[i], n_state); /* set non-zero (but "small") tprobs to floor value */ vector_nz_floor(tmat[i], n_state, tprob_floor); r = vector_normalize(tmat[i], n_state); if (r != S3_SUCCESS) ret_val = r; } return ret_val; } void print_tmat(FILE *fp, float **tmat, int n_state) { uint32 i, j; for (i = 0; i < n_state-1; i++) { for (j = 0; j < n_state; j++) { fprintf(fp, "(%u %u) == %f\n", i, j, tmat[i][j]); } } } float32 *** s2_read_tmat(const char *in_dir_name, acmod_set_t *acmod_set, float32 tprob_floor) { float32 ***tmat; uint32 n_ci; uint32 i, j, k; int err; n_ci = acmod_set_n_ci(acmod_set); fflush(stdout); fprintf(stderr, "%s(%d): reading %d tied CI transition matrices from %s\n", __FILE__, __LINE__, n_ci, in_dir_name); tmat = (float ***)ckd_calloc_3d(n_ci, S2_N_STATE-1, S2_N_STATE, sizeof(float)); fflush(stdout); fprintf(stderr, "%s(%d): applying floor %e\n", __FILE__, __LINE__, tprob_floor); fflush(stderr); err = 0; for (i = 0; i < n_ci; i++) { for (j = 0; j < S2_N_STATE-1; j++) { for (k = 0; k < S2_N_STATE; k++) { tmat[i][j][k] = 0.0; } } if (extract_tmat(tmat[i], in_dir_name, acmod_set_id2name(acmod_set, i)) != S3_SUCCESS) err = 1; #ifdef S2_READ_TMAT_VERBOSE if (!err) { print_tmat(stdout, tmat[i], S2_N_STATE); fflush(stdout); } #endif } if (!err) { return tmat; } else { return NULL; } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.10 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.9 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.8 1995/10/17 14:03:23 eht * Changed to port to Windows NT * * Revision 1.7 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.6 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.5 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.4 1995/09/07 19:25:05 eht * Change read_long to read_int32 for machines where sizeof(long) != sizeof(int) * * Revision 1.3 95/08/09 20:32:05 20:32:05 eht (<NAME>) * No normalization of counts. * * Revision 1.2 1995/06/02 20:30:30 eht * Add PWP's error reporting stuff * * Revision 1.1 1995/05/22 19:19:38 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/exp/gauden/subvq.h /* * subvq.h * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 12-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _GAUDEN_SUBVQ_ #define _GAUDEN_SUBVQ_ #include <libutil/libutil.h> #include <libmisc/vector.h> typedef struct { arraysize_t origsize; /* origsize.r = #codebooks (or states) in original model; origsize.c = max #codewords/codebook in original model */ int32 n_sv; /* #Subvectors */ int32 vqsize; /* #Codewords in each subvector quantized mean/var table */ int32 *svsize; /* Length of each subvector */ int32 **featdim; /* featdim[s] = Original feature dimensions in subvector s */ float32 ***mean; /* mean[s] = vector quantized means for subvector s (of size vqsize x svsize[s]) */ float32 ***var; /* var[s] = vector quantized vars for subvector s (vqsize x svsize[s] vectors) */ float32 **idet; /* Covariance matrix determinants for this subvq table; actually, log (1/(det x (2pi)^k)), the usual thing. */ int32 ***map; /* map[i][j] = map from original codebook(i)/codeword(j) to sequence of nearest vector quantized subvector codewords; so, each map[i][j] is of length n_sv. */ bitvec_t cb_invalid; /* Flag for each codebook; TRUE iff entire map for that codebook is invalid */ } subvq_t; /* * SubVQ file format: * VQParam #Original-Codebooks #Original-Codewords/codebook(max) -> #Subvectors #VQ-codewords * Subvector 0 length <length> <feature-dim> <feature-dim> <feature-dim> ... * Subvector 1 length <length> <feature-dim> <feature-dim> <feature-dim> ... * ... * Codebook 0 * Row 0 of mean/var values (interleaved) for subvector 0 codebook (in 1 line) * Row 1 of above * Row 2 of above * ... * Map 0 * Mappings for state 0 codewords (in original model) to codewords of this subvector codebook * Mappings for state 1 codewords (in original model) to codewords of this subvector codebook * Mappings for state 1 codewords (in original model) to codewords of this subvector codebook * ... * Repeated for each subvector codebook 1 * Repeated for each subvector codebook 2 * ... * End */ subvq_t *subvq_init (char *file); void subvq_free (subvq_t *s); /* * Compare the input vector to all the subvector codewords in the given codebook, after breaking * up the input into subvectors, appropriately, of course. Enter the computed Mahalanobis * distances, converted into logs3 values, into the given score array. Note the shape of the * score array: vqsize x n_sv. */ void subvq_dist_eval (subvq_t *vq, float32 *vec, int32 **score); /* Out: Mahalanobis distance scores (logs3 values), of size and shape vq->vqsize x vq->n_sv. Caller must allocate this array. */ #endif <file_sep>/SphinxTrain/src/programs/dict2tri/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 <NAME>. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ find the triphone list from the dictionary"; const char examplestr[] = "Example : \n\ This compute both the cross-word triphones and internal triphones, \n\ dict2tri -dictfn dict -basephnfn phonelist -btwtri yes \n\ \n\ This compute only the cross-word triphones, \n\ dict2tri -dictfn dict -basephnfn phonelist -btwtri no \n\ \n"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary file name" }, { "-basephnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Base phone list file name"}, { "-btwtri", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Compute between-word triphone set"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/11/29 01:43:45 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.4 2004/11/29 01:11:19 egouvea * Fixed license terms in some new files. * * Revision 1.3 2004/11/29 00:49:20 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.2 2004/08/08 03:56:20 arthchan2003 * dict2tri help and example * * Revision 1.1 2004/06/17 19:39:47 arthchan2003 * add back all command line information into the code * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/mllr_transform/parse_cmd_ln.c /********************************************************************* * * $Header$ * * Carnegie Mellon ARPA Speech Group * * Copyright (c) 1995 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: parse_cmd_ln.c * * Traceability: * * Description: * * Author: * $Author$ *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; #include "cmd_ln_defn.h" cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/11/29 01:43:51 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.3 2004/08/07 20:25:47 arthchan2003 * Add help and example string for mllr_solve. Fix help and example logic for mllr_solve and mllr_transfrom * * Revision 1.2 2004/08/03 07:23:12 arthchan2003 * Check in the code for usage and example of mllr_transform * * Revision 1.1 2004/07/26 05:04:20 arthchan2003 * mllr_transform committed, it is an adaptation of Sam Joo's mllr_adapt * * Revision 1.1 97/03/07 08:53:38 eht * Initial revision * * Revision 1.4 1996/01/30 17:06:44 eht * Include "-gaucntfn" argument and coalesce "-meanfn" and "-varfn" * into "-gaufn" * * Revision 1.3 1995/09/07 20:03:56 eht * Include defn of TRUE/FALSE for machines like HP's running HPUX * * Revision 1.2 1995/08/09 20:37:06 eht * *** empty log message *** * * Revision 1.1 1995/06/02 20:36:50 eht * Initial revision * * */ <file_sep>/cmudict/scripts/README.txt Maintenance scripts for cmudict ------------------------------- [20100118] (air) Use these scripts for checking and compiling the dictionary. The process is the following: 1) make changes to the dictionary - it's assumed that the changes are manual - check your work by doing a svn diff with the previous version 2) run scripts/test_cmudict.pl EG: ./scripts/test_cmudict.pl -p cmudict.0.7a.phones cmudict.0.7a - this checks for collation order, legal entry format and phonetic symbols - if necessary fix problems then repeat this step until no errors 3) run CompileDictionary* [converts cmudict to the Sphinx format using make_baseform.pl] [checks for consistency using test_dict.pl] - produces two *_SPHINX_40 files; one generic the other major-versioned 4) use svn to update cmudict; be sure to add a proper logging message That's it! <file_sep>/CLP/include/Prob.h #ifndef _Prob_h_ #define _Prob_h_ #include <math.h> #include <assert.h> #define LSMALL (-0.5E10) #define LZERO (-1.0E10) #define MINEARG (-708.3) typedef double LnProb; /* * The sum of two log probs: LogPlus(x,y) = log(e^x + e^y) */ inline double LogPlus(double x, double y) { if (x<y) { double tmp = x; x=y; y=tmp; } double diff = y-x; if (diff< MINEARG) if (x < 0) return (x< LSMALL)? LZERO:x; else return x; else { double z = exp(diff); return x + log(1.0+z); } } /////////////////////////////////////////////////////// /* The difference of two log probs: LogMinus(x,y) = log(e^x - e^y) * */ inline double LogMinus(double x, double y) { assert(x >= y); if (x=y){ return LZERO; } else{ double diff = y-x; if (diff< MINEARG) if (x < 0) return (x<LSMALL)?LZERO:x; else return x; else{ double z = exp(diff); return x + log(1.0 - z); } } } #endif <file_sep>/archive_s3/s3.0/src/libmain/cmn.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * cmn.c -- Various forms of cepstral mean normalization * * * HISTORY * * 19-Jun-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed to compute CMN over ALL dimensions of cep instead of 1..12. * * 04-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include <libutil/libutil.h> #include "cmn.h" void cmn (float32 **mfc, int32 n_frame, int32 veclen) { static float32 *mean = 0; float *mfcp; int32 i, f; assert ((n_frame > 0) && (veclen > 0)); if (mean == 0) mean = (float32 *) ckd_calloc (veclen, sizeof (float32)); for (i = 0; i < veclen; i++) mean[i] = 0.0; for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mean[i] += mfcp[i]; } for (i = 0; i < veclen; i++) mean[i] /= n_frame; for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mfcp[i] -= mean[i]; } } <file_sep>/archive_s3/s3/doc/s3-2_files/Makefile # ==================================================================== # Copyright (c) 1995-2002 Carnegie Mellon University. All rights # reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # # ==================================================================== # Copyright (c) 2000 Carnegie Mellon University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 3. The names "Sphinx" and "<NAME>" must not be used to # endorse or promote products derived from this software without # prior written permission. To obtain permission, contact # <EMAIL>. # # 4. Products derived from this software may not be called "Sphinx" # nor may "Sphinx" appear in their names without prior written # permission of Carnegie Mellon University. To obtain permission, # contact <EMAIL>. # # 5. Redistributions of any form whatsoever must retain the following # acknowledgment: # "This product includes software developed by Carnegie # Mellon University (http://www.speech.cs.cmu.edu/)." # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # # # ==================================================================== TOP=../.. DIRNAME=doc/s3-2_files BUILD_DIRS = ALL_DIRS= DFILES = \ buttons.gif error.htm filelist.xml frame.htm fullscreen.htm \ master01.htm master02.htm master03.htm master03.xml \ master03_image002.gif master03_stylesheet.css outline.htm pres.xml \ preview.wmf script.js slide0001.htm slide0001_image001.gif \ slide0004.htm slide0005.htm slide0006.htm slide0007.htm slide0008.htm \ slide0009.htm slide0010.htm slide0011.htm slide0012.htm \ slide0012_image003.gif slide0015.htm slide0015_image004.gif \ slide0015_image005.gif slide0015_image006.gif slide0015_image007.gif \ slide0015_image008.gif slide0016.htm slide0016.xml \ slide0016_image009.gif slide0016_image010.gif slide0016_image011.gif \ slide0016_image012.gif slide0016_image013.gif slide0016_image014.gif \ slide0016_image015.gif slide0016_image016.gif slide0016_image017.gif \ slide0016_image018.gif slide0016_image019.gif slide0016_image020.gif \ slide0017.htm slide0017.xml slide0017_image021.gif \ slide0017_image022.gif slide0017_image023.gif slide0017_image024.gif \ slide0017_image025.gif slide0017_image026.gif slide0017_image027.gif \ slide0017_image028.gif slide0017_image029.gif slide0017_image030.gif \ slide0017_image031.gif slide0018.htm slide0018.xml \ slide0018_image032.gif slide0019.htm slide0020.htm \ slide0020_image033.gif slide0021.htm slide0021_image034.gif \ slide0022.htm slide0022_image035.gif slide0023.htm \ slide0023_image036.gif slide0024.htm slide0024_image037.gif \ slide0026.htm slide0026_image038.gif slide0027.htm slide0028.htm \ slide0028_image039.gif slide0029.htm slide0029.xml \ slide0029_image040.gif slide0030.htm slide0030.xml \ slide0030_image041.gif slide0031.htm slide0031_image042.gif \ slide0032.htm slide0032_image043.gif slide0033.htm slide0034.htm \ slide0034_image044.gif slide0035.htm slide0035_image045.gif \ slide0036.htm slide0036_image046.gif slide0037.htm \ slide0037_image047.gif slide0038.htm slide0038_image048.gif \ slide0039.htm slide0040.htm slide0041.htm FILES = Makefile $(DFILES) ALL = include $(TOP)/config/common_make_rules <file_sep>/SphinxTrain/src/libs/libcommon/prefetch.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * prefetch.c -- a simple interface to set up prefetching of files that * a program will be opening soon. * * By <NAME>, CMU Speech Group, May 23, 1995. * (Thanks to <NAME> suggesting the open, read one char, close idea.) */ /* #ifndef WIN32 */ #if 0 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/param.h> #include <sys_compat/file.h> #endif /***************************************************************** * The general idea here is to spawn off a child process on start-up, * with a pipe between the master and the child. * * Whenever the master wants to prefetch a file, it writes the name * of the file, terminated by a newline, to the child. * * The child reads the names of files, and for each one, tries * to open the file, read the first byte, and close the file. * This will have the effect of putting the file info block, and * the first block of data, into the file buffer cache of the kernel. * * The pipe is set to be non-blocking on the master side, since * it would be silly for the master to block waiting for the child, * when what we are really trying to do is speed things up. ***************************************************************** */ /* #define TESTING */ /* #ifndef WIN32 */ #if 0 static int _fd_to_prefetch = -1; static pid_t _pid_of_prefetch = -1; int prefetch_init() { pid_t pid; int p_fd[2]; FILE *fp_from_prefetch; return 0; if (pipe(p_fd) < 0) { perror("WARNING: pipe()"); fflush(stderr); return -1; } #ifdef TESTING printf("MASTER pipe fds == %d, %d\n", p_fd[0], p_fd[1]); fflush(stdout); #endif /* TESTING */ pid = fork(); if (pid < 0) { perror("WARNING: fork()"); fflush(stderr); return -1; } #ifdef TESTING printf("MASTER pid == %d\n", pid); fflush(stdout); #endif /* TESTING */ if (pid == 0) { /* child */ char buf[MAXPATHLEN+1]; char *cp; char dummy; int fd; close (p_fd[1]); /* close the writing side of the pipe */ if ((fp_from_prefetch = fdopen(p_fd[0], "r")) == NULL) { perror("WARNING: fdopen()"); fflush(stderr); exit (7); } for (;;) { if (fgets(buf, MAXPATHLEN, fp_from_prefetch) == NULL) { #ifdef TESTING perror("CHILD: fgets()"); fflush(stderr); printf("CHILD read failed\n"); fflush(stdout); #endif /* TESTING */ exit (0); /* file error: master probably died */ } /* remove the trailing newline. */ if ((cp = strrchr (buf, '\n')) != NULL) *cp = '\0'; #ifdef TESTING printf("CHILD read \"%s\"\n", buf); fflush(stdout); #endif /* TESTING */ if ((fd = open(buf, O_RDONLY, 0)) < 0) { #ifdef TESTING perror("CHILD open()"); fflush(stderr); printf("CHILD could not open \"%s\"; continuing\n", buf); fflush(stdout); #endif /* TESTING */ continue; } #ifdef TESTING printf("CHILD opened \"%s\" as fd %d\n", buf, fd); fflush(stdout); #endif /* TESTING */ if (read(fd, &dummy, 1) != 1) { #ifdef TESTING perror("CHILD read()"); fflush(stderr); printf("CHILD could not read from \"%s\"\n", buf); fflush(stdout); #endif /* TESTING */ } close(fd); } /* end for(;;) */ } else { /* parent */ close (p_fd[0]); /* close the reading side of the pipe */ _fd_to_prefetch = p_fd[1]; _pid_of_prefetch = pid; #ifndef _HPUX_SOURCE if (fcntl(_fd_to_prefetch, F_SETFL, FNDELAY)) { perror("WARNING: fcntl()"); fflush(stderr); return -1; } #else if (fcntl(_fd_to_prefetch, F_SETFL, O_NDELAY)) { perror("WARNING: fcntl()"); fflush(stderr); return -1; } #endif return 0; } } int prefetch_hint(fn) char *fn; { char buf[MAXPATHLEN+1]; char *p; int i, l; extern int errno; return 0; if (fn == NULL) return -1; if (_fd_to_prefetch < 0) return -2; #ifdef TESTING printf("MASTER writing \"%s\"\n", fn); fflush(stdout); #endif /* TESTING */ strncpy(buf, fn, MAXPATHLEN); buf[MAXPATHLEN] = '\0'; l = strlen(buf); buf[l++] = '\n'; buf[l] = '\0'; p = buf; i = write(_fd_to_prefetch, p, l); if (i < 0) { if (errno == EWOULDBLOCK) return 1; else return -1; } for (l -= i, p += i; l > 0; l -= i, p += i) { i = write(_fd_to_prefetch, p, l); if (i < 0) { if (errno == EWOULDBLOCK) { i = 0; } else { return -1; } } } #ifdef TESTING printf("MASTER done.\n"); fflush(stdout); #endif /* TESTING */ return 0; /* success */ } int prefetch_finish() { int status; if (_fd_to_prefetch < 0) return -2; #ifdef TESTING printf("MASTER closing fd %d.\n", _fd_to_prefetch); fflush(stdout); #endif /* TESTING */ close(_fd_to_prefetch); /* may cause child to exit */ _fd_to_prefetch = -1; #ifdef TESTING printf("MASTER waiting for pid %d.\n", _pid_of_prefetch); fflush(stdout); #endif /* TESTING */ (void) kill (_pid_of_prefetch, SIGINT); /* kill the child just in case */ /* reap the child process */ while (waitpid(_pid_of_prefetch, &status, 0) < 0) { if (errno != EINTR) { perror("WARNING: waitpid()"); fflush(stderr); return -1; } #ifdef TESTING printf("MASTER still waiting for pid %d.\n", _pid_of_prefetch); fflush(stdout); #endif /* TESTING */ } _pid_of_prefetch = -1; #ifdef TESTING printf("MASTER finished.\n"); fflush(stdout); #endif /* TESTING */ return 0; } #else /* WIN32 */ /* Just define some stubs for now */ int prefetch_init() { return 0; } int prefetch_hint(char *fn) { return 0; } int prefetch_finish() { return 0; } #endif #ifdef TESTING main(argc, argv) int argc; char *argv[]; { prefetch_init(); argv++; /* skip program name */ while (*argv) { prefetch_hint(*argv++); } sleep (10); prefetch_finish(); exit (0); } #endif /* TESTING */ <file_sep>/tools/riddler/java/edu/cmu/sphinx/tools/riddler/persist/Audio.java /** * Copyright 1999-2007 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * <p/> * User: <NAME> * Date: Jan 13, 2007 * Time: 8:32:49 PM */ package edu.cmu.sphinx.tools.riddler.persist; import edu.cmu.sphinx.tools.riddler.persist.audio.AudioDescriptor; import javax.persistence.*; import java.util.List; import java.util.ArrayList; /** * Unique identifier for a piece of audio data. Audio data belongs to an Item and consists of one or more * RegionOfAudio records. * @author <NAME> */ @Entity public class Audio { @Id @GeneratedValue(strategy = GenerationType.TABLE) private String id; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private AudioDescriptor audioDescriptor; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="audio") private List<RegionOfAudio> audioRegions = new ArrayList<RegionOfAudio>(); /** * parent reference, for bi-directional fetching */ @OneToOne private Item item; public Audio(AudioDescriptor audioDescriptor, List<RegionOfAudio> audioRegions) { this.audioDescriptor = audioDescriptor; this.audioRegions = audioRegions; } public Audio() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<RegionOfAudio> getAudioRegions() { return audioRegions; } public void setAudioRegions(List<RegionOfAudio> audioRegions) { this.audioRegions = audioRegions; } public AudioDescriptor getAudioDescriptor() { return audioDescriptor; } public void setAudioDescriptor(AudioDescriptor audioDescriptor) { this.audioDescriptor = audioDescriptor; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } } <file_sep>/archive_s3/s3.2/src/libutil/io.h /* * io.h -- Packaged I/O routines. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 08-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added stat_mtime(). * * 11-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added _myfopen() and myfopen macro. * * 05-Sep-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _LIBUTIL_IO_H_ #define _LIBUTIL_IO_H_ #include <stdio.h> #include <sys/stat.h> #include "prim_type.h" /* * Like fopen, but use popen and zcat if it is determined that "file" is compressed * (i.e., has a .z, .Z, .gz, or .GZ extension). */ FILE *fopen_comp (char *file, /* In: File to be opened */ char *mode, /* In: "r" or "w", as with normal fopen */ int32 *ispipe); /* Out: On return *ispipe is TRUE iff file was opened via a pipe */ /* * Close a file opened using fopen_comp. */ void fclose_comp (FILE *fp, /* In: File pointer to be closed */ int32 ispipe); /* In: ispipe argument that was returned by the corresponding fopen_comp() call */ /* * Open a file for reading, but if file not present try to open compressed version (if * file is uncompressed, and vice versa). */ FILE *fopen_compchk (char *file, /* In: File to be opened */ int32 *ispipe); /* Out: On return *ispipe is TRUE iff file was opened via a pipe */ /* * Wrapper around fopen to check for failure and E_FATAL if failed. */ FILE *_myfopen(char *file, char *mode, char *pgm, int32 line); /* In: __FILE__, __LINE__ from where called */ #define myfopen(file,mode) _myfopen((file),(mode),__FILE__,__LINE__) /* * NFS file reads seem to fail now and then. Use the following functions in place of * the regular fread. It retries failed freads several times and quits only if all of * them fail. Be aware, however, that even normal failures such as attempting to read * beyond EOF will trigger such retries, wasting about a minute in retries. * Arguments identical to regular fread. */ int32 fread_retry(void *pointer, int32 size, int32 num_items, FILE *stream); /* * Like fread_retry, but for stat. Arguments identical to regular stat. * Return value: 0 if successful, -1 if stat failed several attempts. */ int32 stat_retry (char *file, struct stat *statbuf); /* * Return time of last modification for the given file, or -1 if stat fails. */ int32 stat_mtime (char *file); #endif <file_sep>/SphinxTrain/src/programs/mllr_solve/main.c /* ==================================================================== * Copyright (c) 1999-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * * 2004-07-26 : ARCHAN (<EMAIL>) at Carnegie Mellon Unversity * First adapted from SamJoo's package. */ #include "parse_cmd_ln.h" /* The SPHINX-III common library */ #include <s3/common.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3gau_io.h> #include <s3/s3acc_io.h> #include <s3/gauden.h> #include <s3/regmat_io.h> #include <s3/matrix.h> #include <s3/feat.h> #include <s3/mllr.h> #include <s3/mllr_io.h> #include <s3/s3cb2mllr_io.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s2/log.h> #include <sys_compat/file.h> #include <sys_compat/misc.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <string.h> #define ABS(x) ((x) < 0 ? (-(x)) : (x)) #define VAR_CONST 0.5 static int initialize(int argc, char *argv[]) { /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); return S3_SUCCESS; } /******************************************************************** * Make MLLR matrix A and B using conventional MLLR method ********************************************************************/ int mllr_mat(float32 *****out_A, float32 ****out_B, const char *var_fn, vector_t ***mean, vector_t ***wt_mean, /* read from bw accum */ float32 ***wt_dcount, /* read from bw accum */ uint32 gau_begin, int32 *cb2mllr, uint32 mllr_mult, uint32 mllr_add, float32 varfloor, uint32 n_mgau, uint32 n_stream, uint32 n_density, uint32 n_mllr_class, const uint32 *veclen) { vector_t ***var = NULL; float32 ****A = NULL; float32 ***B = NULL; float32 *****regl = NULL; float32 ****regr = NULL; float32 wt_mean_var; float32 wt_dcount_var; float32 wt_dcount_var_mean; float32 *tmean = NULL; uint32 n_mgau_rd; uint32 n_stream_rd; uint32 n_density_rd; const uint32 *veclen_rd = NULL; uint32 i, j, k, l, s, p , q; int32 m, mc; int32 len=0; /* uint32 i, j, k, l, p, q, s; int32 m, mc, mi; */ E_INFO("\n"); E_INFO(" ---- mllr_solve(): Conventional MLLR method\n"); if (cmd_ln_int32("-fullvar")) { /* Extract diagonals to solve MLLR (we are not doing variance adaptation, yet) */ vector_t ****fullvar; uint32 i, j, k, l; if (s3gau_read_full(var_fn, &fullvar, &n_mgau_rd, &n_stream_rd, &n_density_rd, &veclen_rd) != S3_SUCCESS) { E_FATAL("Couldn't read %s", var_fn); } var = gauden_alloc_param(n_mgau_rd, n_stream_rd, n_density_rd, veclen_rd); for (i = 0; i < n_mgau_rd; ++i) for (j = 0; j < n_stream_rd; ++j) for (k = 0; k < n_density_rd; ++k) for (l = 0; l < veclen_rd[j]; ++l) var[i][j][k][l] = fullvar[i][j][k][l][l]; gauden_free_param_full(fullvar); } else { if (s3gau_read(var_fn, &var, &n_mgau_rd, &n_stream_rd, &n_density_rd, &veclen_rd) != S3_SUCCESS) { E_FATAL("Couldn't read %s", var_fn); } } if (n_mgau != n_mgau_rd) { E_FATAL("n_mgau mismatch (%u : %u)\n",n_mgau,n_mgau_rd); } if (n_stream != n_stream_rd) { E_FATAL("n_stream mismatch (%u : %u)\n",n_stream,n_stream_rd); } if (n_density != n_density_rd) { E_FATAL("n_density mismatch (%u : %u)\n",n_density,n_density_rd); } for (s = 0; s < n_stream; s++) { if (veclen[s] != veclen_rd[s]) { E_FATAL("vector length of stream %u (== %u) " "!= prior length (== %u)\n", s, veclen_rd[s], veclen[s]); } } ckd_free((void *)veclen_rd); veclen_rd = NULL; /* Invert variances. */ for (i = 0; i < n_mgau; i++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { for (l = 0; l < veclen[j]; l++) { if (var[i][j][k][l] <= 0.) { var[i][j][k][l] = VAR_CONST; } else if (var[i][j][k][l] < varfloor) { var[i][j][k][l] = 1. / varfloor; } else { var[i][j][k][l] = 1. / var[i][j][k][l]; } } } } } fprintf(stderr,"\n"); E_INFO(" ---- A. Accum regl, regr\n"); E_INFO(" No classes %d, no. stream %d\n",n_mllr_class,n_stream); /* Legetter's set of G matrices, one per dimension per class. */ regl = (float32 *****)ckd_calloc_2d(n_mllr_class, n_stream, sizeof(float32 ***)); /* Legetter's Z matrices, one per class. */ regr = (float32 ****) ckd_calloc_2d(n_mllr_class, n_stream, sizeof(float32 **)); for (i = 0; i < n_mllr_class; i++) { for (j = 0; j < n_stream; j++) { len = veclen[j]; regl[i][j] = (float32 ***)ckd_calloc_3d(len, len+1, len+1, sizeof(float32)); regr[i][j] = (float32 **) ckd_calloc_2d(len, len+1, sizeof(float32)); } } /* E_INFO(" Checking\n");*/ for (i = gau_begin; i < n_mgau; i++) { mc = cb2mllr[i]; if (mc < 0) continue; /* skip */ for (j = 0; j < n_stream; j++) { len=veclen[j]; for (k = 0; k < n_density; k++) { if (wt_dcount[i][j][k] > 0.) { tmean = mean[i][j][k]; for (l = 0; l < len; l++) { wt_mean_var = wt_mean[i][j][k][l] * var[i][j][k][l]; wt_dcount_var = wt_dcount[i][j][k] * var[i][j][k][l]; for (p = 0; p < len; p++) { wt_dcount_var_mean = wt_dcount_var * tmean[p]; for (q = p; q < len; q++) { /* This is g(l)_{pq} = sum_r(v_{ii}(r) d_{pq}(r))*/ /* or in other words sum(likelihood * invvar * outer(mean, mean)) */ regl[mc][j][l][p][q] += (float32) (wt_dcount_var_mean * tmean[q]); } /* G corresponding to extended element of q. */ regl[mc][j][l][p][len] += (float32)(wt_dcount_var_mean); /* This is z_{lp} = sum(likelihood * invvar * obs * mean_p) */ regr[mc][j][l][p] += (float32)(wt_mean_var * tmean[p]); } /* G corresponding to extended element of p and q. */ /* Question: what about regl[mc][j][l][len][0..len]? */ /* Answer: G(l) is symmetric, so we already calculated them. */ regl[mc][j][l][len][len] += (float32)wt_dcount_var; /* Z corresponding to extended element of p. */ regr[mc][j][l][len] += (float32)(wt_mean_var); } } } } } gauden_free_param(mean); gauden_free_param(wt_mean); ckd_free_3d((void ***)wt_dcount); /* Fill in the lower triangular part of regl. */ for (m = 0; m < n_mllr_class; m++) { for (j = 0; j < n_stream; j++) { for (l = 0; l < veclen[j]; l++) { for (p = 0; p <= veclen[j]; p++) { for (q = p+1; q <= veclen[j]; q++) { regl[m][j][l][q][p] = regl[m][j][l][p][q]; } } } } } E_INFO(" ---- B. Compute MLLR matrices (A,B)\n"); if(compute_mllr(regl, regr, veclen, n_mllr_class, n_stream, mllr_mult, mllr_add, &A, &B) != S3_SUCCESS) { E_FATAL("MLLR computation failed\n"); } free_mllr_reg(regl,regr, n_mllr_class, n_stream); *out_A = A; *out_B = B; return S3_SUCCESS; } int main(int argc, char *argv[]) { const char *out_mllr_fn; const char **accum_dir; const char *mean_fn; const char *var_fn; const char *cb2mllrfn; const char *moddeffn; uint32 cdonly; uint32 mllr_mult; /* option 0 or 1 */ uint32 mllr_add; /* option 0 or 1 */ float32 varfloor; vector_t ***mean = NULL; /* baseline mean */ vector_t ***wt_mean = NULL; /* read from bw accum */ float32 ***wt_dcount = NULL; /* read from bw accum */ vector_t ***wt_var = NULL; /* not used */ int32 pass2var; /* not used */ uint32 n_mgau; uint32 n_stream; uint32 n_density; uint32 n_mllr_class; uint32 n_mgau_rd; uint32 n_stream_rd; uint32 n_density_rd; const uint32 *veclen = NULL; const uint32 *veclen_rd = NULL; float32 ****A = NULL; /* Output mllr: A */ float32 ***B = NULL; /* Output mllr: B */ int32 *cb2mllr = NULL; /* int32 **mllr2cb = NULL; int32 *n_mllr2cb = NULL;*/ model_def_t *mdef; uint32 gau_begin; uint32 i,s ; if (initialize(argc, argv) != S3_SUCCESS) { E_FATAL("errors initializing.\n"); } out_mllr_fn = (const char *) cmd_ln_access("-outmllrfn"); accum_dir = (const char **) cmd_ln_access("-accumdir"); mean_fn = (const char *) cmd_ln_access("-meanfn"); var_fn = (const char *) cmd_ln_access("-varfn"); cb2mllrfn = (const char *) cmd_ln_access("-cb2mllrfn"); cdonly = *(uint32 *) cmd_ln_access("-cdonly"); moddeffn = (const char *) cmd_ln_access("-moddeffn"); mllr_mult = *(uint32 *) cmd_ln_access("-mllrmult"); mllr_add = *(uint32 *) cmd_ln_access("-mllradd"); varfloor = *(float32 *) cmd_ln_access("-varfloor"); assert(accum_dir[0] != NULL); /* must be at least one accum dir */ if (! (out_mllr_fn && accum_dir && mean_fn)) { E_FATAL("Some of options are missing.\n"); } if (varfloor < 0.) { E_FATAL("varfloor is negative (%e)\n",varfloor); } if (cb2mllrfn && strcmp(cb2mllrfn,"NO") == 0) { cb2mllrfn = NULL; } if (moddeffn && strcmp(moddeffn,"NO") == 0) { moddeffn = NULL; } /*--------------------------------------------------------------------*/ fprintf(stderr,"\n"); E_INFO("-- 1. Read input mean, (var) and accumulation.\n"); /*--------------------------------------------------------------------*/ /*-------------- Read baseline mean --------------*/ if (s3gau_read(mean_fn, &mean, &n_mgau, &n_stream, &n_density, &veclen) != S3_SUCCESS) { E_FATAL("Couldn't read %s", mean_fn); } /*-------- Read accum_dir (accumulation from bw) --------*/ for (i = 0; accum_dir[i]; i++) { E_INFO("Reading and accumulating counts from %s\n", accum_dir[i]); if (rdacc_den(accum_dir[i], &wt_mean, &wt_var, &pass2var, &wt_dcount, &n_mgau_rd, &n_stream_rd, &n_density_rd, &veclen_rd) != S3_SUCCESS) { E_FATAL("Error in reading %s\n", accum_dir[i]); } } if (n_mgau != n_mgau_rd) { E_FATAL("n_mgau mismatch (%u : %u)\n",n_mgau,n_mgau_rd); } if (n_stream != n_stream_rd) { E_FATAL("n_stream mismatch (%u : %u)\n",n_stream,n_stream_rd); } if (n_density != n_density_rd) { E_FATAL("n_density mismatch (%u : %u)\n",n_density,n_density_rd); } for (s = 0; s < n_stream; s++) { if (veclen[s] != veclen_rd[s]) { E_FATAL("vector length of stream %u (== %u) " "!= prior length (== %u)\n", s, veclen_rd[s], veclen[s]); } } ckd_free((void *)veclen_rd); veclen_rd = NULL; if (wt_var) { /* We don't use 'wt_var' in this program. */ gauden_free_param(wt_var); wt_var = NULL; } /*--------------------------------------------------------------------*/ fprintf(stderr,"\n"); E_INFO("-- 2. Read cb2mllrfn\n"); /*--------------------------------------------------------------------*/ if (strcmp(cb2mllrfn, ".1cls.") == 0) { n_mllr_class = 1; cb2mllr = (int32 *) ckd_calloc(n_mgau, sizeof(int32)); } else { if (s3cb2mllr_read(cb2mllrfn, &cb2mllr, &n_mgau_rd, &n_mllr_class) != S3_SUCCESS) { E_FATAL("Unable to read %s\n",cb2mllrfn); } if (n_mgau_rd != n_mgau) { E_FATAL("cb2mllr maps %u cb, but read %u cb from files\n", n_mgau_rd, n_mgau); } } E_INFO("n_mllr_class = %d\n", n_mllr_class); gau_begin = 0; if (cdonly) { if (! moddeffn) { E_FATAL("-moddeffn is not given.\n"); } else if (model_def_read(&mdef, moddeffn) != S3_SUCCESS) { E_FATAL("Can not read model definition file %s\n", moddeffn); } gau_begin = mdef->n_tied_ci_state; for (i=0; i<gau_begin; i++) { cb2mllr[i] = -1; /* skip CI senones */ } E_INFO("Use CD senones only. (index >= %d)\n",mdef->n_tied_ci_state); } /*--------------------------------------------------------------------*/ fprintf(stderr,"\n"); E_INFO("-- 3. Calculate mllr matrices\n"); /*--------------------------------------------------------------------*/ mllr_mat(&A, &B, var_fn, mean, wt_mean, wt_dcount, gau_begin, cb2mllr, mllr_mult, mllr_add, varfloor, n_mgau, n_stream, n_density, n_mllr_class, veclen); /*--------------------------------------------------------------------*/ fprintf(stderr,"\n"); E_INFO("-- 4. Store mllr matrices (A,B) to %s\n", out_mllr_fn); fflush(stderr); /*--------------------------------------------------------------------*/ if(store_reg_mat(out_mllr_fn, veclen, n_mllr_class, n_stream, A, B) != S3_SUCCESS) { E_FATAL("Unable to write %s\n", out_mllr_fn); } ckd_free((void *)veclen); free_mllr_A(A, n_mllr_class, n_stream); free_mllr_B(B, n_mllr_class, n_stream); return 0 ; } <file_sep>/tools/audiocollector/src/java/edu/cmu/sphinx/tools/datacollection/client/AudioCollectorPresentationApplet.java package edu.cmu.sphinx.tools.datacollection.client; import edu.cmu.sphinx.frontend.util.VUMeter; import edu.cmu.sphinx.tools.audio.Player; import edu.cmu.sphinx.util.props.ConfigurationManager; import edu.cmu.sphinx.util.props.PropertyException; import netscape.javascript.JSObject; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * Created by IntelliJ IDEA. * User: bertrand * Date: Apr 10, 2006 * Time: 11:56:53 PM * Copyright Apr 10, 2006, All rights reserved. * AudioControllerApplet is the desktop internet browser specific presentation logic for AudioController * It is responsible for directing and interacting with the subject through a successfull data collection * session. */ public class AudioCollectorPresentationApplet extends JApplet implements KeyListener, ActionListener { AudioCollector _audioCollector = null; ConfigurationManager _audioConfigManager = null; //Below are the applet's widgets JButton _previousButton = null; JButton _recordButton = null; JButton _playButton = null; JButton _stopButton = null; JButton _nextButton = null; JButton _submitButton = null; //Below are browser DOM Objects we will be manipulating JSObject _billboard = null; JSObject _eqAverageNormal = null; JSObject _eqAverageMid = null; JSObject _eqAverageHi = null; JSObject _eqMax = null; JSObject _eqPeak = null; JSObject _eqRMS = null; static final byte BAR_LENGTH = 25; static String BAR = ""; URL _submitURL; String[] BARS = new String[BAR_LENGTH]; JRootPane _content = null; Player _currentPlayer = null; JButton _defaultButton = _nextButton; /** * Convenience method sets the passed button as the default button * @param b */ private void setDefaultButton(JButton b) { _defaultButton = b; _defaultButton.grabFocus(); } public void keyPressed(KeyEvent e) { } /** * Implements the keyboard shortkey, if anybutton is pressed the current default button will be "clicked" * @param e */ public void keyTyped(KeyEvent e) { System.out.println("KeyPressed: action="+_defaultButton.getName()); _defaultButton.doClick(); } public void keyReleased(KeyEvent e) { } /** * upon any mouse clicks, translates the button that is currently being chosen by the user * into actions for the AudioController, keep in mind that buttons that should not be clicked * based on the current AudioController's state, are disabled so we assume here that only legal buttons * are clicked. (no checking for legality). * @param e */ public void actionPerformed(ActionEvent e) { if (e.getSource() == _previousButton) { setDefaultButton(_playButton); _audioCollector.previous(); } else if (e.getSource() == _recordButton) { setDefaultButton(_stopButton); _audioCollector.record(); } else if (e.getSource() == _playButton) { _currentPlayer = _audioCollector.play(); setDefaultButton(_stopButton); _currentPlayer.start(); //Starts a thread to Auto Stop at the end of the recording w/o user interacton new Thread() { public void run() { while (_currentPlayer.isPlaying()) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } if (_audioCollector.isStopActive()) _stopButton.doClick(); } }.start(); } else if (e.getSource() == _stopButton) { if (_currentPlayer != null && _currentPlayer.isPlaying()) _currentPlayer.stop(); setDefaultButton(_nextButton); _audioCollector.stop(); } else if (e.getSource() == _nextButton) { setDefaultButton(_recordButton); _audioCollector.next(); } else if (e.getSource() == _submitButton) { setDefaultButton(_submitButton); _billboard.setMember("value", "Sending data collected..."); _audioCollector.submit(_submitURL); _billboard.setMember("value", "All done! Thank YOU for participating in this data collection effort."); } refresh(); } /** * returns a progress bar based on the parameters passed * @param metric1 parameter to map * @param max maximum value that parameter may have * @return a progress bar in the format of a string */ String displayBar(final double metric1, final double max) { byte b = (byte) (BAR_LENGTH * (metric1 / max)); if (BARS[b] == null) { StringBuffer sbuf = new StringBuffer(BAR); for (byte i = 0; i < b; i++) { sbuf.setCharAt(i, '\u2588'); } BARS[b] = sbuf.toString(); } return BARS[b]; } /** * Marks the progress bar with local maximum for effect * @param mark * @param max * @return progress bar as a String */ private String maxBar(double mark, double max){ StringBuffer retBuf = new StringBuffer(BAR); byte b2 = (byte) (BAR_LENGTH * (mark / max)); retBuf.setCharAt(b2, '\u25BA'); return retBuf.toString(); } /** * starts a thread to constantly display the ambient volume (or playback) associate with the * AudioCollector */ void displayEQ() { Thread eq = new Thread() { public void run() { double maxNormal = 0.0; double maxHi = 0.0; double maxMid = 0.0; final double MID_CUTOFF = 26.0; String oldStatus = ""; System.out.println("Entering while loop..."); while (true) { final VUMeter vum = _audioCollector.getCurrentVUMeter(); final double average = vum.getAverageDB() ; final double peak = vum.getPeakDB(); final double hi = vum.getMaxDB(); final String bar = displayBar(average, hi); String status; //displays the red clipping bar if (vum.getIsClipping()) { if (maxHi < peak) maxHi = peak; _eqAverageHi.setMember("value", bar); _eqAverageMid.setMember("value", maxBar(maxMid, hi)); _eqAverageNormal.setMember("value", maxBar(maxNormal, hi)); status = "volume: Clipping"; } //displays the orange bar if close to clipping else if (vum.getMaxDB() - vum.getAverageDB() < MID_CUTOFF) { if (maxMid < peak) maxMid = peak; _eqAverageMid.setMember("value", bar); _eqAverageNormal.setMember("value", maxBar(maxNormal, hi)); _eqAverageHi.setMember("value", maxBar(maxHi, hi)); status = "volume: Warning"; } //Displays the green bar if audio levels are normal else { if (maxNormal < peak) maxNormal = peak; _eqAverageNormal.setMember("value", bar); _eqAverageMid.setMember("value", maxBar(maxMid, hi)); _eqAverageHi.setMember("value", maxBar(maxHi, hi)); status = "volume: Normal"; } if (!oldStatus.equals(status)) System.out.println(oldStatus=status); try { sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } } } }; eq.setDaemon(true); eq.start(); } /** * refreshes all the widgets on the JApplet based on the current state of the AudioCollector */ void refresh() { _previousButton.setEnabled(_audioCollector.isPreviousActive()); _recordButton.setEnabled(_audioCollector.isRecordActive()); _playButton.setEnabled(_audioCollector.isPlayActive()); _stopButton.setEnabled(_audioCollector.isStopActive()); _nextButton.setEnabled(_audioCollector.isNextActive()); _submitButton.setVisible(_audioCollector.isSubmitActive()); _nextButton.setVisible(!_audioCollector.isSubmitActive()); if (_audioCollector.getCurrentState() != AudioCollector.INVALID_STATE) _billboard.setMember("value", getTranscript()); } public String getTranscript() { return _audioCollector.getCurrentTranscript(); } private URL getResourceURL(String resource) { return AudioCollectorPresentationApplet.class.getResource(resource); } /** * Interacts with the JSP to get all the information necessary to create an AudioCollector for this session * and creates all the GUI Objects necessary (include the JSObjects so we can change the Browser's DOM on the * fly a la AJAX). parameter from JSP: "corpus" : serialized corpus (using CorpusTranscriptsOnlyWriter, "store" * the url to a jsp that will received the resulting zip stream, "config" a url to a config Manager file specifying * the specifics of the client native audio capabilities. */ public void init() { String corpusAsString = getParameter("corpus"); URL url; String submitURLString; try { url = new URL(getParameter("config")); submitURLString = getParameter("store"); _audioConfigManager = new ConfigurationManager(url); _audioCollector = new AudioCollector(corpusAsString, _audioConfigManager); _submitURL = new URL(submitURLString + "?ID=" + _audioCollector._corpus.getProperty("ID") + "&userID=" + _audioCollector._corpus.getProperty("userID")); } catch (MalformedURLException e) { e.printStackTrace(); } catch (PropertyException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } _previousButton = new JButton(new ImageIcon(getResourceURL("images/previous.gif"))); _recordButton = new JButton(new ImageIcon(getResourceURL("images/record.gif"))); _playButton = new JButton(new ImageIcon(getResourceURL("images/play.gif"))); _stopButton = new JButton(new ImageIcon(getResourceURL("images/stop.gif"))); _nextButton = new JButton(new ImageIcon(getResourceURL("images/next.gif"))); _submitButton = new JButton("submit"); _content = getRootPane(); _content.setLayout(new FlowLayout()); _content.setBackground(Color.gray); _content.add(_previousButton); _content.add(_recordButton); _content.add(_playButton); _content.add(_stopButton); _content.add(_nextButton); _content.add(_submitButton); _previousButton.setName("previous button"); _recordButton.setName("record button"); _playButton.setName("play button"); _stopButton.setName("stop button"); _nextButton.setName("next button"); _submitButton.setName("submit button"); _previousButton.addActionListener(this); _recordButton.addActionListener(this); _playButton.addActionListener(this); _stopButton.addActionListener(this); _nextButton.addActionListener(this); _submitButton.addActionListener(this); _previousButton.addKeyListener(this); _recordButton.addKeyListener(this); _playButton.addKeyListener(this); _stopButton.addKeyListener(this); _nextButton.addKeyListener(this); _submitButton.addKeyListener(this); _content.addKeyListener(this); setDefaultButton(_recordButton); JSObject MainWin = JSObject.getWindow(this); JSObject DocumentPage = (JSObject) MainWin.getMember("document"); JSObject billboardForm = (JSObject) DocumentPage.getMember("billboard"); JSObject eqForm = (JSObject) DocumentPage.getMember("eq"); _billboard = (JSObject) billboardForm.getMember("transcript"); _eqAverageNormal = (JSObject) eqForm.getMember("average-normal"); _eqAverageMid = (JSObject) eqForm.getMember("average-mid"); _eqAverageHi = (JSObject) eqForm.getMember("average-hi"); for (int i=0; i<BAR_LENGTH; i++) { BAR +='\u0020'; } displayEQ(); refresh(); } /** * calls AudioCollector's destroy for cleanup */ public void destroy() { super.destroy(); _audioCollector.destroy(); } public String toString() { return "record=" + _audioCollector.isRecordActive() + ",play=" + _audioCollector.isPlayActive() + ",stop=" + _audioCollector.isStopActive(); } } <file_sep>/SphinxTrain/src/libs/libcep_feat/v2_feat.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3_feat_0.c * * Description: * Compute a unified feature stream (Ver 0) * * f(t) = < s2_cep(t) s2_dcep(t, 2) s2_ddcep(t, 2) > * * Optionally does the following transformations on MFCC before computing the * derived features above: * * 1. Cepstral mean normalization (based on current utt or prior * utterances). * 2. Automatic gain control: * - subtract utter max c[0] from all c[0] * - subtract estimated utter max (based on prior utterances) * from all c[0] of current utterances. * 3. Silence deletion * - based on c[0] histogram of current utterance * - based on c[0] histogram of prior utterance * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$";*/ #include "v2_feat.h" #include <s3/feat.h> #include <s3/agc.h> #include <s3/cmn.h> #include <s3/silcomp.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <assert.h> #include <string.h> #include <stdio.h> #define N_FEAT 1 static uint32 n_feat = N_FEAT; static uint32 vecsize[1]; static uint32 mfcc_len; static uint32 delta_wsize = 2; uint32 doubledelta_wsize = 1; const char * v2_feat_doc() { return "1 stream :== < cep + dcep + ddcep >"; } uint32 v2_feat_id() { return FEAT_ID_V2; } uint32 v2_feat_n_stream() { return n_feat; } uint32 v2_feat_blksize() { return vecsize[0]; } const uint32 * v2_feat_vecsize() { return vecsize; } void v2_feat_set_in_veclen(uint32 veclen) { mfcc_len = veclen; vecsize[0] = 3 * veclen; cmn_set_veclen(veclen); agc_set_veclen(veclen); } vector_t ** v2_feat_alloc(uint32 n_frames) { vector_t **out; float *data; uint32 len; uint32 i, j, k; uint32 frame_size; out = (vector_t **)ckd_calloc_2d(n_frames, n_feat, sizeof(vector_t)); for (i = 0, frame_size = 0; i < n_feat; i++) frame_size += vecsize[i]; len = n_frames * frame_size; data = ckd_calloc(len, sizeof(float32)); for (i = 0, k = 0; i < n_frames; i++) { assert((k % frame_size) == 0); for (j = 0; j < n_feat; j++) { out[i][j] = &data[k]; k += vecsize[j]; } } assert(k == len); return out; } void v2_feat_free(vector_t **f) { ckd_free(f[0][0]); /* frees the data block */ ckd_free_2d((void **)f); /* frees the access overhead */ } void deltacep_frame(vector_t dcep, vector_t mfcc) { int32 s_w; int32 k; int32 mfcc_len; mfcc_len = feat_mfcc_len(); s_w = delta_wsize * mfcc_len; for (k = 0; k < mfcc_len; k++) { /* compute the short duration diff cep */ dcep[k] = mfcc[k + s_w] - mfcc[k - s_w]; } } void doubledelta_frame(vector_t ddcep, vector_t mfcc) { int32 d_w; int32 dd_w; int32 mfcc_frame_len; int32 k; float32 d1; float32 d2; mfcc_frame_len = feat_mfcc_len(); /* compute dcep window offset in terms of coefficients */ d_w = delta_wsize * mfcc_frame_len; /* compute ddcep window offset in terms of coefficients */ dd_w = doubledelta_wsize * mfcc_frame_len; for (k = 0; k < mfcc_frame_len; k++) { /* compute 2nd diff of mfcc[k] */ /* dcep[k] of doubledelta_wsize frames in future */ d1 = mfcc[k + d_w + dd_w] - mfcc[k - d_w + dd_w]; /* dcep[k] of doubledelta_wsize frames in past */ d2 = mfcc[k + d_w - dd_w] - mfcc[k - d_w - dd_w]; ddcep[k] = d1 - d2; } } vector_t ** v2_feat_compute(vector_t *mfcc, uint32 *inout_n_frame) { vector_t mfcc_frame; vector_t **out; vector_t out_frame; uint32 svd_n_frame; uint32 n_frame; const char *comp_type = cmd_ln_access("-silcomp"); uint32 i, j; uint32 mfcc_len; uint32 cep_off; uint32 dcep_off; uint32 ddcep_off; uint32 s_d_begin; uint32 s_d_end; uint32 dd_begin; uint32 dd_end; void v2_mfcc_print(vector_t *mfcc, uint32 n_frame); mfcc_len = feat_mfcc_len(); /* # of coefficients c[0..MFCC_LEN-1] per frame */ cep_off = 0; /* cep feature is first and includes c[0] */ dcep_off = mfcc_len; /* dcep feature includes long and short diff */ ddcep_off = 2 * mfcc_len; /* ddcep feature is mfcc_len long */ n_frame = svd_n_frame = *inout_n_frame; n_frame = sil_compression(comp_type, mfcc, n_frame); /* set the begin and end frames for the short dur diff cep */ s_d_begin = delta_wsize; s_d_end = n_frame - s_d_begin; /* set the begin and end frames for the 2nd diff cep */ dd_begin = doubledelta_wsize + delta_wsize; dd_end = n_frame - dd_begin; cmn(&mfcc[0][0], n_frame); agc(&mfcc[0][0], n_frame); out = feat_alloc(n_frame); for (i = 0, j = 0; i < n_frame; i++, j += mfcc_len) { out_frame = out[i][0]; mfcc_frame = mfcc[i]; memcpy(out_frame, mfcc_frame, mfcc_len * sizeof(float32)); if ((i >= s_d_begin) && (i < s_d_end)) { deltacep_frame(out_frame + dcep_off, mfcc_frame); } if ((i >= dd_begin) && (i < dd_end)) { doubledelta_frame(out_frame + ddcep_off, mfcc_frame); } } /* Deal w/ short diff boundaries */ for (i = 0; i < s_d_begin; i++) { memcpy(&out[i][0][dcep_off], &out[s_d_begin][0][dcep_off], (mfcc_len)*sizeof(float32)); } for (i = s_d_end; i < n_frame; i++) { memcpy(&out[i][0][dcep_off], &out[s_d_end-1][0][dcep_off], mfcc_len*sizeof(float32)); } /* Deal w/ 2nd diff boundaries */ for (i = 0; i < dd_begin; i++) { memcpy(&out[i][0][ddcep_off], &out[dd_begin][0][ddcep_off], mfcc_len*sizeof(float32)); } for (i = dd_end; i < n_frame; i++) { memcpy(&out[i][0][ddcep_off], &out[dd_end-1][0][ddcep_off], mfcc_len*sizeof(float32)); } *inout_n_frame = n_frame; return out; } void v2_mfcc_print(vector_t *mfcc, uint32 n_frame) { uint32 i, k; uint32 mfcc_len; mfcc_len = feat_mfcc_len(); for (i = 0; i < n_frame; i++) { printf("mfcc[%04u]: ", i); for (k = 0; k < mfcc_len; k++) { printf("%6.3f ", mfcc[i][k]); } printf("\n"); } } void v2_feat_print(const char *label, vector_t **f, uint32 n_frames) { uint32 i; int32 j; uint32 k; char *name[] = { "" }; vector_t *frame; vector_t stream; for (i = 0; i < n_frames; i++) { frame = f[i]; for (j = 0; j < n_feat; j++) { stream = frame[j]; printf("%s%s[%04u]: ", label, name[j], i); for (k = 0; k < vecsize[j]; k++) { printf("%6.3f ", stream[k]); } printf("\n"); } printf("\n"); } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1996/03/25 15:36:31 eht * Changes to allow for settable input feature length * * Revision 1.2 1996/01/26 18:04:51 eht * *** empty log message *** * * Revision 1.1 1995/12/14 20:12:58 eht * Initial revision * */ <file_sep>/archive_s3/s3.0/pgm/sensprd/sensprd.c /* * sensprd.c -- Spread of senone scores. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * $Log$ * Revision 1.1 2000/04/24 09:07:29 lenzo * Import s3.0. * * * 06-Oct-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <s3.h> #include <libmain/gauden.h> #include <libmain/senone.h> #include <libmain/tmat.h> #include <libmain/lm.h> #include <libmain/fillpen.h> #include <libmain/hmm.h> #include <libmain/misc.h> #include <libmain/cmn.h> #include <libmain/agc.h> #include <libmain/logs3.h> #include <libmain/am.h> static arg_t arglist[] = { { "-logbase", ARG_FLOAT32, "1.0001", "Base in which all log values calculated" }, { "-feat", ARG_STRING, "s3_1x39", "Feature vector type (s3_1x39 or s2_4x)" }, { "-mean", REQARG_STRING, NULL, "Mixture gaussian means input file" }, { "-var", REQARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to -var file)" }, { "-sen2mgaumap", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, { "-mixw", REQARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to -mixw file)" }, { "-ctl", REQARG_STRING, NULL, "Control file listing utterances to be processed" }, { "-cepdir", ARG_STRING, ".", "Directory of mfc files (for utterances in -ctl file)" }, { NULL, ARG_INT32, NULL, NULL } }; static void process_ctlfile (acoustic_t *am, char *ctl) { FILE *fp; char uttfile[4096]; char uttid[4096]; int32 sf, ef, nfr, featwin; char *cepdir; char cepfile[4096]; float32 **mfc; int32 i, f, sum; float64 logp, p, sump, ent; if ((fp = fopen(ctl, "r")) == NULL) E_FATAL_SYSTEM("fopen(%s,r) failed\n", ctl); cepdir = (char *) cmd_ln_access ("-cepdir"); featwin = feat_window_size (); while (_ctl_read (fp, uttfile, &sf, &ef, uttid) >= 0) { _ctl2cepfile (uttfile, cepdir, cepfile); /* nfr below includes the padding */ if ((nfr = s2mfc_read (cepfile, sf, ef, featwin, &mfc)) < 0) E_FATAL("MFC read (%s) failed\n", uttid); E_INFO("%s: %d frames\n", uttid, nfr - (featwin << 1)); cmn (mfc, nfr, feat_cepsize()); agc_max (mfc, nfr); for (f = featwin; f < nfr-featwin; f++) { for (i = 0; i < am->sen->n_sen; i++) bitvec_set (am->sen_active, i); acoustic_eval (am, mfc+f); /* Find log(sum(senone-scores)) */ sum = LOGPROB_ZERO; for (i = 0; i < am->sen->n_sen; i++) sum = logs3_add (sum, am->senscr[i]); sump = 0.0; ent = 0.0; for (i = 0; i < am->sen->n_sen; i++) { logp = logs3_to_log (am->senscr[i] - sum); p = exp(logp); sump += p; ent -= p * logp; } printf ("%5d %6.2f %7.2f\n", f-featwin, sump, ent); } } fclose (fp); } main (int32 argc, char *argv[]) { acoustic_t *am; gauden_t *g; senone_t *s; int32 cepsize; unlimit (); cmd_ln_parse (arglist, argc, argv); logs3_init ( *((float32 *) cmd_ln_access("-logbase")) ); feat_init ((char *) cmd_ln_access ("-feat")); cepsize = feat_cepsize (); g = gauden_init ((char *) cmd_ln_access ("-mean"), (char *) cmd_ln_access ("-var"), *((float32 *) cmd_ln_access ("-varfloor"))); s = senone_init ((char *) cmd_ln_access ("-mixw"), (char *) cmd_ln_access ("-sen2mgaumap"), *((float32 *) cmd_ln_access ("-mixwfloor"))); am = acoustic_init (g, s); process_ctlfile (am, (char *)(cmd_ln_access("-ctl"))); } <file_sep>/cmuclmtk/src/libs/ac_lmfunc_impl.c /* ==================================================================== * Copyright (c) 1999-2006 Car<NAME> University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include "ac_lmfunc_impl.h" #include "ac_hash.h" #include "ac_parsetext.h" #include "idngram2lm.h" // in liblmest/ /* Start Implementation of text2wfreq */ int text2wfreq_impl(FILE* infp, FILE* outfp, int init_nwords, int verbosity) { int hash_size, scanrc; struct hash_table vocab; char word[MAX_STRING_LENGTH]; hash_size = nearest_prime( init_nwords ); new_hashtable( &vocab, hash_size ); while( (scanrc = fscanf(infp, "%500s", word )) == 1 ) { if ( strlen( word ) >= MAX_STRING_LENGTH ) { pc_message(verbosity,1,"text2wfreq : WARNING: word too long, will be split: %s...\n",word); } if (strlen(word)) { update( &vocab, word ,verbosity); } } if ( scanrc != EOF ) { quit(-1,"Error reading input\n"); } print( outfp, &vocab ); return 0; } /* Start Implementation of wfreq2vocab */ typedef struct { char *word; int count; } word_rec; static int sort_by_count(const void *rec1,const void *rec2) { word_rec *r1; word_rec *r2; r1 = (word_rec *) rec1; r2 = (word_rec *) rec2; return(r2->count-r1->count); } static int sort_alpha(const void *rec1,const void *rec2) { word_rec *r1; word_rec *r2; char *s1; char *s2; r1 = (word_rec *) rec1; r2 = (word_rec *) rec2; s1 = r1->word; s2 = r2->word; return (strcmp(s1,s2)); } /* To make this function less dependent on input stream, just pull records out and create an interface for it */ int wfreq2vocab_impl(FILE* ifp, FILE* ofp, int cutoff, int vocab_size, int num_recs, int verbosity) { flag gt_set; flag top_set; int current_rec; int num_above_threshold; int num_to_output; int i; word_rec *records; char temp_word[750]; gt_set = (cutoff != -1); top_set = (vocab_size != -1); if(cutoff==-1) cutoff=0; if(vocab_size==-1) vocab_size=0; if (gt_set && top_set) quit(-1,"wfreq2vocab : Error : Can't use both the -top and the -gt options.\n"); if (!gt_set && !top_set) vocab_size = 20000; if (gt_set) pc_message(verbosity,2,"wfreq2vocab : Will generate a vocabulary containing all words which\n occurred more that %d times. Reading wfreq stream from stdin...\n",cutoff); else pc_message(verbosity,2,"wfreq2vocab : Will generate a vocabulary containing the most\n frequent %d words. Reading wfreq stream from stdin...\n",vocab_size); current_rec = 0; num_above_threshold = 0; records = (word_rec *) rr_malloc(sizeof(word_rec)*num_recs); while (!rr_feof(ifp)) { if (fscanf(ifp, "%s %d",temp_word,&(records[current_rec].count)) != 2) { if (!rr_feof(ifp)) quit(-1,"Error reading unigram counts from standard input.\n"); }else { records[current_rec].word = salloc(temp_word); if (gt_set && records[current_rec].count > cutoff) num_above_threshold++; current_rec++; } if(current_rec > num_recs ){ quit2(-1,"The number of records %d reach the user-defined limit %d, consider to increase the number of records by -records\n",current_rec,num_recs); } } /* Sort records in descending order of count */ qsort((void*) records,(size_t) current_rec, sizeof(word_rec),sort_by_count); if (gt_set) num_to_output = num_above_threshold; else num_to_output = vocab_size; if (current_rec<num_to_output) num_to_output = current_rec; /* Now sort the relevant records alphabetically */ qsort((void*) records,(size_t) num_to_output, sizeof(word_rec),sort_alpha); if (gt_set) pc_message(verbosity,2,"Size of vocabulary = %d\n",num_to_output); if (num_to_output>MAX_UNIGRAM) { pc_message(verbosity,1,"Warning : Vocab size exceeds %d. This might cause problems with \n",MAX_UNIGRAM); pc_message(verbosity,1,"other tools, since word id's are stored in 2 bytes.\n"); } if (num_to_output == 0) pc_message(verbosity,1,"Warning : Vocab size = 0.\n"); /* Print the vocab to stdout */ printf("## Vocab generated by v2 of the CMU-Cambridge Statistcal\n"); printf("## Language Modeling toolkit.\n"); printf("##\n"); printf("## Includes %d words ",num_to_output); printf("##\n"); for (i=0;i<=num_to_output-1;i++) fprintf(ofp,"%s\n",records[i].word); pc_message(verbosity,0,"wfreq2vocab : Done.\n"); return 0; } int read_vocab(char* vocab_filename, int verbosity, struct idngram_hash_table* vocabulary, int M ) { FILE *vocab_file; int vocab_size; char temp_word[MAX_WORD_LENGTH]; char temp_word2[MAX_WORD_LENGTH]; vocab_size = 0; vocab_file = rr_iopen(vocab_filename); pc_message(verbosity,2,"Reading vocabulary... \n"); while (fgets (temp_word, sizeof(temp_word),vocab_file)) { if (strncmp(temp_word,"##",2)==0) continue; sscanf (temp_word, "%s ",temp_word2); /* printf("hey hey %s %d\n ", temp_word2, idngram_hash(temp_word2,M));*/ /* Check for repeated words in the vocabulary */ if (index2(vocabulary,temp_word2) != 0) warn_on_repeated_words(temp_word2); warn_on_wrong_vocab_comments(temp_word); vocab_size++; /* printf("%s %d\n ", temp_word2, idngram_hash(temp_word2,M));*/ add_to_idngram_hashtable(vocabulary,idngram_hash(temp_word2,M),temp_word2,vocab_size); if(vocab_size == M){ quit(-1, "Number of entries reached the size of the hash. Run the program again with a larger has size -hash \n"); } } if (vocab_size > MAX_VOCAB_SIZE) fprintf(stderr,"text2idngram : vocab_size %d\n is larger than %d\n",vocab_size,MAX_VOCAB_SIZE); return 0; } static int ng; /* Static variable to be used in qsort */ int compare_ngrams(const void *ngram1, const void *ngram2 ) { int i; wordid_t *ngram_pointer1; wordid_t *ngram_pointer2; ngram_pointer1 = (wordid_t *) ngram1; ngram_pointer2 = (wordid_t *) ngram2; for (i=0;i<=ng-1;i++) { if (ngram_pointer1[i]<ngram_pointer2[i]) return(-1); else { if (ngram_pointer1[i]>ngram_pointer2[i]) return(1); } } return(0); } void add_to_buffer(wordid_t word_index, int ypos, int xpos, wordid_t *buffer) { buffer[(ng*ypos)+xpos] = word_index; } wordid_t buffer_contents(int ypos, int xpos, wordid_t *buffer) { return (buffer[(ng*ypos)+xpos]); } int get_word( FILE *fp , char *word ) { /* read word from stream, checking for read errors and EOF */ int nread; int rt_val; rt_val = 0; nread = fscanf( fp,MAX_WORD_LENGTH_FORMAT, word ); if ( nread == 1 ) rt_val = 1; else { if ( nread != EOF ) quit(-1, "Error reading file" ); } return(rt_val); } /* @return number_of_tempfiles */ int read_txt2ngram_buffer(FILE* infp, struct idngram_hash_table *vocabulary, int32 verbosity, wordid_t *buffer, int buffer_size, unsigned int n, char* temp_file_root, char* temp_file_ext, FILE* temp_file ) { /* Read text into buffer */ char temp_word[MAX_WORD_LENGTH]; int position_in_buffer; int number_of_tempfiles; unsigned int i,j; wordid_t *placeholder; wordid_t *temp_ngram; int temp_count; #if 1 int tmpval; #endif temp_ngram = (wordid_t *) rr_malloc(sizeof(wordid_t)*n); placeholder = (wordid_t *) rr_malloc(sizeof(wordid_t)*n); ng=n; position_in_buffer = 0; number_of_tempfiles = 0; //tk: looks like things may croak if the corpus has less than n words //not that such a corpus would be useful anyway for (i=0;i<=n-1;i++) { get_word(infp,temp_word); /* fprintf(stderr,"%s \n",temp_word); fprintf(stderr,"%d \n",index2(vocabulary,temp_word)); fflush(stderr); */ add_to_buffer(index2(vocabulary,temp_word),0,i,buffer); } while (!rr_feof(infp)) { /* Fill up the buffer */ pc_message(verbosity,2,"Reading text into the n-gram buffer...\n"); pc_message(verbosity,2,"20,000 n-grams processed for each \".\", 1,000,000 for each line.\n"); while ((position_in_buffer<buffer_size) && (!rr_feof(infp))) { position_in_buffer++; show_idngram_nlines(position_in_buffer,verbosity); for (i=1;i<=n-1;i++) add_to_buffer(buffer_contents(position_in_buffer-1,i,buffer), position_in_buffer,i-1,buffer); if (get_word(infp,temp_word) == 1) { /* fprintf(stderr,"%s \n",temp_word); fprintf(stderr,"%d \n",index2(vocabulary,temp_word)); fflush(stderr); */ add_to_buffer(index2(vocabulary,temp_word),position_in_buffer, n-1,buffer); } } for (i=0;i<=n-1;i++) placeholder[i] = buffer_contents(position_in_buffer,i,buffer); /* Sort buffer */ pc_message(verbosity,2,"\nSorting n-grams...\n"); qsort((void*) buffer,(size_t) position_in_buffer,n*sizeof(wordid_t),compare_ngrams); /* Output the buffer to temporary BINARY file */ number_of_tempfiles++; sprintf(temp_word,"%s%hu%s",temp_file_root, number_of_tempfiles,temp_file_ext); pc_message(verbosity,2,"Writing sorted n-grams to temporary file %s\n", temp_word); temp_file = rr_oopen(temp_word); for (i=0;i<=n-1;i++) { temp_ngram[i] = buffer_contents(0,i,buffer); #if MAX_VOCAB_SIZE < 65535 /* This check is well-meaning but completely useless since buffer_contents() can never return something greater than MAX_VOCAB_SIZE (dhuggins@cs, 2006-03) */ if (temp_ngram[i] > MAX_VOCAB_SIZE) quit(-1,"Invalid trigram in buffer.\nAborting"); #endif } temp_count = 1; for (i=1;i<=position_in_buffer;i++) { tmpval=compare_ngrams(temp_ngram,&buffer[i*n]); /* for(k=0;k<=n-1;k++){ fprintf(stderr, "tmpval: %d k %d, temp_ngram %d, &buffer[i*n] %d\n",tmpval, k, temp_ngram[k], (&buffer[i*n])[k]); }*/ if (!compare_ngrams(temp_ngram,&buffer[i*n])) temp_count++; else { /* printf("Have been here?\n");*/ for (j=0;j<=n-1;j++) { rr_fwrite((char*) &temp_ngram[j],sizeof(wordid_t),1, temp_file,"temporary n-gram ids"); temp_ngram[j] = buffer_contents(i,j,buffer); } rr_fwrite((char*)&temp_count,sizeof(int),1,temp_file, "temporary n-gram counts"); /* for(j=0 ; j<=n-1;j++) fprintf(stderr,"%d ",temp_ngram[j]); fprintf(stderr,"%d\n",temp_count);*/ temp_count = 1; } } rr_oclose(temp_file); for (i=0;i<=n-1;i++) add_to_buffer(placeholder[i],0,i,buffer); position_in_buffer = 0; } return number_of_tempfiles; } <file_sep>/cmuclmtk/src/win32/compat.h #ifndef COMPAT_H #define COMPAT_H #ifdef _WIN32 #define popen(x, y) _popen((x), (y)) #define pclose(x) _pclose((x)) #define srandom(x) srand((x)) #define random() rand() #endif #endif <file_sep>/SphinxTrain/src/programs/mllr_solve/cmd_ln_defn.h /********************************************************************* * * $Header$ * * CMU ARPA Speech Project * * Copyright (c) 1998 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: cmd_ln_defn.h * * Description: * Command line argument definition * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef CMD_LN_DEFN_H const char helpstr[] = "Description: \n\ \n\ Given a set of mean accumulator, mllr_solve can compute the transform \n\ matrix based on the maximum likelihood criteria. \n\ \n\ The mean and variance are required to be input in arguments -meanfn and -varfn \n\ For linear regression equation y=Ax+b, \n\ If you specific only -mllrmult, then only A will be estimated. \n\ If you specific only -mllradd, then only b will be estimated. "; const char examplestr[] = "Example: \n\ The simplest case: \n\ mllr_solve -outmllrfn output.matrix -accumdir accumdir -meanfn mean -varfn var \n\ \n\ Adapt based on only CD-senones \n\ mllr_solve -outmllrfn output.matrix -accumdir accumdir -meanfn mean -varfn var -cdonly yes -moddeffn mdef. \n\ \n\ Only adapt on A :\n\ mllr_solve -outmllrfn output.matrix -accumdir accumdir -meanfn mean -varfn var -mllrmult yes -mllradd no \n\ \n\ help and example:\n\ mllr_solve -help yes -example yes "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-outmllrfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Output MLLR regression matrices file"}, { "-accumdir", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "One or more paths containing reestimation sums from bw" }, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Baseline Gaussian density mean file"}, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "variance (baseline-var, or error-var) file"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Variances are full covariance matrices"}, { "-cb2mllrfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".1cls.", "Codebook to mllr class mapping index file (If it is given, ignore -cdonly)"}, { "-cdonly", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Use only CD senones for MLLR (If yes, -moddeffn should be given.)"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model Definition file (to get CD starting point for MLLR)"}, { "-mllrmult", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate full multiplicative term of MLLR adatpation of means (yes/no)"}, { "-mllradd", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate shift term of MLLR adaptation of means (yes/no)"}, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1e-3", "var floor value"}, { NULL, CMD_LN_UNDEF,CMD_LN_NO_VALIDATION,CMD_LN_NO_DEFAULT, NULL } }; #define CMD_LN_DEFN_H #endif /* CMD_LN_DEFN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2005/06/14 00:28:58 arthchan2003 * Another typo * * Revision 1.4 2005/06/13 20:05:39 arthchan2003 * spelling mistakes: arguements to arguments * * Revision 1.3 2004/08/07 20:31:49 arthchan2003 * fix small problem in command line info mllr_mult -> mllrmult * * Revision 1.1 2004/07/27 12:09:26 arthchan2003 * Missing the whole directory of mllr_solve * * */ <file_sep>/SphinxTrain/src/libs/libcommon/profile.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * profile.c -- For timing and event counting. * * HISTORY * * 01-Aug-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed timer_ names to cyctimer_ (for cycle counter). * Added timing_ structures and functions using system calls for timing. * * 13-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Added ifdefs around cyctimer_print_all and cyctimer_print_all_norm. * * 27-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created from Sphinx-II version. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #if (! WIN32) #include <sys/time.h> #include <sys/resource.h> #else #include <windows.h> #include <time.h> #endif #include <s3/profile.h> #include <s3/err.h> #include <s3/ckd_alloc.h> typedef struct { char *name; uint32 count; } ctr_t; static ctr_t *ctr = NULL; static int32 n_ctr = 0; #define MAX_CTR 30 int32 counter_new (char *name) { if (! ctr) ctr = (ctr_t *) ckd_calloc (MAX_CTR, sizeof(ctr_t)); if (n_ctr >= MAX_CTR) { E_WARN("#counters (%d) exceeded\n", MAX_CTR); return -1; } ctr[n_ctr].name = (char *) ckd_salloc (name); ctr[n_ctr].count = 0; return (n_ctr++); } void counter_increment (int32 id, int32 inc) { if ((id < 0) || (id >= MAX_CTR)) return; ctr[id].count += inc; } void counter_reset (int32 id) { if ((id < 0) || (id >= MAX_CTR)) return; ctr[id].count = 0; } void counter_reset_all ( void ) { int32 i; for (i = 0; i < n_ctr; i++) counter_reset (i); } void counter_print_all (FILE *fp) { int32 i; if (n_ctr > 0) { fprintf (fp, "CTR:"); for (i = 0; i < n_ctr; i++) fprintf (fp, "[%s %10d]", ctr[i].name, ctr[i].count); fprintf (fp, "\n"); } } #if (WIN32) #define TM_LOWSCALE 1e-7 #define TM_HIGHSCALE (4294967296.0 * TM_LOWSCALE); static float64 make_sec (FILETIME *tm) { float64 dt; dt = tm->dwLowDateTime * TM_LOWSCALE; dt += tm->dwHighDateTime * TM_HIGHSCALE; return (dt); } #else /* !WIN32 */ static float64 make_sec (struct timeval *s) { return (s->tv_sec + s->tv_usec * 0.000001); } #endif #define MAX_NAMED_TMR 10 static timing_t *tmr_list[MAX_NAMED_TMR]; static char *tmr_name[MAX_NAMED_TMR]; static int n_tmr = 0; void timing_bind_name(const char *name, timing_t *tmr) { int i; if (n_tmr == MAX_NAMED_TMR) { E_ERROR("No more named timers; increase MAX_NAMED_TMR\n"); return; } if (n_tmr > 0) { for (i = 0; i < n_tmr; i++) { if (strcmp(name, tmr_name[i]) == 0) { E_ERROR("Timer %s already defined\n", name); return; } } } tmr_list[n_tmr] = tmr; tmr_name[n_tmr] = strdup(name); ++n_tmr; } timing_t * timing_get(const char *name) { int i; timing_t *ret = NULL; if (n_tmr > 0) { for (i = 0; i < n_tmr; i++) { if (strcmp(name, tmr_name[i]) == 0) { ret = tmr_list[i]; break; } } } return ret; } /* * Obtain and initialize a timing module */ timing_t *timing_new ( void ) { timing_t *tm; tm = (timing_t *) ckd_calloc (1, sizeof(timing_t)); tm->t_elapsed = 0.0; tm->t_cpu = 0.0; return tm; } void timing_start (timing_t *tm) { #if (! WIN32) struct timeval e_start; /* Elapsed time */ #if (! _HPUX_SOURCE) struct rusage start; /* CPU time */ /* Unix but not HPUX */ getrusage (RUSAGE_SELF, &start); tm->start_cpu = make_sec (&start.ru_utime) + make_sec (&start.ru_stime); #endif /* Unix + HP */ gettimeofday (&e_start, 0); tm->start_elapsed = make_sec (&e_start); #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes (pid, &t_create, &t_exit, &kst, &ust); tm->start_cpu = make_sec (&ust) + make_sec (&kst); tm->start_elapsed = (float64)clock() / CLOCKS_PER_SEC; #endif } void timing_stop (timing_t *tm) { float64 dt_cpu, dt_elapsed; #if (! WIN32) struct timeval e_stop; /* Elapsed time */ #if (! _HPUX_SOURCE) struct rusage stop; /* CPU time */ /* Unix but not HPUX */ getrusage (RUSAGE_SELF, &stop); dt_cpu = make_sec (&stop.ru_utime) + make_sec (&stop.ru_stime) - tm->start_cpu; #else dt_cpu = 0.0; #endif /* Unix + HP */ gettimeofday (&e_stop, 0); dt_elapsed = (make_sec (&e_stop) - tm->start_elapsed); #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes (pid, &t_create, &t_exit, &kst, &ust); dt_cpu = make_sec (&ust) + make_sec (&kst) - tm->start_cpu; dt_elapsed = ((float64)clock() / CLOCKS_PER_SEC) - tm->start_elapsed; #endif tm->t_cpu += dt_cpu; tm->t_elapsed += dt_elapsed; tm->t_tot_cpu += dt_cpu; tm->t_tot_elapsed += dt_elapsed; } void timing_reset (timing_t *tm) { tm->t_cpu = 0.0; tm->t_elapsed = 0.0; } <file_sep>/SphinxTrain/src/libs/libmodinv/mod_inv.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: mod_inv.c * * Description: * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include <s3/model_inventory.h> #include <s3/ckd_alloc.h> #include <s3/s2_param.h> #include <s3/common.h> #include <s3/s3mixw_io.h> #include <s3/s3tmat_io.h> #include <s3/s3gau_io.h> #include <s3/s3regmat_io.h> #include <s3/model_def.h> #include <sys_compat/file.h> #include <stdio.h> model_inventory_t * mod_inv_new() { model_inventory_t *new_mi = ckd_calloc(1, sizeof(model_inventory_t)); new_mi->gauden = gauden_alloc(); return new_mi; } void mod_inv_free(model_inventory_t *minv) { /* Free mixing weight related stuff */ if (minv->mixw) { ckd_free_3d((void ***)minv->mixw); } minv->mixw = NULL; if (minv->mixw_acc) { ckd_free_3d((void ***)minv->mixw_acc); } minv->mixw_acc = NULL; if (minv->l_mixw_acc) { ckd_free_3d((void ***)minv->l_mixw_acc); } minv->l_mixw_acc = NULL; if (minv->mixw_inverse) ckd_free((void *)minv->mixw_inverse); minv->mixw_inverse = NULL; /* Free density related stuff */ gauden_free(minv->gauden); minv->gauden = NULL; if (minv->cb_inverse) ckd_free((void *)minv->cb_inverse); minv->cb_inverse = NULL; /* Free transition matrix related stuff */ if (minv->tmat) { ckd_free_3d((void ***)minv->tmat); } minv->tmat = NULL; if (minv->tmat_acc) { ckd_free_3d((void ***)minv->tmat_acc); } minv->tmat_acc = NULL; if (minv->l_tmat_acc) { ckd_free_2d((void **)minv->l_tmat_acc); } minv->l_tmat_acc = NULL; /* Free the top-level inventory structure */ ckd_free(minv); } void mod_inv_set_n_feat(model_inventory_t *minv, uint32 n_feat) { minv->n_feat = n_feat; } void mod_inv_set_n_density(model_inventory_t *minv, uint32 n_density) { minv->n_density = n_density; } int32 mod_inv_alloc_gauden_acc(model_inventory_t *minv) { /* allocate accumulators for mean/variance reestimation sums */ if (gauden_alloc_acc(minv->gauden) != S3_SUCCESS) return S3_ERROR; return S3_SUCCESS; } int32 mod_inv_read_gauden(model_inventory_t *minv, const char *meanfn, const char *varfn, float32 varfloor, uint32 n_top, int32 var_is_full) { vector_t ***mean; vector_t ***var = NULL, ****fullvar = NULL; uint32 n_mgau, i; uint32 n_feat, j; uint32 n_density, k; const uint32 *veclen, *vl; gauden_t *g; if (s3gau_read(meanfn, &mean, &n_mgau, &n_feat, &n_density, &veclen) != S3_SUCCESS) { return S3_ERROR; } if ((minv->n_feat > 0) && (n_feat != minv->n_feat)) { E_FATAL("# of features in mean file %u is inconsistent w/ inventory, %u\n", n_feat, minv->n_feat); } else if (minv->n_feat == 0) { E_WARN("Model inventory n_feat not set; setting to mean file value, %u.\n", n_feat); minv->n_feat = n_feat; } if ((minv->n_density > 0) && (n_density != minv->n_density)) { E_FATAL("mean file contains a different # of Gaussian densities, %u, per mixture than previously defined, %u\n", n_density, minv->n_density); } else if (minv->n_density == 0) { /* This warning is bogus. */ /* E_WARN("Model inventory n_density not set; setting to mean file value, %u.\n", n_density); */ minv->n_density = n_density; } if (var_is_full) { if (s3gau_read_full(varfn, &fullvar, &i, &j, &k, &vl) != S3_SUCCESS) { return S3_ERROR; } } else { if (s3gau_read(varfn, &var, &i, &j, &k, &vl) != S3_SUCCESS) { return S3_ERROR; } } if (j != minv->n_feat) { E_FATAL("# of features in mean file %u is incompatible w/ prior setting, %u\n", j, minv->n_feat); } if (k != minv->n_density) { E_FATAL("variance file contains a different # of Gaussian densities, %u, per mixture than prior setting, %u\n", minv->n_density); } if (i != n_mgau) { E_FATAL("mean and variance file have an inconsistent # mgau, %u and %u resp.\n", n_mgau, i); } for (i = 0; i < n_feat; i++) { if (vl[i] != veclen[i]) { E_FATAL("Vector length of feature %u is %u in mean file but %u in variance file\n", i, veclen[i], vl[i]); } } ckd_free((void *)vl); g = minv->gauden; /* configure the gauden structure */ gauden_set_n_mgau(g, n_mgau); gauden_set_feat(g, n_feat, veclen); gauden_set_n_density(g, n_density); gauden_set_mean(g, mean); if (var_is_full) gauden_set_fullvar(g, fullvar); else gauden_set_var(g, var); gauden_set_min_var(varfloor); gauden_floor_variance(g); if (n_top > n_density) { E_WARN("n_top %u > n_density %u. n_top <- %u\n", n_top, n_density, n_density); gauden_set_n_top(g, n_density); } else { gauden_set_n_top(g, n_top); } return S3_SUCCESS; } int32 mod_inv_alloc_tmat_acc(model_inventory_t *minv) { minv->tmat_acc = (float32 ***)ckd_calloc_3d(minv->n_tmat, minv->n_state_pm-1, minv->n_state_pm, sizeof(float32)); return S3_SUCCESS; } int32 mod_inv_read_tmat(model_inventory_t *minv, const char *fn, float32 floor) { float32 ***tmat; uint32 n_tmat; uint32 n_state_pm; uint32 i, j; if (s3tmat_read(fn, &tmat, &n_tmat, &n_state_pm) != S3_SUCCESS) { return S3_ERROR; } if (floor != 0) { E_INFO("inserting tprob floor %e and renormalizing\n", floor); for (i = 0; i < n_tmat; i++) { for (j = 0; j < n_state_pm-1; j++) { vector_normalize(tmat[i][j], n_state_pm); vector_nz_floor(tmat[i][j], n_state_pm, floor); vector_normalize(tmat[i][j], n_state_pm); } } } minv->tmat = tmat; minv->n_tmat = n_tmat; minv->n_state_pm = n_state_pm; return S3_SUCCESS; } int32 mod_inv_alloc_mixw_acc(model_inventory_t *minv) { minv->mixw_acc = (float32 ***)ckd_calloc_3d(minv->n_mixw, minv->n_feat, minv->n_density, sizeof(float32)); return S3_SUCCESS; } int32 mod_inv_read_mixw(model_inventory_t *minv, const model_def_t *mdef, const char *fn, float32 floor) { float32 ***mixw; uint32 n_mixw, i; uint32 n_feat, j; uint32 n_density; if (s3mixw_read(fn, &mixw, &n_mixw, &n_feat, &n_density) != S3_SUCCESS) { return S3_ERROR; } minv->mixw = mixw; minv->n_mixw = n_mixw; if (n_mixw != mdef->n_tied_state) { E_WARN("# of tied states in mdef file, %u != # of mixing weight sets, %u, in %s\n", mdef->n_tied_state, n_mixw, fn); } if ((minv->n_feat > 0) && (n_feat != minv->n_feat)) { E_FATAL("# of features in mixw file, %u, is inconsistent w/ prior setting, %u\n", n_feat, minv->n_feat); } else if (minv->n_feat == 0) { E_WARN("Model inventory n_feat not set; setting to value in mixw file, %u.\n", n_feat); minv->n_feat = n_feat; } if ((minv->n_density > 0) && (n_density != minv->n_density)) { E_WARN("# of densities/mixture, %u in %s != prior settting, %u\n", n_density, fn, minv->n_density); } else if (minv->n_density == 0) { /* This warning is bogus. */ /* E_WARN("Model inventory n_density not set; setting to value in mixw file, %u.\n", n_density); */ minv->n_density = n_density; } if (floor != 0) { uint32 *err_norm = NULL; uint32 n_err_norm = 0; uint32 err = FALSE; for (i = 0; i < n_mixw; i++) { for (j = 0; j < n_feat; j++) { if (vector_normalize(mixw[i][j], n_density) != S3_SUCCESS) { err = TRUE; } vector_floor(mixw[i][j], n_density, floor); vector_normalize(mixw[i][j], n_density); } if (err) { if (err_norm) { err_norm[n_err_norm++] = i; } else { /* first use; allocate it */ err_norm = ckd_calloc(n_mixw, sizeof(uint32)); err_norm[n_err_norm++] = i; } err = FALSE; } } if (n_err_norm > 0) { E_INFO("Norm failed for %d mixw:", n_err_norm); for (i = 0; i < n_err_norm; i++) { E_INFOCONT(" %u", err_norm[i]); } E_INFOCONT("\n"); ckd_free(err_norm); } } return S3_SUCCESS; } int mod_inv_restore_acc(model_inventory_t *minv, const char *accumdir, int mixw_reest, int mean_reest, int var_reest, int tmat_reest) { char fn[MAXPATHLEN+1]; uint32 n_mixw; uint32 n_feat; uint32 n_density; uint32 n_tmat; uint32 n_state_pm; uint32 n_cb; const uint32 *veclen, *rd_veclen; int ret = S3_SUCCESS; uint32 i; int32 pass2var; veclen = feat_vecsize(); if (mixw_reest) { ckd_free_3d((void ***)minv->mixw_acc); minv->mixw_acc = NULL; sprintf(fn, "%s/mixw_counts", accumdir); if (s3mixw_read(fn, &minv->mixw_acc, &n_mixw, &n_feat, &n_density) != S3_SUCCESS) { return S3_ERROR; } if (n_mixw != minv->n_mixw) { E_ERROR("Checkpointed n_mixw=%u inconsistent w/ trainer config=%u\n", n_mixw, minv->n_mixw); ret = S3_ERROR; } if (n_feat != minv->n_feat) { E_ERROR("Checkpointed n_feat=%u inconsistent w/ trainer config=%u\n", n_feat, minv->n_feat); ret = S3_ERROR; } if (n_density != minv->n_density) { E_ERROR("Checkpointed n_density=%u inconsistent w/ trainer config=%u\n", n_density, minv->n_density); ret = S3_ERROR; } } if (tmat_reest) { ckd_free_3d((void ***)minv->tmat_acc); minv->tmat_acc = NULL; sprintf(fn, "%s/tmat_counts", accumdir); if (s3tmat_read(fn, &minv->tmat_acc, &n_tmat, &n_state_pm) != S3_SUCCESS) { return S3_ERROR; } if (n_tmat != minv->n_tmat) { E_ERROR("Checkpointed n_tmat=%u inconsistent w/ trainer config=%u\n", n_tmat, minv->n_tmat); } if (n_state_pm != minv->n_state_pm) { E_ERROR("Checkpointed n_state_pm=%u inconsistent w/ trainer config=%u\n", n_state_pm, minv->n_state_pm); ret = S3_ERROR; } } if (mean_reest || var_reest) { gauden_free_acc(minv->gauden); sprintf(fn, "%s/gauden_counts", accumdir); if (s3gaucnt_read(fn, &(minv->gauden->macc), &(minv->gauden->vacc), &pass2var, &(minv->gauden->dnom), &n_cb, &n_feat, &n_density, &rd_veclen) != S3_SUCCESS) { return S3_ERROR; } if (n_cb != minv->gauden->n_mgau) { E_ERROR("Checkpointed n_cb=%u inconsistent w/ trainer config=%u\n", n_cb, minv->gauden->n_mgau); ret = S3_ERROR; } if (n_feat != minv->n_feat) { E_ERROR("Checkpointed n_feat=%u inconsistent w/ trainer config=%u\n", n_feat, minv->n_feat); ret = S3_ERROR; } if (n_density != minv->n_density) { E_ERROR("Checkpointed n_density=%u inconsistent w/ trainer config=%u\n", n_density, minv->n_density); ret = S3_ERROR; } for (i = 0; i < n_feat; i++) { if (veclen[i] != rd_veclen[i]) { E_ERROR("Checkpointed veclen[%u]=%u inconsistent w/ trainer config veclen[%u]=%u\n", i, rd_veclen[i], i, veclen[i]); ret = S3_ERROR; } } ckd_free((void *)rd_veclen); } return ret; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:41 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.7 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.6 1996/07/29 16:46:51 eht * Put reading and initialization of model parameter code here * * Revision 1.5 1995/10/18 11:23:10 eht * Changed the commenting conventions * * Revision 1.4 1995/10/09 15:11:53 eht * Changed interface to ckd_alloc to remove need for __FILE__, __LINE__ arguments * * Revision 1.3 1995/07/07 17:58:47 eht * Get rid of tying_init() since DAG is no longer used * * Revision 1.2 1995/06/02 16:48:06 eht * model inventory functions * * Revision 1.1 1995/02/06 14:26:45 eht * Initial revision * * */ <file_sep>/tools/corpusBrowser/src/java/edu/cmu/sphinx/tools/corpusBrowser/CorpusBuilder.java package edu.cmu.sphinx.tools.corpusBrowser; import edu.cmu.sphinx.decoder.search.Token; import edu.cmu.sphinx.linguist.dictionary.FastDictionary; import edu.cmu.sphinx.linguist.dictionary.FullDictionary; import edu.cmu.sphinx.linguist.flat.FlatLinguist; import edu.cmu.sphinx.result.Result; import edu.cmu.sphinx.tools.batch.BatchForcedAlignerRecognizer; import edu.cmu.sphinx.tools.corpus.*; import edu.cmu.sphinx.tools.corpus.xml.CorpusXMLReader; import edu.cmu.sphinx.tools.corpus.xml.CorpusXMLWriter; import edu.cmu.sphinx.util.props.*; import javolution.util.FastSet; import java.io.*; import java.net.URL; import java.util.Iterator; import java.util.Set; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Jan 18, 2006 * Time: 12:44:53 PM */ public class CorpusBuilder extends BatchForcedAlignerRecognizer { private static final String PROP_EXCLUDE_UTTERANCES = "excludeUtterances"; protected Set<Integer> excludedUtterances; /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#register(java.lang.String, * edu.cmu.sphinx.util.props.Registry) */ public void register(String name, Registry registry) throws PropertyException { super.register(name, registry); registry.register(PROP_EXCLUDE_UTTERANCES, PropertyType.STRING); } /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet) */ public void newProperties(PropertySheet ps) throws PropertyException { super.newProperties(ps); String eu = ps.getString(PROP_EXCLUDE_UTTERANCES, ""); excludedUtterances = new FastSet<Integer>(); for (String uid : eu.split(",")) { excludedUtterances.add(new Integer(uid)); } FlatLinguist fl = (FlatLinguist) (recognizer.getDecoder().getSearchManager().getLinguist()); String dictionaryFile; if( fl.getGrammar().getDictionary() instanceof FullDictionary ) { dictionaryFile = ((FullDictionary)(fl.getGrammar().getDictionary())).getWordDictionaryFile().getPath(); } else { dictionaryFile = ((FastDictionary)(fl.getGrammar().getDictionary())).getWordDictionaryFile().getPath(); } Dictionary dictionary = new Dictionary(); dictionary.setDictionaryFile(dictionaryFile); corpus = new Corpus(); corpus.setDictionary(dictionary); } public void decode() { try { utteranceId = 0; DataOutputStream ctm = new DataOutputStream(new FileOutputStream(ctmFile)); recognizer.allocate(); for (Iterator i = new CTLIterator(); i.hasNext();) { CTLUtterance utt = (CTLUtterance) i.next(); if (excludedUtterances.contains(utteranceId)) { System.out.println("Excluding utterance " + utteranceId); } else { setInputStream(utt); Result result = recognizer.recognize(); System.out.println("Utterance " + utteranceId + ": " + utt.getName()); System.out.println("Reference: " + utt.getRef()); System.out.println("Result : " + result); logger.info("Utterance " + utteranceId + ": " + utt.getName()); logger.info("Result : " + result); handleResult(ctm, utt, result); } utteranceId++; } recognizer.deallocate(); } catch (IOException io) { logger.severe("I/O error during decoding: " + io.getMessage()); } logger.info("BatchCTLDecoder: " + utteranceId + " utterances decoded"); } private String stripExtension( String fileName ) { return fileName.substring(0,fileName.lastIndexOf('.')); } protected void handleResult(DataOutputStream out, CTLUtterance utt, Result result) throws IOException { Utterance utterance = new Utterance(); //AudioDatabase adb = new AudioDatabase( stripExtension(utt.getFile()), 16,1,16000,100 ); RegionOfAudioData rad = new RegionOfAudioData(); rad.setBeginTime(utt.getStartOffset()); rad.setEndTime(utt.getEndOffset()); //addWords(utterance, result.getBestToken(), utterance.getEndTime(), adb); corpus.addUtterance(utterance); System.out.println(utt + " --> " + result); } // add all the lastWord and all the words from this token and before private void addWords(Utterance utterance, Token token, int nextBegin, AudioDatabase adb) { if (token != null) { edu.cmu.sphinx.linguist.dictionary.Word word = token.getWord(); int begin = token.getFrameNumber() + utterance.getBeginTime(); addWords(utterance, token.getPredecessor(), begin, adb); if (word != null) { String spelling = word.getSpelling(); Word w = new Word(); w.setSpelling(spelling); RegionOfAudioData rad = new RegionOfAudioData(); rad.setAudioDatabase(adb); rad.setBeginTime( begin ); rad.setEndTime( nextBegin ); rad.setExcluded( false); w.setRegionOfAudioData(rad); utterance.addWord(w); System.out.println(token.getWord() + " " + begin); } } } protected Corpus corpus = null; public static void main(String[] args) { if (args.length != 1) { System.out.println( "Usage: CorpusBuilder propertiesFile"); System.exit(1); } String propertiesFile = args[0]; try { URL url = new File(propertiesFile).toURI().toURL(); ConfigurationManager cm = new ConfigurationManager(url); CorpusBuilder me = (CorpusBuilder) cm.lookup("batchNIST"); if (me == null) { System.err.println("Can't find batchCTL in " + propertiesFile); return; } me.decode(); CorpusWriter cw = new CorpusXMLWriter( new FileOutputStream("dump.xml") ); cw.write(me.corpus); CorpusReader cr = new CorpusXMLReader( new FileInputStream("dump.xml") ); Corpus c2 = cr.read(); } catch (IOException ioe) { System.err.println("I/O error during initialization: \n " + ioe); return; } catch (InstantiationException e) { System.err.println("Error during initialization: \n " + e); return; } catch (PropertyException e) { System.err.println("Error during initialization: \n " + e); return; } } /* static void test1() { Corpus.Word dog = new Corpus.Word("Dog", 123, 256, false); Corpus.Word cat = new Corpus.Word("Cat", 456, 789, true); ArrayList l = new ArrayList(); l.add(dog); l.add(cat); Corpus.Utterance utt = new Corpus.Utterance(100, 800, l); Corpus.Word bread = new Corpus.Word("Dog", 100, 200, false); Corpus.Word butter = new Corpus.Word("Butter", 300, 400, true); ArrayList l2 = new ArrayList(); l2.add(bread); l2.add(butter); Corpus.Utterance utt2 = new Corpus.Utterance(100, 500, l2); ArrayList l3 = new ArrayList(); l3.add(utt); l3.add(utt2); Corpus corpus = new Corpus( new Corpus.Dictionary("foo.dict"), new Corpus.Waveform("foo.pcm", 16, 16000, 1), new Corpus.Spectrogram(), new Corpus.Pitch(), new Corpus.Energy(), l3); ObjectWriter<Corpus.Utterance> uttWriter = new ObjectWriter<Corpus.Utterance>(); ObjectWriter<Corpus> corpusWriter = new ObjectWriter<Corpus>(); //writer.setClassIdentifierEnabled(false); try { ObjectWriter ow = new ObjectWriter(); OutputStream oc = new FileOutputStream("corpus.xml"); Writer oc2 = new Utf8StreamWriter().setOutputStream(oc); // UTF-8 encoding. WriterHandler corpusHandler = new WriterHandler().setWriter(oc2); corpusHandler.setIndent("\t"); // Indents with tabs. corpusHandler.setProlog("<?xml version=\"1.0\" encoding=\"UTF-8\"/>"); ow.write(corpus, corpusHandler); uttWriter.write(utt, new FileOutputStream("utt.xml")); corpusWriter.write(corpus, new FileOutputStream("corpus.xml")); Corpus.Utterance u2 = new ObjectReader<Corpus.Utterance>().read(new FileInputStream("utt.xml")); Corpus c2 = new ObjectReader<Corpus>().read(new FileInputStream("corpus.xml")); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (SAXException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } */ } <file_sep>/archive_s3/s3.0/pgm/misc/proncount.c /* * proncount.c -- Extract pronunciations for words * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-May-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * Input lines of the form (sorted): * ASKED AE S T 1 * ASKED AE S T 1 * ASKED AE S T 2 * ASKED AE S T 4 * ASKED AE S T AX 1 * ASKED AE S T AX DD 1 * ASKED AE S TD 1 * ASKED AE S TD 1 * Output sums up counts for distinct pronunciations. */ #include <libutil/libutil.h> static int32 cmp_wptr (char **p1, char **p2, int32 n) { int32 i; for (i = 0; (i < n) && (strcmp (p1[i], p2[i]) == 0); i++); return (i < n) ? -1 : 0; } #define MAX_WORDS 4092 main (int32 argc, char *argv[]) { char line[16384], **wptr, **prev_wptr; int32 i, j, k, n, lineno, count, prev_n, total_count; if (argc > 1) { E_INFO("Usage: %s < <pron.count>\n", argv[0]); exit(0); } prev_wptr = (char **) ckd_calloc (1024, sizeof(char *)); prev_n = -1; total_count = -1; wptr = (char **) ckd_calloc (MAX_WORDS, sizeof(char *)); lineno = 0; while (fgets (line, sizeof(line), stdin) != NULL) { lineno++; if ((n = str2words (line, wptr, MAX_WORDS)) < 0) E_FATAL("str2words(%s) failed; increase %d(?)\n", line, MAX_WORDS); if (n == 0) continue; /* Read last (count) field */ if (sscanf (wptr[n-1], "%d", &count) != 1) E_FATAL("Last field not a count: %s\n", wptr[n-1]); if (count == 0) break; --n; /* Omit count field */ /* Check if same as previous line (except for count field) */ if ((n == prev_n) && (cmp_wptr (wptr, prev_wptr, n) == 0)) total_count += count; else { if (total_count > 0) { printf ("%5d", total_count); printf ("\t%s\t", prev_wptr[0]); for (i = 1; i < prev_n; i++) printf (" %s", prev_wptr[i]); printf ("\n"); } total_count = count; for (i = 0; i < prev_n; i++) ckd_free (prev_wptr[i]); for (i = 0; i < n; i++) prev_wptr[i] = (char *) ckd_salloc (wptr[i]); prev_n = n; } } if (total_count > 0) { printf ("%5d", total_count); printf ("\t%s\t", prev_wptr[0]); for (i = 1; i < prev_n; i++) printf (" %s", prev_wptr[i]); printf ("\n"); } } <file_sep>/SphinxTrain/src/libs/libmllr/mllr.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #include <string.h> #include <math.h> #include <s3/s3.h> #include <s3/common.h> #include <s3/s3regmat_io.h> #include <s3/mllr.h> #include <s3/clapack_lite.h> void dump_regmat_statistics(float64 *****regl, float64 ****regr, uint32 nclass, uint32 nfeat, const uint32 *veclen) { uint32 i,j,k,l,m,len; printf("regl\n"); for(m=0; m <nclass ; m++){ for(i=0; i < nfeat ;i++){ len=veclen[i]; for(l=0; l < len ; l++){ printf("class: %d, stream: %d, mixture %d\n",m,i,l); for(j=0;j<len;j++){ printf("%d ", j); for(k=0;k<len;k++){ printf("%f ",regl[m][i][l][j][k]); } printf("\n"); } } } } printf("regr\n"); for(m=0; m <nclass ; m++){ for(i=0; i < nfeat ;i++){ len=veclen[i]; for(l=0; l < len ; l++){ printf("class: %d, stream: %d, mixture %d\n",m,i,l); for(j=0;j<len;j++){ printf("%f ",regr[m][i][l][j]); } printf("\n"); } } } } /* 20040726 : ARCHAN : What is this routine doing? This routine can do the conventional Legetter's method of maximum likelihood linear regression. For every regression class, every stream (nfeat is the number of stream). */ int32 compute_mllr ( float32 *****regl, float32 ****regr, const uint32 *veclen, uint32 nclass, uint32 nfeat, uint32 mllrmult, uint32 mllradd, float32 *****A, float32 ****B ) { uint32 i,j,k,m,len; float32 ****Aloc, ***Bloc; float32 *ABloc=NULL; Aloc = (float32 ****) ckd_calloc_2d(nclass, nfeat, sizeof(float32 ***)); Bloc = (float32 ***) ckd_calloc_2d(nclass, nfeat, sizeof(float32 **)); #if 0 dump_regmat_statistics(regl, regr, nclass, nfeat veclen); #endif /* Here, regl is the same as Legetter's G, while regr is Z. The * original papers use the formula w_i^T = G(i)^{-1} z_i^T to * calculate the rows of W (the transformation matrix). However * what they really mean by this is that we solve for w_i^T in the * equation G(i) w_i^T = z_i^T. That is what this code does, * optionally omitting the bias or rotation parts of W. */ for (m = 0; m < nclass; m++) { for (i = 0; i < nfeat; i++) { len = veclen[i]; Aloc[m][i] = (float32 **) ckd_calloc_2d(len, len, sizeof(float32)); Bloc[m][i] = (float32 *) ckd_calloc(len, sizeof(float32)); ABloc = (float32 *) ckd_calloc(len+1, sizeof(float64)); if (mllrmult && !mllradd) { /* Compute only multiplicative part of MLLR*/ E_INFO("Computing only multiplicative part of MLLR\n"); for (j = 0; j < len; j++) { Bloc[m][i][j] = 0.0; } for (j = 0; j < len; ++j) { /** If estimation of rotation not possible, dont rotate **/ if (solve(regl[m][i][j],regr[m][i][j],ABloc,len) != S3_SUCCESS){ E_INFO("Estimation of %d th multiplicative", " term in MLLR regression failed\n",j); for (k = 0;k < len; k++) { Aloc[m][i][j][k] = 0.0; } Aloc[m][i][j][j] = 1.0; } else { for (k = 0; k < len; k++) { Aloc[m][i][j][k] = ABloc[k]; } } } } else if(!mllrmult && mllradd){ /* Compute only additive part of MLLR*/ E_INFO("Computing only additive part of MLLR\n"); for (j = 0; j < len; j++) { for (k = 0; k < len; k++) { Aloc[m][i][j][k] = 0.0; } Aloc[m][i][j][j] = 1.0; } for (j = 0; j < len; j++) { /** If estimation of shift not possible, dont shift **/ if (regl[m][i][j][len][len] > MIN_IEEE_NORM_POS_FLOAT32) { Bloc[m][i][j] = (regr[m][i][j][len]-regl[m][i][j][len][j])/ regl[m][i][j][len][len]; } else { E_INFO("%th dimension of addition term of %dth MLLR adaptation underflow!\nSet to zero...\n",j); Bloc[m][i][j] = 0.0; } } } else if (mllrmult && mllradd) { /* Compute both multiplicative and additive part of MLLR*/ E_INFO("Computing both multiplicative and additive part of MLLR\n"); for (j = 0; j < len; ++j) { /** If estimation of regression not possible, dont do anything **/ if (solve(regl[m][i][j],regr[m][i][j],ABloc,len+1) != S3_SUCCESS) { E_INFO("Estimation of %d th regression in MLLR failed\n",j); for (k = 0;k < len; k++) { Aloc[m][i][j][k] = 0.0; } Aloc[m][i][j][j] = 1.0; Bloc[m][i][j] = 0.0; } else { for (k = 0; k < len; ++k) { Aloc[m][i][j][k] = ABloc[k]; } Bloc[m][i][j] = ABloc[len]; } } } else if(!mllrmult && !mllradd){ /*MLLR flags are not set - Error*/ E_FATAL("ERROR: MLLR flags are not set\n"); } ckd_free(ABloc); } } *A = Aloc; *B = Bloc; return S3_SUCCESS; } /* Solve x for equations Ax=b */ int32 solve(float32 **A, /*Input : an n*n matrix A */ float32 *b, /*Input : a n dimesion vector b */ float32 *x, /*Output : a n dimesion vector x */ int32 n) { float32 *tmp_l; float32 *tmp_r; int i, j; int32 N, NRHS, LDA, LDB, INFO; int32 *IPIV; N=n; NRHS=1; LDA=n; LDB=n; /* don't know whether we HAVE to do this to get the f2c routine running. */ tmp_l = (float32 *)ckd_calloc(N * N, sizeof(float32)); /*To use the f2c lapack function, row/column ordering of the arrays need to be changed. */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) tmp_l[j*N+i] = A[i][j]; tmp_r = (float32*) ckd_calloc(N, sizeof(float32)); for (i = 0; i < N; i++) tmp_r[i] = b[i]; IPIV = (int32 *)ckd_calloc(N, sizeof(int32)); /* Beware ! all arguments of lapack have to be a pointer */ sgesv_(&N, &NRHS, tmp_l,&LDA,IPIV,tmp_r, &LDB, &INFO); if( INFO==0 ){ /*fprintf( stderr, "OK\n" );*/ } else{ return S3_ERROR; } for(i= 0 ; i< n ; i++){ x[i] = tmp_r[i]; } ckd_free ((void *)tmp_l); ckd_free ((void *)tmp_r); ckd_free ((void *)IPIV); return S3_SUCCESS; } /* Transform means using MLLR. */ int32 mllr_transform_mean(vector_t ***mean, vector_t ***var, /* NOT USED */ uint32 gau_begin, uint32 n_mgau, uint32 n_feat, uint32 n_density, const uint32 *veclen, float32 ****A, float32 ***B, int32 *cb2mllr, uint32 n_mllr_class) { uint32 i, j, k, l, m; float32 *tmean; for (i = gau_begin; i < n_mgau; i++) { int32 mc; if (cb2mllr) mc = cb2mllr[i]; else mc = 0; if (mc < 0) continue; /* skip */ for (j = 0; j < n_feat; j++) { tmean = (float32 *)ckd_calloc(veclen[j],sizeof(float32)); for (k = 0; k < n_density; k++) { for (l = 0; l < veclen[j]; l++) { tmean[l] = 0; for (m = 0; m < veclen[j]; m++) { tmean[l] += A[mc][j][l][m] * mean[i][j][k][m]; } tmean[l] += B[mc][j][l]; } /* Write back the transformed mean vector */ for (l = 0; l < veclen[j]; l++) mean[i][j][k][l] = tmean[l]; } ckd_free(tmean); } } return S3_SUCCESS; } <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/audio/Switch.java package edu.cmu.sphinx.tools.audio; import edu.cmu.sphinx.frontend.*; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Mar 22, 2006 * Time: 5:52:38 PM */ public class Switch extends BaseDataProcessor { protected ThrowAwayThread throwAwayThread; public void open() { throwAwayThread = new ThrowAwayThread(); throwAwayThread.start(); } public void close() { if (isOn()) { throwAwayThread.interrupt(); } } public boolean isOn() { return false; } public void off() { /* // wait until the BOS has been read while (state == GOING_ON) { try { Thread.sleep(10); } catch (InterruptedException e) { } } // assert state == STREAMING; state = EOS; if (!throwingAwayData) { // assert thread == null; throwingAwayData = true; thread = new SwitchThread(); thread.start(); } */ } final int GOING_ON = 1; final int GOING_OFF = 2; final int ON = 3; final int OFF = 4; protected int state = OFF; protected int dataCount; /** * Returns the processed Data output. * * @return an Data object that has been processed by this DataProcessor * @throws edu.cmu.sphinx.frontend.DataProcessingException * if a data processor error occurs */ public Data getData() throws DataProcessingException { Data d = null; switch (state) { case GOING_ON: state = ON; d = new DataStartSignal(16000); break; case GOING_OFF: state = OFF; d = new DataEndSignal(dataCount); break; case ON: d = getPredecessor().getData(); if (d instanceof DataEndSignal) { off(); close(); } break; case OFF: d = null; break; default: throw new Error("Internal Error: Switch in bad state"); } return d; } boolean throwingAwayData; class ThrowAwayThread extends Thread { public void run() { while (throwingAwayData) { try { getPredecessor().getData(); } catch (DataProcessingException e) { // ignore exceptions } } } } } <file_sep>/CLP/configure.ac AC_PREREQ([2.65]) AC_INIT([consensus], 0.1) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AC_CONFIG_SRCDIR([src/Clustering.cc]) CXXFLAGS=${CXXFLAGS:--g -O3 -ffast-math -Wall} AC_PROG_CXX AC_PROG_CC AC_FUNC_ALLOCA AC_CHECK_HEADERS([fcntl.h stdlib.h string.h unistd.h]) AC_HEADER_STDBOOL AC_C_INLINE AC_TYPE_SIZE_T AC_CHECK_FUNCS([mkdir strchr]) AC_CONFIG_FILES([Makefile include/Makefile src/Makefile]) AC_OUTPUT <file_sep>/archive_s3/s3.0/src/libmain/senone.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * senone.c -- Mixture density weights associated with each tied state. * * * HISTORY * * $Log$ * Revision 1.2 2001/05/29 15:17:43 lenzo * License updated to Open Source Sphinx * * Revision 1.1 2000/04/24 09:07:29 lenzo * Import s3.0. * * * 21-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started based on original S3 implementation. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libmisc/libmisc.h> #include "senone.h" #if _SENONE_TEST_ #include "gauden.h" #endif #define MIXW_PARAM_VERSION "1.0" #define SPDEF_PARAM_VERSION "1.2" #if _SENONE_TEST_ static void senone_dump (const senone_t *s) { int32 i, j, c, m, f; mixw_t *fw; for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; /* Parent mgau */ j = s->mgau2sen_idx[i]; /* Index of senone i within list of senones for mgau m */ fw = s->mgau2sen[m].feat_mixw; for (f = 0; f < s->n_feat; f++) { printf ("%5d %5d %5d %2d %4d", i, m, j, f, fw[f].n_wt); for (c = 0; c < fw[f].n_wt; c++) printf (" %3d", fw[f].prob[j][c]); printf ("\n"); } } } #endif static int32 senone_mgau_map_read (senone_t *s, char *file_name) { FILE *fp; int32 byteswap, chksum_present, n_mgau_present; uint32 chksum; int32 i; char eofchk; char **argname, **argval; float32 v; E_INFO("Reading senone-codebook map file: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; n_mgau_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], SPDEF_PARAM_VERSION) != 0) { E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], SPDEF_PARAM_VERSION); } /* HACK!! Convert version# to float32 and take appropriate action */ if (sscanf (argval[i], "%f", &v) != 1) E_FATAL("%s: Bad version no. string: %s\n", file_name, argval[i]); n_mgau_present = (v > 1.1) ? 1 : 0; } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #gauden (if version matches) */ if (n_mgau_present) { if (bio_fread (&(s->n_mgau), sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#gauden) failed\n", file_name); } /* Read 1d array data; s->sen2mgau allocated by called function */ if (bio_fread_1d ((void **)(&s->sen2mgau), sizeof(int32), &(s->n_sen), fp, byteswap, &chksum) < 0) { E_FATAL("bio_fread_1d(%s) failed\n", file_name); } /* Infer n_mgau if not present in this version */ if (! n_mgau_present) { s->n_mgau = 1; for (i = 0; i < s->n_sen; i++) { if (s->sen2mgau[i] >= s->n_mgau) s->n_mgau = s->sen2mgau[i]+1; } } if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); /* Check for validity of mappings */ for (i = 0; i < s->n_sen; i++) { if ((s->sen2mgau[i] >= s->n_mgau) || NOT_MGAUID(s->sen2mgau[i])) E_FATAL("Bad sen2mgau[%d]= %d, out of range [0, %d)\n", i, s->sen2mgau[i], s->n_mgau); } if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read %d->%d senone-codebook mappings\n", s->n_sen, s->n_mgau); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static void build_mgau2sen (senone_t *s, int32 n_cw) { int32 i, j, m, f; s3senid_t *sen; mixw_t *fw; /* Create mgau2sen map from sen2mgau */ s->mgau2sen = (mgau2sen_t *) ckd_calloc (s->n_mgau, sizeof(mgau2sen_t)); s->mgau2sen_idx = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; assert ((m < s->n_mgau) && (m >= 0)); (s->mgau2sen[m].n_sen)++; } sen = (s3senid_t *) ckd_calloc (s->n_sen, sizeof(s3senid_t)); for (m = 0; m < s->n_mgau; m++) { s->mgau2sen[m].sen = sen; sen += s->mgau2sen[m].n_sen; s->mgau2sen[m].n_sen = 0; } for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; j = s->mgau2sen[m].n_sen; s->mgau2sen[m].sen[j] = i; s->mgau2sen_idx[i] = j; (s->mgau2sen[m].n_sen)++; } /* Allocate space for the weights */ for (m = 0; m < s->n_mgau; m++) { fw = (mixw_t *) ckd_calloc (s->n_feat, sizeof(mixw_t)); s->mgau2sen[m].feat_mixw = fw; for (f = 0; f < s->n_feat; f++) { fw[f].n_wt = n_cw; fw[f].prob = (senprob_t **) ckd_calloc_2d (s->mgau2sen[m].n_sen, n_cw, sizeof(senprob_t)); } } } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static int32 senone_mixw_read(senone_t *s, char *file_name, float64 mixwfloor) { FILE *fp; char **argname, **argval; int32 byteswap, chksum_present; uint32 chksum; float32 *pdf; int32 i, j, f, m, c, p, n_sen, n_err, n_cw, nval; char eofchk; mixw_t *fw; E_INFO("Reading senone mixture weights: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], MIXW_PARAM_VERSION) != 0) E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], MIXW_PARAM_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #senones, #features, #codewords, arraysize */ n_sen = s->n_sen; if ((bio_fread (&(s->n_sen), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(s->n_feat), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(n_cw), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&nval, sizeof(int32), 1, fp, byteswap, &chksum) != 1)) { E_FATAL("bio_fread(%s) (arraysize) failed\n", file_name); } if ((n_sen != 0) && (s->n_sen != n_sen)) E_FATAL("#senones(%d) conflict with mapping file(%d)\n", s->n_sen, n_sen); if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_feat <= 0) E_FATAL("Bad #features: %d\n", s->n_feat); if (n_cw <= 0) E_FATAL("Bad #mixing-wts/senone: %d\n", n_cw); /* Allocate sen2mgau map if not yet done so (i.e. no explicit mapping file given */ if (! s->sen2mgau) { assert ((s->n_mgau == 0) || (s->n_mgau == 1)); s->sen2mgau = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); if (s->n_mgau == 1) { /* Semicontinuous mode; all senones map to single, shared gaussian: 0 */ for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = 0; } else { /* Fully continuous mode; each senone maps to own parent gaussian */ s->n_mgau = s->n_sen; for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = i; } } else assert (s->n_mgau != 0); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); if (nval != s->n_sen * s->n_feat * n_cw) { E_FATAL("%s: #float32 values(%d) doesn't match dimensions: %d x %d x %d\n", file_name, nval, s->n_sen, s->n_feat, n_cw); } /* * Compute #LSB bits to be dropped to represent mixwfloor with 8 bits. * All PDF values will be truncated (in the LSB positions) by these many bits. */ if ((mixwfloor <= 0.0) || (mixwfloor >= 1.0)) E_FATAL("mixwfloor (%e) not in range (0, 1)\n", mixwfloor); p = logs3(mixwfloor); for (s->shift = 0, p = -p; p >= 256; s->shift++, p >>= 1); E_INFO("Truncating senone logs3(wt) values by %d bits, to 8 bits\n", s->shift); /* Allocate memory for s->mgau2sen and senone PDF data */ build_mgau2sen (s, n_cw); /* Temporary structure to read in floats */ pdf = (float32 *) ckd_calloc (n_cw, sizeof(float32)); /* Read senone probs data, normalize, floor, convert to logs3, truncate to 8 bits */ n_err = 0; for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; /* Parent mgau */ j = s->mgau2sen_idx[i]; /* Index of senone i within list of senones for mgau m */ fw = s->mgau2sen[m].feat_mixw; for (f = 0; f < s->n_feat; f++) { if (bio_fread((void *)pdf, sizeof(float32), n_cw, fp, byteswap, &chksum) != n_cw) { E_FATAL("bio_fread(%s) (arraydata) failed\n", file_name); } /* Normalize and floor */ if (vector_sum_norm (pdf, n_cw) == 0.0) n_err++; vector_floor (pdf, n_cw, mixwfloor); vector_sum_norm (pdf, n_cw); /* Convert to logs3, truncate to 8 bits, and store in s->pdf */ for (c = 0; c < n_cw; c++) { p = -(logs3(pdf[c])); p += (1 << (s->shift-1)) - 1; /* Rounding before truncation */ p = (p < (255 << s->shift)) ? (p >> s->shift) : 255; /* Trunc/shift */ fw[f].prob[j][c] = p; } } } if (n_err > 0) E_WARN("Weight normalization failed for %d senones\n", n_err); ckd_free (pdf); if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read mixture weights for %d senones: %d features x %d codewords\n", s->n_sen, s->n_feat, n_cw); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ senone_t *senone_init (char *mixwfile, char *sen2mgau_map, float64 mixwfloor) { senone_t *s; s = (senone_t *) ckd_calloc (1, sizeof(senone_t)); s->n_sen = 0; /* As yet unknown */ s->sen2mgau = NULL; assert (sen2mgau_map); if (strcmp (sen2mgau_map, ".semi.") == 0) { /* Not a file; map all senones to a single parent mgau */ s->n_mgau = 1; /* But we don't yet know the #senones */ } else if (strcmp (sen2mgau_map, ".cont.") == 0) { /* Not a file; map each senone to its own distinct parent mgau */ s->n_mgau = 0; /* We don't yet know the #senones */ } else { /* Read mapping file */ senone_mgau_map_read (s, sen2mgau_map); /* Fills in n_sen */ } assert (mixwfile); senone_mixw_read (s, mixwfile, mixwfloor); return s; } int32 senone_eval (senone_t *s, int32 sid, int32 f, int32 *dist, int32 *valid, int32 n_dist) { int32 i, j, c, scr, fscr; s3mgauid_t m; mixw_t *fw; m = s->sen2mgau[sid]; assert ((m >= 0) && (m < s->n_mgau)); fw = &(s->mgau2sen[m].feat_mixw[f]); assert ((fw->n_wt >= n_dist) && (n_dist > 0)); i = s->mgau2sen_idx[sid]; /* Weight first codeword */ if (valid) { j = valid[0]; scr = dist[j] - (fw->prob[i][j] << s->shift); /* Remaining codewords */ for (c = 1; c < n_dist; c++) { j = valid[c]; fscr = dist[j] - (fw->prob[i][j] << s->shift); scr = logs3_add (scr, fscr); } } else { scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } } return scr; } void senone_eval_all (senone_t *s, int32 m, int32 f, int32 *dist, int32 *valid, int32 n_dist, int32 *senscr) { int32 i, j, c, scr, fscr; s3senid_t sid; mixw_t *fw; fw = &(s->mgau2sen[m].feat_mixw[f]); assert ((fw->n_wt >= n_dist) && (n_dist > 0)); if (valid) { for (i = 0; i < s->mgau2sen[m].n_sen; i++) { sid = s->mgau2sen[m].sen[i]; /* Weight first codeword */ j = valid[0]; scr = dist[j] - (fw->prob[i][j] << s->shift); /* Remaining codewords */ for (c = 1; c < n_dist; c++) { j = valid[c]; fscr = dist[j] - (fw->prob[i][j] << s->shift); scr = logs3_add (scr, fscr); } senscr[sid] += scr; } } else { for (i = 0; i < s->mgau2sen[m].n_sen; i++) { sid = s->mgau2sen[m].sen[i]; #if 1 /* Weight first codeword */ scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } senscr[sid] += scr; #else senscr[sid] += senone_eval (s, sid, f, dist, n_dist); #endif } } } void senone_set_active (bitvec_t sen_active, s3senid_t *sen, int32 n_sen) { int32 i; for (i = 0; i < n_sen; i++) bitvec_set (sen_active, sen[i]); } int32 senone_get_senscale (int32 *scale, int32 sf, int32 ef) { int32 f, sc; sc = 0; for (f = sf; f <= ef; f++) sc += scale[f]; return sc; } #if (_SENONE_TEST_) main (int32 argc, char *argv[]) { gauden_t *g; senone_t *s; float64 varflr, wtflr; int32 *dist; char *cepfile; float32 **feat, **mfc; int32 i, j, w, m, f, d, k, nfr, cepsize; int32 *senscr; if (argc != 9) E_FATAL("Usage: %s mean var varfloor sen mgaumap mixwfloor cep feat\n", argv[0]); if (sscanf (argv[3], "%lf", &varflr) != 1) E_FATAL("Usage: %s mean var varfloor sen mgaumap mixwfloor cep feat\n", argv[0]); if (sscanf (argv[6], "%lf", &wtflr) != 1) E_FATAL("Usage: %s mean var varfloor sen mgaumap mixwfloor cep feat\n", argv[0]); logs3_init ((float64) 1.0001); feat_init (argv[8]); cepsize = feat_cepsize (); s = senone_init (argv[4], argv[5], wtflr); #if 1 senone_dump (s); fflush (stdout); #endif g = gauden_init (argv[1], argv[2], varflr, TRUE); #if 0 gauden_dump (g); #endif cepfile = argv[7]; feat = (float32 **) ckd_calloc (g->n_feat, sizeof(float32 *)); for (i = 0; i < g->n_feat; i++) feat[i] = (float32 *) ckd_calloc (g->featlen[i], sizeof(float32)); dist = (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); w = feat_window_size (); senscr = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); nfr = s2mfc_read (cepfile, 0, (int32)0x7ffffff0, 0, &mfc); E_INFO("%d frames\n", nfr); cmn (mfc, nfr, cepsize); agc_max (mfc, nfr); for (i = w; i < nfr-w-1; i++) { feat_cep2feat (mfc+i, feat); memset (senscr, 0, s->n_sen * sizeof(int32)); for (m = 0; m < g->n_mgau; m++) { for (f = 0; f < g->n_feat; f++) { k = gauden_dist (g, m, f, feat[f], dist); senone_eval_all (s, m, f, dist, k, senscr); } } printf ("%5d:\n", i); for (j = 0; j < s->n_sen; j++) printf ("%d\n", senscr[j]); } } #endif <file_sep>/SphinxTrain/src/libs/libclust/kmeans.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: kmeans.c * * Description: * Given a set of K mean vectors and any sample vector out of a * corpus of vectors, label the sample vector with the mean vector * index which minimizes the Eucl. distance between the two. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/kmeans.h> #include <s3/ckd_alloc.h> #include <s3/profile.h> #include <s3/s3.h> #include <assert.h> #ifndef NULL #define NULL (void *)0 #endif static vector_t (*get_obs)(uint32 i); void k_means_set_get_obs(vector_t (*fn)(uint32 i)) { get_obs = fn; } static void nn_sort_kmeans(vector_t *mean, uint32 n_mean, uint32 veclen, idx_dist_t **nnmap); float64 k_means(vector_t *mean, /* initial set of means */ uint32 n_mean, /* # of means (should be k_mean?) */ uint32 n_obs, /* # of observations */ uint32 veclen, /* vector length of means and corpus */ float32 min_conv_ratio, uint32 max_iter, /* If not converged by this count, just quit */ codew_t **out_label) /* The final labelling of the corpus according to the adjusted means; if NULL passed, just discarded. */ { uint32 i; float32 p_sqerr = MAX_POS_FLOAT32; float32 sqerr; float32 conv_ratio; codew_t *label; int ret; label = (codew_t *)ckd_calloc(n_obs, sizeof(codew_t)); sqerr = k_means_label(label, mean, n_mean, n_obs, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; for (i = 0; (i < max_iter) && (conv_ratio > min_conv_ratio); i++) { E_INFO("kmtrineq iter [%u] %e ...\n", i, conv_ratio); ret = k_means_update(mean, n_mean, veclen, label, n_obs); if (ret != K_MEANS_SUCCESS) return (float64)ret; p_sqerr = sqerr; sqerr = k_means_label(label, mean, n_mean, n_obs, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; } E_INFO("km n_iter %u sqerr %e conv_ratio %e\n", i, sqerr, conv_ratio); if (out_label) { *out_label = label; } else { ckd_free(label); } return sqerr; } float64 k_means_trineq(vector_t *mean, /* initial set of means */ uint32 n_mean, /* # of means (should be k_mean?) */ uint32 n_obs, /* # of observations */ uint32 veclen, /* vector length of means and corpus */ float32 min_conv_ratio, uint32 max_iter, /* If not converged by this count, just quit */ codew_t **out_label) /* The final labelling of the corpus according to the adjusted means; if NULL passed, just discarded. */ { uint32 i; float32 p_sqerr = MAX_POS_FLOAT32; float32 sqerr; float32 conv_ratio; codew_t *label; int ret; idx_dist_t **nnmap; /* for a given codeword, ascendingly sorted list of its nearest neighbors. i.e. nnmap[k][0] would be the nearest neighbor to codeword k, etc. */ label = (codew_t *)ckd_calloc(n_obs, sizeof(codew_t)); sqerr = k_means_label(label, mean, n_mean, n_obs, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; nnmap = (idx_dist_t **)ckd_calloc_2d(n_mean, n_mean-1, sizeof(idx_dist_t)); for (i = 0; (i < max_iter) && (conv_ratio > min_conv_ratio); i++) { E_INFO("km iter [%u] %e ...\n", i, conv_ratio); ret = k_means_update(mean, n_mean, veclen, label, n_obs); if (ret != K_MEANS_SUCCESS) return (float64)ret; nn_sort_kmeans(mean, n_mean, veclen, nnmap); p_sqerr = sqerr; sqerr = k_means_label_trineq(label, mean, n_mean, nnmap, n_obs, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; } E_INFO("kmtrineq n_iter %u sqerr %e conv_ratio %e\n", i, sqerr, conv_ratio); ckd_free(nnmap); if (out_label) { *out_label = label; } else { ckd_free(label); } return sqerr; } /********************************************************************* * * Function: * * Description: * * Function Inputs: * * Global Inputs: * * Return Values: * * Global Outputs: * * Errors: * * Pre-Conditions: * * Post-Conditions: * * Design: * * Notes: * *********************************************************************/ float64 k_means_label(codew_t *label, vector_t *mean, uint32 n_mean, /* # of mean vectors */ uint32 n_obs, /* in # of vectors */ uint32 veclen) { uint32 i, j, b_j, l; float64 t, d; float64 b_d; float64 sqerr; vector_t c; vector_t m; for (i = 0, sqerr = 0; i < n_obs; i++, sqerr += b_d) { c = get_obs(i); if (c == NULL) { E_INFO("No observations for %u, but expected up through %u\n", i, n_obs-1); } /* Get an estimate of best distance (b_d) and codeword (b_j) */ b_j = label[i]; m = mean[b_j]; for (l = 0, b_d = 0.0; l < veclen; l++) { t = m[l] - c[l]; b_d += t * t; } for (j = 0; j < n_mean; j++) { m = mean[j]; for (l = 0, d = 0.0; (l < veclen) && (d < b_d); l++) { t = m[l] - c[l]; d += t * t; } if (d < b_d) { b_d = d; b_j = j; } } label[i] = b_j; } return sqerr; } int cmp_dist(const void *a, const void *b) { const idx_dist_t *a_ = (idx_dist_t *)a; const idx_dist_t *b_ = (idx_dist_t *)b; if (a_->d < b_->d) { return -1; } else if (a_->d > b_->d) { return 1; } else { return 0; } } static void nn_sort_kmeans(vector_t *mean, uint32 n_mean, uint32 veclen, idx_dist_t **nnmap) { uint32 i, j, k, l; vector_t ma, mb; float64 diff, d; for (i = 0; i < n_mean; i++) { ma = mean[i]; for (j = 0, k = 0; j < n_mean; j++) { if (i != j) { mb = mean[j]; for (l = 0, d = 0; l < veclen; l++) { diff = ma[l] - mb[l]; d += diff * diff; } nnmap[i][k].idx = j; nnmap[i][k].d = d; ++k; } } assert(k == (n_mean-1)); qsort(&nnmap[i][0], n_mean-1, sizeof(idx_dist_t), cmp_dist); } } float64 k_means_label_trineq(codew_t *label, vector_t *mean, uint32 n_mean, /* # of mean vectors */ idx_dist_t **nnmap, uint32 n_obs, /* in # of vectors */ uint32 veclen) { uint32 i, eb_j, b_j, l, k; float64 t, d; float64 b_d, eb_d; float64 sqerr; vector_t c; vector_t m; idx_dist_t *nnmap_eb; for (i = 0, sqerr = 0; i < n_obs; i++) { c = get_obs(i); if (c == NULL) { E_INFO("No observations for %u, but expected up through %u\n", i, n_obs-1); } /* Get an estimate of b_d */ eb_j = label[i]; m = mean[eb_j]; for (l = 0, eb_d = 0.0; l < veclen; l++) { t = m[l] - c[l]; eb_d += t * t; } nnmap_eb = nnmap[eb_j]; b_d = eb_d; b_j = eb_j; for (k = 0; k < n_mean-1 && nnmap_eb[k].d <= 4.0 * eb_d; k++) { m = mean[nnmap_eb[k].idx]; for (l = 0, d = 0.0; (l < veclen) && (d < b_d); l++) { t = m[l] - c[l]; d += t * t; } if (d < b_d) { b_j = nnmap_eb[k].idx; b_d = d; } } sqerr += b_d; label[i] = b_j; } return sqerr; } #include <s3/ckd_alloc.h> /********************************************************************* * * Function: * * Description: * * Function Inputs: * * Global Inputs: * * Return Values: * * Global Outputs: * * Errors: * * Pre-Conditions: * * Post-Conditions: * * Design: * * Notes: * *********************************************************************/ int k_means_update(vector_t *mean, uint32 n_mean, uint32 veclen, codew_t *label, uint32 n_obs) { uint32 i, j, l, *cnt; vector_t m; vector_t c; int ret = K_MEANS_SUCCESS; cnt = (uint32 *)ckd_calloc(n_mean, sizeof(uint32)); for (i = 0; i < n_mean; i++) { for (l = 0; l < veclen; l++) { mean[i][l] = 0.0; } } for (i = 0; i < n_obs; i++) { assert((0 <= label[i]) && (label[i] < n_mean)); m = mean[label[i]]; cnt[label[i]]++; c = get_obs(i); if (c == NULL) { E_INFO("No observations for %u, but expected up through %u\n", i, n_obs-1); } for (l = 0; l < veclen; l++) { m[l] += c[l]; } } for (i = 0; i < n_mean; i++) { j = cnt[i]; if (j != 0) { for (l = 0; l < veclen; l++) { mean[i][l] /= (float32) j; } } else { E_WARN("Empty cluster %u\n", i); ret = K_MEANS_EMPTY_CODEWORD; } } ckd_free(cnt); return ret; } /********************************************************************* * * Function: * * Description: * * Function Inputs: * * Global Inputs: * * Return Values: * * Global Outputs: * * Errors: * * Pre-Conditions: * * Post-Conditions: * * Design: * * Notes: * *********************************************************************/ float64 k_means_label_subset(codew_t *label, vector_t *mean, uint32 n_mean, /* # of mean vectors */ uint32 *subset, uint32 n_obs_subset, /* in # of vectors */ uint32 veclen) { uint32 i, j, b_j=0, l; float64 t, d; float64 b_d; float64 sqerr; vector_t c; vector_t m; for (i = 0, sqerr = 0; i < n_obs_subset; i++) { b_d = 1e300; c = get_obs(subset[i]); for (j = 0; j < n_mean; j++) { m = mean[j]; for (l = 0, d = 0.0; (l < veclen) && (d < b_d); l++) { t = m[l] - c[l]; d += t * t; } if (d < b_d) { b_d = d; b_j = j; } } label[i] = b_j; sqerr += b_d; } return sqerr; } /********************************************************************* * * Function: * * Description: * * Function Inputs: * * Global Inputs: * * Return Values: * * Global Outputs: * * Errors: * * Pre-Conditions: * * Post-Conditions: * * Design: * * Notes: * *********************************************************************/ int k_means_update_subset(vector_t *mean, uint32 n_mean, uint32 veclen, uint32 *subset, codew_t *label, uint32 n_obs_subset) { uint32 i, j, l, *cnt; vector_t m; vector_t c; int ret = K_MEANS_SUCCESS; cnt = (uint32 *)ckd_calloc(n_mean, sizeof(uint32)); for (i = 0; i < n_mean; i++) { for (l = 0; l < veclen; l++) { mean[i][l] = 0.0; } } for (i = 0; i < n_obs_subset; i++) { assert((0 <= label[i]) && (label[i] < n_mean)); m = mean[label[i]]; cnt[label[i]]++; c = get_obs(subset[i]); for (l = 0; l < veclen; l++) { m[l] += c[l]; } } for (i = 0; i < n_mean; i++) { j = cnt[i]; if (j != 0) { for (l = 0; l < veclen; l++) { mean[i][l] /= (float32) j; } } else { E_WARN("Empty cluster %u\n", i); ret = K_MEANS_EMPTY_CODEWORD; } } ckd_free(cnt); return ret; } float64 k_means_subset(vector_t *mean, /* initial set of means */ uint32 n_mean, /* # of means (should be k_mean?) */ uint32 *subset, uint32 n_obs_subset, /* # of observations */ uint32 veclen, /* vector length of means and corpus */ float32 min_conv_ratio, uint32 max_iter, /* If not converged by this count, just quit */ codew_t **out_label) /* The final labelling of the corpus according to the adjusted means; if NULL passed, just discarded. */ { uint32 i; float32 p_sqerr = MAX_POS_FLOAT32; float32 sqerr; float32 conv_ratio; codew_t *label; int ret; label = (codew_t *)ckd_calloc(n_obs_subset, sizeof(codew_t)); sqerr = k_means_label_subset(label, mean, n_mean, subset, n_obs_subset, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; E_INFO("sqerr %e conv_ratio %e\n", sqerr, conv_ratio); for (i = 0; (i < max_iter) && (conv_ratio > min_conv_ratio); i++) { ret = k_means_update_subset(mean, n_mean, veclen, subset, label, n_obs_subset); if (ret != K_MEANS_SUCCESS) return (float64)ret; p_sqerr = sqerr; sqerr = k_means_label_subset(label, mean, n_mean, subset, n_obs_subset, veclen); conv_ratio = (p_sqerr - sqerr) / p_sqerr; E_INFO("sqerr %e conv_ratio %e\n", sqerr, conv_ratio); } if (out_label) { /* caller provided place to save the VQ labels */ *out_label = label; } else { /* caller provided no way to save 'em, so chunk 'em */ ckd_free(label); } return sqerr; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 1995/12/01 20:56:39 eht * Initial revision * * */ <file_sep>/sphinx4/tests/other/InstanceOfTest.java /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package tests.other; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.TimerPool; /** * * Performas some math timings. Used to compare different modes of * math (floating, double, mixed, integer) */ public class InstanceOfTest { private int maxIterations; Timer instanceOfTimer; Timer booleanTimer; Timer castTimer; Timer noCastTimer; public InstanceOfTest(int iterations) { maxIterations = iterations; instanceOfTimer = TimerPool.getTimer(this, "instanceOfTimer"); booleanTimer = TimerPool.getTimer(this, "booleanTimer"); castTimer = TimerPool.getTimer(this, "castTimer"); noCastTimer = TimerPool.getTimer(this, "noCastTimer"); } /** * instance of check */ public int doInstanceOfCheck(BaseClass[] bc) { int fooCount = 0; instanceOfTimer.start(); for (int i = 0; i < maxIterations; i++) { for (BaseClass baseClass : bc) { if (baseClass instanceof FooClass) { fooCount++; } } } instanceOfTimer.stop(); return fooCount; } /** * boolean check */ public int doBooleanCheck(BaseClass[] bc) { int fooCount = 0; booleanTimer.start(); for (int i = 0; i < maxIterations; i++) { for (BaseClass baseClass : bc) { if (baseClass.isFoo()) { fooCount++; } } } booleanTimer.stop(); return fooCount; } /** * instance of check */ public int doCastCheck(BaseClass[] bc) { int fooCount = 0; castTimer.start(); for (int i = 0; i < maxIterations; i++) { for (BaseClass baseClass : bc) { if (baseClass instanceof FooClass) { FooClass foo = (FooClass)baseClass; fooCount += foo.getBigId(); } } } castTimer.stop(); return fooCount; } public int doNoCastCheck(BaseClass[] bc) { int fooCount = 0; noCastTimer.start(); for (int i = 0; i < maxIterations; i++) { for (BaseClass baseClass : bc) { if (baseClass instanceof FooClass) { FooClass foo = ((FooClass)baseClass).getFooClass(); fooCount += foo.getBigId(); } } } noCastTimer.stop(); return fooCount; } /** * Time all of the routines for multiple interations */ public void doScores(BaseClass[] bc) { doInstanceOfCheck(bc); doBooleanCheck(bc); doCastCheck(bc); doNoCastCheck(bc); } /** * Shows the results */ public void dump() { TimerPool.dumpAll(); } /** * Runs the timing test */ public final static int COUNT = 10000; public static void main(String[] args) { InstanceOfTest iot = new InstanceOfTest(10000); BaseClass[] array = new BaseClass[COUNT]; for (int i = 0; i < array.length; i++) { array[i] = (i % 2 == 1) ? new BaseClass(i) : new FooClass(i); } // warm-up iot.doScores(array); TimerPool.resetAll(); // go live iot.doScores(array); iot.dump(); } } class BaseClass { int id; BaseClass(int id) { this.id = id; } boolean isFoo() { return false; } int getId() { return id; } } class FooClass extends BaseClass { FooClass(int id) { super(id); } final boolean isFoo() { return true; } FooClass getFooClass() { return this; } int getBigId() { return getId() * 2; } } <file_sep>/archive_s3/s3.0/pgm/mfc2ascii/mfc2ascii.c /* * mfc2ascii.c -- Print out an mfc cepstrum file in readable ascii format. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 21-Jul-1998 <NAME> (<EMAIL>) at Carnegie Mellon University * Added temporal smoothing (-lpf) option. * * 14-May-1998 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <sys/types.h> #include <sys/stat.h> #if (! WIN32) #include <sys/file.h> #include <sys/errno.h> #include <sys/param.h> #else #include <fcntl.h> #endif static void usagemsg (char *pgm) { printf ("Usage: %s [-lpf(smooth)] [-numbered] [-s<startdim(0..12)>] [-e<enddim(0..12)>] <mfcfile>\n", pgm); exit(-1); } main (int argc, char *argv[]) { struct stat statbuf; char *file; FILE *fp; int32 byterev; int32 i, n, n_float32, fr, numbered, sd, ed, smooth; float32 cep[13], cep_1[13], cep_2[13], c; /* Hack!! Hardwired 13 */ if (argc < 2) usagemsg (argv[0]); numbered = 0; file = NULL; sd = -1; /* Start and end dimensions to output */ ed = -1; smooth = 0; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'n': if (numbered) usagemsg (argv[0]); numbered = 1; break; case 'l': if (smooth) usagemsg (argv[0]); smooth = 1; break; case 's': if ((sd >= 0) || (sscanf (&(argv[i][2]), "%d", &sd) != 1) || (sd < 0) || (sd > 12)) usagemsg (argv[0]); break; case 'e': if ((ed >= 0) || (sscanf (&(argv[i][2]), "%d", &ed) != 1) || (ed < 0) || (ed > 12)) usagemsg (argv[0]); break; default: usagemsg (argv[0]); break; } } else { if (file) usagemsg (argv[0]); file = argv[i]; } } if (! file) usagemsg (argv[0]); if (sd < 0) sd = 0; if (ed < 0) ed = 12; if (stat (file, &statbuf) != 0) { E_ERROR("stat(%s) failed\n", file); return -1; } if ((fp = fopen(file, "rb")) == NULL) { E_ERROR("fopen(%s,rb) failed\n", file); return -1; } /* Read #floats in header */ if (fread_retry (&n_float32, sizeof(int32), 1, fp) != 1) { fclose (fp); return -1; } /* Check of n_float32 matches file size */ byterev = FALSE; if ((n_float32*sizeof(float32) + 4) != statbuf.st_size) { n = n_float32; SWAP_INT32(&n); if ((n*sizeof(float32) + 4) != statbuf.st_size) { E_ERROR("Header size field: %d(%08x); filesize: %d(%08x)\n", n_float32, n_float32, statbuf.st_size, statbuf.st_size); fclose (fp); return -1; } n_float32 = n; byterev = TRUE; } if (n_float32 <= 0) { E_ERROR("Header size field: %d\n", n_float32); fclose (fp); return -1; } if (byterev) E_INFO("Byte-reversing %s\n", file); E_INFO("Dimensions %d..%d%s\n", sd, ed, (smooth ? " (LPFed)" : "")); fr = 0; while (fread (cep, sizeof(float32), 13, fp) == 13) { if (byterev) { for (i = 0; i < 13; i++) { SWAP_FLOAT32(cep+i); } } if (smooth) { /* Smoothing (LPF-ing): 0.25, 0.5, 0.25; except at the ends: 0.5, 0.5 */ if ((fr > 0) && numbered) printf ("%10d ", fr-1); if (fr == 1) { for (i = sd; i <= ed; i++) { c = 0.5 * cep_1[i] + 0.5 * cep[i]; printf (" %11.7f", c); } } else if (fr > 1) { for (i = sd; i <= ed; i++) { c = 0.25 * cep_2[i] + 0.5 * cep_1[i] + 0.25 * cep[i]; printf (" %11.7f", c); } } memcpy (cep_2, cep_1, sizeof(float32) * 13); memcpy (cep_1, cep, sizeof(float32) * 13); } else { if (numbered) printf ("%10d ", fr); for (i = sd; i <= ed; i++) { printf (" %11.7f", cep[i]); } } if ((! smooth) || (fr > 0)) printf ("\n"); fflush (stdout); fr++; } if (smooth && (fr > 0)) { if (numbered) printf ("%10d ", fr-1); if (fr > 1) { for (i = sd; i <= ed; i++) { c = 0.5 * cep_2[i] + 0.5 * cep_1[i]; printf (" %11.7f", c); } } else if (fr == 1) { for (i = sd; i <= ed; i++) printf (" %11.7f", cep_1[i]); } printf ("\n"); fflush (stdout); } } <file_sep>/share/lm3g2dmp/lm_3g.h /* * lm_3g.h - darpa standard trigram language model header file * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-Apr-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Added lm3g_raw_score() and lm_t.invlw. * Changed lm_{u,b,t}g_score to lm3g_{u,b,t}g_score. * * 01-Jul-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Added tginfo_t to help speed up find_bg() and find_tg() searches. * * $Log$ * Revision 1.1 2002/11/11 17:42:40 egouvea * Initial import of lm3g2dmp from Ravi's files. * * Revision 1.1.1.1 2000/02/28 18:34:44 rkm * Imported Sources * * Revision 6.5 93/10/27 17:47:04 rkm * *** empty log message *** * * Revision 6.4 93/10/15 15:02:39 rkm * *** empty log message *** * */ #ifndef _LM_3G_H_ #define _LM_3G_H_ #include "primtype.h" #include "hash.h" /* log quantities represented in either floating or integer format */ typedef union { float f; int32 l; } log_t; typedef struct unigram_s { int32 wid; /* dict word-id */ log_t prob1; log_t bo_wt1; int32 bigrams; /* index of 1st entry in lm_t.bigrams[] */ } unigram_t, UniGram, *UniGramPtr; /* * To conserve space, bigram info is kept in many tables. Since the number * of distinct values << #bigrams, these table indices can be 16-bit values. * prob2 and bo_wt2 are such indices, but keeping trigram index is less easy. * It is supposed to be the index of the first trigram entry for each bigram. * But such an index cannot be represented in 16-bits, hence the following * segmentation scheme: Partition bigrams into segments of BG_SEG_SZ * consecutive entries, such that #trigrams in each segment <= 2**16 (the * corresponding trigram segment). The bigram_t.trigrams value is then a * 16-bit relative index within the trigram segment. A separate table-- * lm_t.tseg_base--has the index of the 1st trigram for each bigram segment. */ #define BG_SEG_SZ 512 /* chosen so that #trigram/segment <= 2**16 */ #define LOG_BG_SEG_SZ 9 typedef struct bigram_s { u_int16 wid; /* dict word-id */ u_int16 prob2; /* index into array of actual bigram probs */ u_int16 bo_wt2; /* index into array of actual bigram backoff wts */ u_int16 trigrams; /* index of 1st entry in lm_t.trigrams[], RELATIVE TO its segment base (see above) */ } bigram_t, BiGram, *BiGramPtr; /* * As with bigrams, trigram prob info kept in a separate table for conserving * memory space. */ typedef struct trigram_s { u_int16 wid; /* dict word-id */ u_int16 prob3; /* index into array of actual trigram probs */ } trigram_t; /* * The following trigram information cache eliminates most traversals of 1g->2g->3g * tree to locate trigrams for a given bigram (lw1,lw2). The organization is optimized * for locality of access (to the same lw1), given lw2. */ typedef struct tginfo_s { int32 w1; /* lw1 component of bigram lw1,lw2. All bigrams with same lw2 linked together (see lm_t.tginfo). */ int32 n_tg; /* #tg for parent bigram lw1,lw2 */ int32 bowt; /* tg bowt for lw1,lw2 */ int32 used; /* whether used since last lm_reset */ trigram_t *tg; /* Trigrams for lw1,lw2 */ struct tginfo_s *next; /* Next lw1 with same parent lw2; NULL if none. */ } tginfo_t; /* * The language model. * Bigrams for each unigram are contiguous. Bigrams for unigram i+1 come * immediately after bigrams for unigram i. So, no need for a separate count * of bigrams/unigram; it is enough to know the 1st bigram for each unigram. * But an extra dummy unigram entry needed at the end to terminate the last * real entry. * Similarly, trigrams for each bigram are contiguous and trigrams for bigram * i+1 come immediately after trigrams for bigram i, and an extra dummy bigram * entry is required at the end. */ typedef struct lm_s { unigram_t *unigrams; bigram_t *bigrams; /* for entire LM */ trigram_t *trigrams;/* for entire LM */ log_t *prob2; /* table of actual bigram probs */ int32 n_prob2; /* prob2 size */ log_t *bo_wt2; /* table of actual bigram backoff weights */ int32 n_bo_wt2; /* bo_wt2 size */ log_t *prob3; /* table of actual trigram probs */ int32 n_prob3; /* prob3 size */ int32 *tseg_base; /* tseg_base[i>>LOG_BG_SEG_SZ] = index of 1st trigram for bigram segment (i>>LOG_BG_SEG_SZ) */ int32 *dictwid_map; /* lexicon word-id to ILM word-id map */ int32 max_ucount; /* To which ucount can grow with dynamic addition of words */ int32 ucount; /* #unigrams in LM */ int32 bcount; /* #bigrams in entire LM */ int32 tcount; /* #trigrams in entire LM */ int32 dict_size; /* #words in lexicon */ double lw; /* language weight */ double invlw; /* 1.0/language weight */ double uw; /* unigram weight */ int32 log_wip; /* word insertion penalty */ tginfo_t **tginfo; /* tginfo[lw2] is head of linked list of trigram information for some cached subset of bigrams (*,lw2). */ hash_t HT; /* hash table for word-string->word-id map */ } lm_t, *LM; #define UG_WID(m,u) ((m)->unigrams[u].wid) #define UG_PROB_F(m,u) ((m)->unigrams[u].prob1.f) #define UG_BO_WT_F(m,u) ((m)->unigrams[u].bo_wt1.f) #define UG_PROB_L(m,u) ((m)->unigrams[u].prob1.l) #define UG_BO_WT_L(m,u) ((m)->unigrams[u].bo_wt1.l) #define FIRST_BG(m,u) ((m)->unigrams[u].bigrams) #define LAST_BG(m,u) (FIRST_BG((m),(u)+1)-1) #define DICT2LM_WID(m,d) ((m)->dictwid_map[d]) #define BG_WID(m,b) ((m)->bigrams[b].wid) #define BG_PROB_F(m,b) ((m)->prob2[(m)->bigrams[b].prob2].f) #define BG_BO_WT_F(m,b) ((m)->bo_wt2[(m)->bigrams[b].bo_wt2].f) #define BG_PROB_L(m,b) ((m)->prob2[(m)->bigrams[b].prob2].l) #define BG_BO_WT_L(m,b) ((m)->bo_wt2[(m)->bigrams[b].bo_wt2].l) #define TSEG_BASE(m,b) ((m)->tseg_base[(b)>>LOG_BG_SEG_SZ]) #define FIRST_TG(m,b) (TSEG_BASE((m),(b))+((m)->bigrams[b].trigrams)) #define LAST_TG(m,b) (FIRST_TG((m),(b)+1)-1) #define TG_WID(m,t) ((m)->trigrams[t].wid) #define TG_PROB_F(m,t) ((m)->prob3[(m)->trigrams[t].prob3].f) #define TG_PROB_L(m,t) ((m)->prob3[(m)->trigrams[t].prob3].l) #define ILLEGAL_WID 65535 /* ----Interface---- */ void lmSetStartSym (/* char *sym */); void lmSetEndSym (/* char *sym */); lm_t * NewModel (/* int32 n_ug, n_bg, n_tg, n_dict */); int32 lm_add_word (lm_t *model, int32 dictwid); void lm_add (/* char *name, lm_t *model, double lw, double uw, double wip */); int32 lm_set_current (char *name); lm_t * lm_get_current (); char * get_current_lmname (); lm_t * lm_name2lm (char *name); int32 get_n_lm (); int32 dictwd_in_lm (/* int32 wid */); int32 lm3g_tg_score (int32 w1, int32 w2, int32 w3); int32 lm3g_bg_score (int32 w1, int32 w2); int32 lm3g_ug_score (int32 w); int32 lm3g_raw_score (int32 score); void lm3g_cache_reset (); void lm3g_cache_stats_dump (); void lm_next_frame (); #endif /* _LM_3G_H_ */ <file_sep>/SphinxTrain/src/programs/make_quests/new_quest.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * $Log$ * Revision 1.6 2005/07/09 03:13:03 arthchan2003 * Fix keyword expansion probelm * * * Revision 1.5 2005/07/09 02:31:47 arthchan2003 * * 1, When user forgot to specify -type, make_quest.c failed to check whether type is valid, when passed as an argument to strcpy, strcpy will cause seg core. Resolved it by explicitly adding a checking and prompting user to specify it correctly. 2, Also added keyword for all .c files. * */ #include <math.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define MINVAR 1e-08 int32 findclosestpair(float32**,float32**,float32*,int32, int32,int32*,int32*); float32 likelhddec(float32*,float32*,float32*,float32*,float32,float32,int32); int compare(); typedef struct node_str {int32 nphones; int32 *phoneids; struct node_str *left; struct node_str *right; } node; int make_tree (float32 **means, float32 **vars, float32 *mixw, int32 *nodephoneids, int32 nphones, int32 ndim, node *root, int32 npermute) { float32 **oldmeans, **oldvars, **newmeans, **newvars; float32 *oldmixw, *newmixw, **tmp2d, *tmp1d; float32 *meana, *vara, *meanb, *varb; float32 cnt, counta, countb, bestdec, reduction; int32 **phoneid, **newphoneid, *numphones, *newnumphones, **it2d, *it1d; int32 i,j,k,l,a,b,set,nsets,ncombinations,bestclust=0; char **identifier, *tmpid; node *left, *right; oldmixw = (float32 *) ckd_calloc(nphones,sizeof(float32)); oldmeans = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); oldvars = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); phoneid = (int32 **)ckd_calloc_2d(nphones,nphones,sizeof(int32)); numphones = (int32 *) ckd_calloc(nphones,sizeof(int32)); newmixw = (float32 *) ckd_calloc(nphones,sizeof(float32)); newmeans = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); newvars = (float32 **) ckd_calloc_2d(nphones,ndim,sizeof(float32)); newphoneid = (int32 **)ckd_calloc_2d(nphones,nphones,sizeof(int32)); newnumphones = (int32 *) ckd_calloc(nphones,sizeof(int32)); for (i=0;i<nphones;i++){ numphones[i] = 1; phoneid[i][0] = nodephoneids[i]; //Phone ids oldmixw[i] = mixw[nodephoneids[i]]; for (l=0;l<ndim;l++){ oldmeans[i][l] = means[nodephoneids[i]][l]; oldvars[i][l] = vars[nodephoneids[i]][l]; } } if (nphones > npermute){ for (nsets = nphones; nsets > npermute; nsets--) { // Find the closest distributions findclosestpair(oldmeans,oldvars,oldmixw,nsets,ndim,&a,&b); // printf("Merging %s %s\n",phoneid[a],phoneid[b]); fflush(stdout); // Copy and Merge distributions... // Copy unmerged distributions first for (i=0,set=0;i<nsets;i++){ if (i != a && i != b){ newnumphones[set] = numphones[i]; for (l=0;l<numphones[i];l++) newphoneid[set][l] = phoneid[i][l]; newmixw[set] = oldmixw[i]; for (l=0;l<ndim;l++){ newmeans[set][l] = oldmeans[i][l]; newvars[set][l] = oldvars[i][l]; } set++; } } // Merge a and b newnumphones[set] = numphones[a]+numphones[b]; for (i=0;i<numphones[a];i++) newphoneid[set][i] = phoneid[a][i]; for (l=0;l<numphones[b];l++,i++) newphoneid[set][i] = phoneid[b][l]; { float32 *nm = newmeans[set]; float32 *nv = newvars[set]; float32 *oma = oldmeans[a]; float32 *ova = oldvars[a]; float32 *omb = oldmeans[b]; float32 *ovb = oldvars[b]; float32 cnta, cntb; cnta = oldmixw[a]; cntb = oldmixw[b]; newmixw[set] = cnta + cntb; for (l=0;l<ndim;l++){ nm[l] = (cnta*oma[l] + cntb*omb[l]) / (cnta + cntb); nv[l] = cnta*(ova[l]+oma[l]*oma[l]) + cntb*(ovb[l]+omb[l]*omb[l]); nv[l] = nv[l]/(cnta+cntb) - nm[l]*nm[l]; if (nv[l] < MINVAR) nv[l] = MINVAR; } } // Switch old and new variables tmp2d = oldmeans; oldmeans = newmeans; newmeans = tmp2d; tmp2d = oldvars; oldvars = newvars; newvars = tmp2d; tmp1d = oldmixw; oldmixw = newmixw; newmixw = tmp1d; it2d = phoneid; phoneid = newphoneid; newphoneid = it2d; it1d = numphones; numphones = newnumphones; newnumphones = it1d; } } else npermute = nphones; if (npermute <= 2){ root->left = root->right = NULL; /* Dont split further */ return 0; } // We have npermute clusters now; permute them to get two clusters // There are 2^(npermute-1)-1 clusters possible. Test them all out. // Create identifiers for 2^(npermute-1) clusters for (i=1,ncombinations=1;i<npermute;i++,ncombinations*=2); identifier = (char **)ckd_calloc_2d(ncombinations,npermute,sizeof(char)); tmpid = (char *)ckd_calloc(npermute,sizeof(char)); for (i=0;i<ncombinations-1;i++){ for(j=0,tmpid[0]=!tmpid[0];!tmpid[j];j++,tmpid[j]=!tmpid[j]); for(j=0;j<npermute;j++) identifier[i][j] = tmpid[j]; } ckd_free(tmpid); // Go through the list and find best pair for (i=0,bestdec=-1.0e+30;i<ncombinations-1;i++){ meana = (float32 *)ckd_calloc(ndim,sizeof(float32)); vara = (float32 *)ckd_calloc(ndim,sizeof(float32)); meanb = (float32 *)ckd_calloc(ndim,sizeof(float32)); varb = (float32 *)ckd_calloc(ndim,sizeof(float32)); counta = countb = 0; for (j=0;j<npermute;j++){ float32 *om = oldmeans[j]; float32 *ov = oldvars[j]; cnt = oldmixw[j]; if (identifier[i][j]){ counta += cnt; for (k=0;k<ndim;k++){ meana[k] += cnt * om[k]; vara[k] += cnt*(ov[k] + om[k]*om[k]); } } else{ countb += cnt; for (k=0;k<ndim;k++){ meanb[k] += cnt * om[k]; varb[k] += cnt*(ov[k] + om[k]*om[k]); } } } for (k=0;k<ndim;k++){ meana[k] /= counta; meanb[k] /= countb; vara[k] = vara[k]/counta - meana[k]*meana[k]; varb[k] = varb[k]/countb - meanb[k]*meanb[k]; } reduction = likelhddec(meana,vara, meanb,varb,counta,countb,ndim); if (reduction > bestdec) { bestdec = reduction; bestclust = i; } ckd_free(meana);ckd_free(vara);ckd_free(meanb);ckd_free(varb); } // Now we know what the best separation is, set the appropriate left // and right trees. left = (node *) ckd_calloc(1,sizeof(node)); right = (node *) ckd_calloc(1,sizeof(node)); root->left = left; root->right = right; left->phoneids = (int32 *) ckd_calloc(nphones,sizeof(int32)); //Overalloc right->phoneids = (int32 *) ckd_calloc(nphones,sizeof(int32)); for (j=0;j<npermute;j++){ if (identifier[bestclust][j]){ for (l=0;l<numphones[j];l++,left->nphones++) left->phoneids[left->nphones] = phoneid[j][l]; } else { for (l=0;l<numphones[j];l++,right->nphones++) right->phoneids[right->nphones] = phoneid[j][l]; } } ckd_free_2d((void **)identifier); ckd_free_3d((void ***)oldmeans); ckd_free_3d((void ***)oldvars); ckd_free_3d((void ***)newmeans); ckd_free_3d((void ***)newvars); ckd_free_2d((void **)oldmixw); ckd_free_2d((void **)newmixw); ckd_free_2d((void **)newphoneid); ckd_free_2d((void **)phoneid); // Recurse make_tree(means,vars,mixw,left->phoneids,left->nphones,ndim, left,npermute); make_tree(means,vars,mixw,right->phoneids,right->nphones,ndim, right,npermute); return 0; } /* Find the two closest distributions. We assume 1 gaussian/state */ int32 findclosestpair(float32 **pmeans, float32 **pvars, float32 *pmixw, int32 nsets, int32 dim, int *a, int32 *b) { float32 reduction, minreduction; int32 i, j, la=0, lb=0; minreduction = 1.0e+32; for (i=0; i<nsets; i++){ for (j=i+1;j<nsets;j++){ if (i != j){ reduction = likelhddec(pmeans[i],pvars[i], pmeans[j],pvars[j], pmixw[i],pmixw[j], dim); if (reduction < minreduction){ minreduction = reduction; la = i; lb = j; } } } } *a = la; *b = lb; return 0; } float32 likelhddec(float32 *meana, float32 *vara, float32 *meanb, float32 *varb, float32 cnta, float32 cntb, int32 dim) { int32 i; float32 cntc, la, lb, lc, nm, nv, lkdec; cntc = cnta + cntb; for (i=0, lc=0, lb=0, la=0;i<dim;i++){ nm = (cnta*meana[i] + cntb*meanb[i])/(cnta+cntb); nv = cnta*(vara[i]+meana[i]*meana[i])+cntb*(varb[i]+meanb[i]*meanb[i]); nv = nv/(cnta+cntb) - nm*nm; if (nv < MINVAR) nv = MINVAR; lc += (float32)log(nv); lb += (float32)log(varb[i]); la += (float32)log(vara[i]); } lkdec = 0.5*(cntc*lc - cntb*lb - cnta*la); return(lkdec); } void free_tree(node *root) { if (root->left != NULL) free_tree(root->left); if (root->right != NULL) free_tree(root->right); ckd_free((void *) root->phoneids); ckd_free((void *) root); return; } void print_tree(node *root, char **phonelist, char *outfile) { FILE *fp; int32 *sortedidx,i; if (root->nphones < 2) return; if (root->left != NULL) print_tree(root->left, phonelist, outfile); if (root->right != NULL) print_tree(root->right, phonelist, outfile); fp = fopen(outfile,"a"); sortedidx = (int32 *)ckd_calloc(root->nphones,sizeof(int32)); qsort(sortedidx,root->nphones,sizeof(int32),compare); for (i=0;i<root->nphones;i++) sortedidx[i] = root->phoneids[i]; for (i=0;i<root->nphones;i++) fprintf(fp," %s",phonelist[sortedidx[i]]); fprintf(fp,"\n"); fclose(fp); ckd_free((void *)sortedidx); return; } int compare(int *i, int *j) { if (*i > *j) return -1; if (*j > *i) return 1; return 0; } <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/corpus/xml/CorpusXMLJavalutionFormats.java package edu.cmu.sphinx.tools.corpus.xml; import edu.cmu.sphinx.tools.corpus.*; import javolution.xml.ObjectReader; import javolution.xml.ObjectWriter; import javolution.xml.XmlElement; import javolution.xml.XmlFormat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.HashMap; //import com.sun.corba.se.impl.orbutil.ObjectWriter; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Apr 2, 2006 * Time: 9:07:05 PM */ public class CorpusXMLJavalutionFormats { static void write(Corpus corpus, OutputStream out) throws IOException { ObjectWriter<Corpus> ow = new ObjectWriter<Corpus>(); ow.write(corpus,out); } static Corpus read(InputStream in) { Corpus c = new ObjectReader<Corpus>().read(in); return c; } static final XmlFormat<Corpus> CorpusXMLFormat = new XmlFormat<Corpus>(Corpus.class) { public void format(Corpus c, XmlElement xml) { xml.add(c.getDictionary(), "dictionary"); xml.add(c.getUtterances(), "utterances"); xml.add(c.getProperties(), "properties"); } public Corpus parse(XmlElement xml) { Corpus c = xml.object(); c.setDictionary((Dictionary) xml.get("dictionary")); c.setProperties((HashMap<String,String>) xml.get("properties")); c.setUtterances((List<Utterance>) xml.get("utterances")); return c; } }; static final XmlFormat<Dictionary> DictionaryXMLFormat = new XmlFormat<Dictionary>(Dictionary.class) { public void format(Dictionary d, XmlElement xml) { xml.add("dictionaryFile", d.getDictionaryFile()); } public Dictionary parse(XmlElement xml) { Dictionary d = xml.object(); d.setDictionaryFile((String)xml.get("dictionaryFile")); return d; } }; static final XmlFormat<Utterance> UtteranceXMLFormat = new XmlFormat<Utterance>(Utterance.class) { public void format(Utterance u, XmlElement xml) { xml.setAttribute("transcript", u.getTranscript()); xml.add( u.getRegionOfAudioData(), "regionOfAudioData"); xml.add(u.getWords(), "words"); } public Utterance parse(XmlElement xml) { Utterance u = xml.object(); u.setTranscript( xml.getAttribute("transcript", "") ); u.setRegionOfAudioData( (RegionOfAudioData) xml.get("regionOfAudioData")); u.addWords( (List<Word>) xml.get("words") ); return u; } }; static final XmlFormat<RegionOfAudioData> RegionOfAudioDataXMLFormat = new XmlFormat<RegionOfAudioData>(RegionOfAudioData.class) { public void format(RegionOfAudioData r, XmlElement xml) { xml.setAttribute("beginTime", r.getBeginTime()); xml.setAttribute("endTime", r.getEndTime()); xml.setAttribute("isExcluded", r.isExcluded()); xml.add(r.getNotes(), "notes"); xml.add(r.getAudioDatabase(), "audioDatabase"); } public RegionOfAudioData parse(XmlElement xml) { RegionOfAudioData r = xml.object(); r.setBeginTime(xml.getAttribute("beginTime", -1)); r.setEndTime(xml.getAttribute("endTime", -1)); r.setExcluded(xml.getAttribute("isExcluded", false)); r.setNotes((Collection<Note>) xml.get("notes")); r.setAudioDatabase((AudioDatabase) xml.get("audioDatabase")); return r; } }; static final XmlFormat<Note> NoteXMLFormat = new XmlFormat<Note>(Note.class) { public void format(Note n, XmlElement xml) { xml.setAttribute("beginTime", n.getBeginTime()); xml.setAttribute("endTime", n.getEndTime()); xml.setAttribute("text", n.getText()); } public Note parse(XmlElement xml) { Note n = xml.object(); n.setBeginTime(xml.getAttribute("beginTime", -1)); n.setEndTime(xml.getAttribute("endTime", -1)); n.setText(xml.getAttribute("text", "")); return n; } }; static final XmlFormat<Word> WordXMLFormat = new XmlFormat<Word>(Word.class) { public void format(Word w, XmlElement xml) { xml.setAttribute("spelling", w.getSpelling()); xml.add( w.getRegionOfAudioData(), "regionOfAudioData"); } public Word parse(XmlElement xml) { Word w = xml.object(); w.setSpelling( xml.getAttribute("spelling", "") ); w.setRegionOfAudioData( (RegionOfAudioData) xml.get("regionOfAudioData") ); return w; } }; static final XmlFormat<AudioDatabase> MandarinAudioDatabaseXMLFormat = new XmlFormat<AudioDatabase>(AudioDatabase.class) { public void format(AudioDatabase adb, XmlElement xml) { xml.add(adb.getPcm(),"pcm"); xml.add(adb.getPitch(),"pitch"); xml.add(adb.getEnergy(),"energy"); } public AudioDatabase parse(XmlElement xml) { AudioDatabase adb = xml.object(); adb.setPcm((PCMAudioFile) xml.get("pcm")); adb.setPitch((TextFileOfDoubles) xml.get("pitch")); adb.setEnergy((TextFileOfDoubles) xml.get("energy")); return adb; } }; static final XmlFormat<PCMAudioFile> PCMAudioFileXMLFormat = new XmlFormat<PCMAudioFile>(PCMAudioFile.class) { public void format(PCMAudioFile adb, XmlElement xml) { xml.setAttribute("pcmFile", adb.getPcmFile()); xml.setAttribute("bitsPerSample", adb.getBitsPerSample()); xml.setAttribute("samplesPerSecond", adb.getSamplesPerSecond()); xml.setAttribute("channelCount", adb.getChannelCount()); } public PCMAudioFile parse(XmlElement xml) { PCMAudioFile paf = new PCMAudioFile(); paf.setPcmFile( xml.getAttribute("pcmFile","")); paf.setBitsPerSample( xml.getAttribute("bitsPerSample",-1)); paf.setSamplesPerSecond( xml.getAttribute("samplesPerSecond",-1)); paf.setChannelCount( xml.getAttribute("channelCount",-1)); return paf; } }; static final XmlFormat<TextFileOfDoubles> TextFileOfDoublesXMLFormat = new XmlFormat<TextFileOfDoubles>(TextFileOfDoubles.class) { public void format(TextFileOfDoubles adb, XmlElement xml) { xml.setAttribute("textFile", adb.getTextFile()); } public TextFileOfDoubles parse(XmlElement xml) { TextFileOfDoubles tf = new TextFileOfDoubles(); tf.setTextFile( xml.getAttribute("textFile","")); return tf; } }; } <file_sep>/archive_s3/s3/src/libfbs/senone.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * senone.h -- Mixture density weights associated with each tied state. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * $Log$ * Revision 1.2 2002/12/03 23:02:44 egouvea * Updated slow decoder with current working version. * Added copyright notice to Makefiles, *.c and *.h files. * Updated some of the documentation. * * Revision 1.1.1.1 2002/12/03 20:20:46 robust * Import of s3decode. * * * 13-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added senone_eval_all(). * * 12-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created. */ #ifndef _LIBFBS_SENONE_H_ #define _LIBFBS_SENONE_H_ #include <libutil/prim_type.h> #include <s3.h> #include "s3types.h" #include "gauden.h" typedef uint8 senprob_t; /* Senone logs3-probs, truncated to 8 bits */ /* * 8-bit senone PDF structure. Senone pdf values are normalized, floored, converted to * logs3 domain, and finally truncated to 8 bits precision to conserve memory space. */ typedef struct { senprob_t ***pdf; /* gaussian density mixture weights, organized two possible ways depending on n_gauden: if (n_gauden > 1): pdf[sen][feat][codeword]. Not an efficient representation--memory access-wise--but evaluating the many codebooks will be more costly. if (n_gauden == 1): pdf[feat][codeword][sen]. Optimized for the shared-distribution semi-continuous case. */ int32 n_sen; /* #senones in this set */ int32 n_feat; /* #feature streams */ int32 n_cw; /* #codewords per codebook,stream */ int32 n_gauden; /* #gaussian density codebooks referred to by senones */ float32 mixwfloor; /* floor applied to each PDF entry */ int32 shift; /* LSB bits truncated from original logs3 value */ s3mgauid_t *mgau; /* senone-id -> mgau-id mapping for senones in this set */ } senone_t; /* * Load a set of senones (mixing weights and mixture gaussian codebook mappings) from * the given files. Normalize weights for each codebook, apply the given floor, convert * PDF values to logs3 domain and quantize to 8-bits. * Return value: pointer to senone structure created. Caller MUST NOT change its contents. */ senone_t *senone_init (char *mixwfile, /* In: mixing weights file */ char *mgau_mapfile, /* In: file specifying mapping from each senone to mixture gaussian codebook. If NULL all senones map to codebook 0 */ float32 mixwfloor); /* In: Floor value for senone weights */ /* * Evaluate the score for the given senone wrt to the given top N gaussian codewords. * Return value: senone score (in logs3 domain). */ int32 senone_eval (senone_t *s, s3senid_t id, /* In: senone for which score desired */ gauden_dist_t **dist, /* In: top N codewords and densities for all features, to be combined into senone score. IE, dist[f][i] = i-th best <codeword,density> for feaure f */ int32 n_top); /* In: Length of dist[f], for each f */ /* * Like senone_eval, but compute all senone scores for the shared density case (ie, * #codebooks = 1). */ void senone_eval_all (senone_t *s, /* In: Senone structure */ gauden_dist_t **dist, /* In: as in senone_eval above */ int32 n_top, /* In: as in senone_eval above */ int32 *senscr); /* Out: Upon return, senscr[i] will contain score for senone i */ #endif <file_sep>/SphinxTrain/src/programs/bw/next_utt_states.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: next_utt_states.h * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef NEXT_UTT_STATES_H #define NEXT_UTT_STATES_H #include <s3/state.h> #include <s3/prim_type.h> #include <s3/lexicon.h> #include <s3/model_inventory.h> #include <s3/model_def.h> state_t *next_utt_states(uint32 *n_state, lexicon_t *lex, model_inventory_t *inv, model_def_t *mdef, char *transcript, int32 sil_del, char* silence_str); #endif /* NEXT_UTT_STATES_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.6 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.4 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.5 1996/07/29 16:22:02 eht * Mixxing includes * * Revision 1.4 1995/10/12 18:22:18 eht * Updated comments and changed <s3/state.h> to "state.h" * * Revision 1.3 1995/10/10 12:44:06 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/08/09 20:20:10 eht * Use mdef structure for tying info rather than DAG thing * * Revision 1.1 1995/06/02 20:43:56 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/acmod_set.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************** * * File: acmod_set.h * * Description: * This header defines the interface to the acmod_set (acoustic * model set) module. See acmod_set.c for the detailed * descriptions of each function below. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef ACMOD_SET_H #define ACMOD_SET_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/acmod_set_ds.h> /* defines the data structures used by this * module */ #include <s3/prim_type.h> acmod_set_t * acmod_set_new(void); int32 acmod_set_set_n_ci_hint(acmod_set_t *acmod_set, uint32 n_ci_hint); int32 acmod_set_set_n_tri_hint(acmod_set_t *acmod_set, uint32 n_tri_hint); acmod_id_t acmod_set_add_ci(acmod_set_t *acmod_set, const char *name, const char **attrib); acmod_id_t acmod_set_add_tri(acmod_set_t *acmod_set, acmod_id_t base, acmod_id_t left_context, acmod_id_t right_context, word_posn_t posn, const char **attrib); acmod_id_t acmod_set_name2id(acmod_set_t *acmod_set, const char *name); const char * acmod_set_id2name(acmod_set_t *acmod_set, acmod_id_t id); const char * acmod_set_id2fullname(acmod_set_t *acmod_set, acmod_id_t id); const char * acmod_set_id2s2name(acmod_set_t *acmod_set, acmod_id_t id); acmod_id_t acmod_set_enum_init(acmod_set_t *acmod_set, acmod_id_t base); acmod_id_t acmod_set_enum(void); acmod_id_t acmod_set_tri2id(acmod_set_t *acmod_set, acmod_id_t base, acmod_id_t left_context, acmod_id_t right_context, word_posn_t posn); int32 acmod_set_id2tri(acmod_set_t *acmod_set, acmod_id_t *base, acmod_id_t *left_context, acmod_id_t *right_context, word_posn_t *posn, acmod_id_t id); const char * acmod_set_s2_id2name(acmod_set_t *acmod_set, acmod_id_t id); uint32 acmod_set_n_acmod(acmod_set_t *acmod_set); uint32 acmod_set_n_base_acmod(acmod_set_t *acmod_set); uint32 acmod_set_n_multi(acmod_set_t *acmod_set); uint32 acmod_set_n_ci(acmod_set_t *acmod_set); acmod_id_t acmod_set_base_phone(acmod_set_t *acmod_set, acmod_id_t id); uint32 acmod_set_has_attrib(acmod_set_t *acmod_set, acmod_id_t id, const char *attrib); const char ** acmod_set_attrib(acmod_set_t *acmod_set, acmod_id_t id); /* some SPHINX-II compatibility routines */ int acmod_set_s2_parse_triphone(acmod_set_t *acmod_set, acmod_id_t *base, acmod_id_t *left, acmod_id_t *right, word_posn_t *posn, char *str); #ifdef __cplusplus } #endif #endif /* ACMOD_SET_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:08 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.7 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.6 96/03/25 15:46:57 eht * Added acmod_set_id2s2name() to output SPHINX-II triphone names * * Revision 1.5 1996/03/04 15:55:43 eht * Added ability to walk the triphone index trees * * Revision 1.4 1996/01/26 18:29:54 eht * Interface definition was incomplete. * * Revision 1.3 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.2 1995/10/09 20:29:29 eht * Changed "char *" to "const char *" for name2id call. * * Revision 1.1 1995/09/08 19:13:52 eht * Initial revision * * Revision 1.1 95/08/15 13:44:14 13:44:14 eht (<NAME>) * Initial revision * * */ <file_sep>/tools/dictator/src/java/edu/cmu/sphinx/tools/dictator/ClipboardControls.java package edu.cmu.sphinx.tools.dictator; import java.awt.*; import java.awt.datatransfer.*; import java.io.IOException; /** * Copyright 1999-2006 Carnegie Mellon University. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Apr 30, 2006 * Time: 9:02:48 AM */ public class ClipboardControls implements ClipboardOwner { /** * Empty implementation of the ClipboardOwner interface. */ public void lostOwnership(Clipboard aClipboard, Transferable aContents) { //do nothing } /** * Place a String on the clipboard, and make this class the * owner of the Clipboard's contents. */ public void setClipboardContents(String aString) { StringSelection stringSelection = new StringSelection(aString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); } /** * Get the String residing on the clipboard. * * @return any text found on the Clipboard; if none found, return an * empty String. */ public String getClipboardContents() { String result = ""; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents(null); boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if (hasTransferableText) { try { result = (String) contents.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException ex) { //highly unlikely since we are using a standard DataFlavor System.out.println(ex); ex.printStackTrace(); } catch (IOException ex) { System.out.println(ex); ex.printStackTrace(); } } return result; } } <file_sep>/archive_s3/s3.0/pgm/misc/cepdx.c /* * cepdx.c -- Differentiate a cepstrum vector stream. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 29-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libfeat/libfeat.h> #include <s3.h> static int32 cepsize; static char uttid[4096]; static float32 *var; /* Feature dimension variances */ static float64 varscale; typedef struct { char p[16]; int32 sf, nf; } pseg_t; static pseg_t *pseg; static int32 n_pseg; static void load_pseg (char *line) { char *lp, wd[1024]; int32 k, len, sf, nf; n_pseg = 0; lp = line; while ((k = sscanf (lp, "%s %d %d%n", wd, &sf, &nf, &len)) == 3) { lp += len; strcpy (pseg[n_pseg].p, wd); pseg[n_pseg].sf = sf; pseg[n_pseg].nf = nf; n_pseg++; } assert (k == 1); assert (wd[0] == '('); k = strlen(wd); assert (wd[k-1] == ')'); wd[k-1] = '\0'; strcpy (uttid, wd+1); } static float64 eucl_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = f1[i] - f2[i]; dist += d*d; } return sqrt(dist); } static float64 maha_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = (f1[i] - f2[i]); dist += d*d / var[i]; } return sqrt(dist); } static void compute_var (float32 **mfc, int32 nfr) { float32 *sum, *mean; int32 i, j; sum = (float32 *) ckd_calloc (cepsize, sizeof(float32)); mean = (float32 *) ckd_calloc (cepsize, sizeof(float32)); for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += mfc[i][j]; } for (i = 0; i < cepsize; i++) mean[i] = sum[i]/(float64)nfr; for (i = 0; i < cepsize; i++) sum[i] = 0.0; for (i = 0; i < nfr; i++) { for (j = 0; j < cepsize; j++) sum[j] += (mfc[i][j] - mean[j]) * (mfc[i][j] - mean[j]); } for (i = 0; i < cepsize; i++) var[i] = sum[i]/(float64)nfr; /* Hack!! Scale variances */ for (i = 0; i < cepsize; i++) fprintf (stderr, " %.3f", var[i]); fprintf (stderr, "\n"); for (i = 0; i < cepsize; i++) var[i] *= (1.0 + (float64)(i*varscale)/(float64)cepsize); for (i = 0; i < cepsize; i++) fprintf (stderr, " %.3f", var[i]); fprintf (stderr, "\n"); fflush (stderr); ckd_free (sum); ckd_free (mean); } static void dx (float32 **mfc, int32 nfr) { int32 i, k, p; float64 *d, maxd; d = (float64 *) ckd_calloc (S3_MAX_FRAMES, sizeof(float64)); maxd = 0.0; for (i = 0; i < nfr-1; i++) { d[i] = maha_dist (mfc[i+1], mfc[i], cepsize); if (d[i] > maxd) maxd = d[i]; } p = 0; for (i = 0; i < nfr-1; i++) { d[i] = (d[i]*10.0)/maxd; assert (pseg[p].sf <= i); if (pseg[p].sf + pseg[p].nf <= i) p++; assert (p < n_pseg); assert (pseg[p].sf <= i); assert (pseg[p].sf + pseg[p].nf > i); printf ("%s %4d %5.2f %10s ", uttid, i, d[i], pseg[p].p); k = d[i]*5.0 + 0.5; for (; k > 0; --k) printf ("."); printf ("\n"); } fflush (stdout); ckd_free (d); } static void process_psegfile (char *cepdir, char *psegfile) { char cepfile[4096], line[16384]; int32 nfr; float32 **mfc; FILE *fp; if ((fp = fopen(psegfile, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", psegfile); for (;;) { if (fgets (line, sizeof(line), fp) == NULL) break; fprintf (stderr, "%s", line); fflush (stderr); load_pseg (line); sprintf (cepfile, "%s/%s.mfc", cepdir, uttid); if ((nfr = s2mfc_read (cepfile, 0, (int32)0x70000000, 0, &mfc)) <= 0) E_FATAL("MFC file read (%s) failed\n", cepfile); E_INFO("%s: %d frames\n", cepfile, nfr); compute_var (mfc, nfr); #if 0 fprintf (stderr, "ready? "); fgets (line, sizeof(line), stdin); #endif dx (mfc, nfr); } fclose (fp); } main (int32 argc, char *argv[]) { char *cepdir, *psegfile; if (argc != 4) E_FATAL("Usage: %s varscale cepdir psegfile\n", argv[0]); if (sscanf (argv[1], "%lf", &varscale) != 1) E_FATAL("Usage: %s varscale cepdir psegfile\n", argv[0]); cepdir = argv[2]; psegfile = argv[3]; feat_init ("s3_1x39"); cepsize = feat_cepsize (); var = (float32 *) ckd_calloc (cepsize, sizeof(float32)); pseg = (pseg_t *) ckd_calloc (S3_MAX_FRAMES, sizeof(pseg_t)); process_psegfile (cepdir, psegfile); exit(0); } <file_sep>/archive_s3/s3.3/src/tests/rm1/Makefile # ==================================================================== # Copyright (c) 2000 <NAME> University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Sphinx III # # ==================================================================== TOP=../../.. DIRNAME=src/tests/rm1 BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) MAINSRCS = dump_frontend.c batch_metrics.c LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile $(SRCS) $(H) LIBNAME= tests LOCAL_INCLUDES = -I$(TOP)/src -I$(TOP)/src/libs3decoder -I$(TOP)/src/libs3audio ifeq ($(MODE),quick) MODEAFFIX = _quick CTLFILE = rm1_quick.ctl REFFILE = rm1_quick.ref else MODE = CTLFILE = rm1.ctl REFFILE = rm1.ref endif ALL = $(BINDIR)/dumpfrontend $(BINDIR)/batchmetrics include $(TOP)/config/common_make_rules $(BINDIR)/dumpfrontend: dump_frontend.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ dump_frontend.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) $(BINDIR)/batchmetrics: batch_metrics.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ batch_metrics.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) rm1_flat_unigram: rm -f gmake-rm1_flat_unigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-lm RM.unigram.arpa.DMP" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-lw 7" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-beam 1e-140" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-wbeam 1e-80" >> ARGS.rm1_flat_unigram$(MODEAFFIX) /bin/echo "-ctl $(CTLFILE)" >> ARGS.rm1_flat_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./rm1$(MODEAFFIX).batch / ./ARGS.rm1_flat_unigram$(MODEAFFIX) > gmake-rm1_flat_unigram$(MODEAFFIX).results rm1_unigram: rm -f gmake-rm1_unigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-lm RM.2845.unigram.arpa.DMP" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-lw 10" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-beam 1e-120" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-wbeam 1e-60" >> ARGS.rm1_unigram$(MODEAFFIX) /bin/echo "-ctl $(CTLFILE)" >> ARGS.rm1_unigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./rm1$(MODEAFFIX).batch / ./ARGS.rm1_unigram$(MODEAFFIX) > gmake-rm1_unigram$(MODEAFFIX).results rm1_bigram: rm -f gmake-rm1_bigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-lm RM.2845.bigram.arpa.DMP" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-lw 13" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-beam 1e-120" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-wbeam 1e-100" >> ARGS.rm1_bigram$(MODEAFFIX) /bin/echo "-ctl $(CTLFILE)" >> ARGS.rm1_bigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./rm1$(MODEAFFIX).batch / ./ARGS.rm1_bigram$(MODEAFFIX) > gmake-rm1_bigram$(MODEAFFIX).results rm1_trigram: rm -f gmake-rm1_trigram$(MODEAFFIX).results /bin/cp ARGS.rm1 ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-lm RM.2845.trigram.arpa.DMP" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-lw 14" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-beam 1e-140" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-wbeam 1e-100" >> ARGS.rm1_trigram$(MODEAFFIX) /bin/echo "-ctl $(CTLFILE)" >> ARGS.rm1_trigram$(MODEAFFIX) $(BINDIR)/batchmetrics ./rm1$(MODEAFFIX).batch / ./ARGS.rm1_trigram$(MODEAFFIX) > gmake-rm1_trigram$(MODEAFFIX).results <file_sep>/archive_s3/s3/src/programs/main_live_pretend.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /******************************************************************** * Example program to show usage of the live mode routines * The decoder is initialized with live_initialize_decoder() * Blocks of samples are decoded by live_utt_decode_block() * To compile an excutable compile using * $(CC) -I. -Isrc -Llibutil/linux -Lsrc/linux main_live_example.c -lutil -ldecoder -lm * from the current directory * Note the include directories (-I*) and the library directories (-L*) * ********************************************************************/ #include <stdio.h> #include <libutil/libutil.h> #include "live.h" #define MAXSAMPLES 1000000 int main (int argc, char *argv[]) { short *samps; int i, j, buflen, endutt, blksize, nhypwds, nsamp; char *argsfile, *ctlfile, *indir; char filename[512], cepfile[512]; partialhyp_t *parthyp; FILE *fp, *sfp; if (argc != 4) E_FATAL("\nUSAGE: %s <ctlfile> <inrawdir> <argsfile>\n",argv[0]); ctlfile = argv[1]; indir = argv[2]; argsfile = argv[3]; samps = (short *) calloc(MAXSAMPLES,sizeof(short)); blksize = 2000; if ((fp = fopen(ctlfile,"r")) == NULL) E_FATAL("Unable to read %s\n",ctlfile); live_initialize_decoder(argsfile); while (fscanf(fp,"%s",filename) != EOF){ sprintf(cepfile,"%s/%s.raw",indir,filename); if ((sfp = fopen(cepfile,"rb")) == NULL) E_FATAL("Unable to read %s\n",cepfile); nsamp = fread(samps, sizeof(short), MAXSAMPLES, sfp); fprintf(stdout,"%d samples in file %s.\nWill be decoded in blocks of %d\n",nsamp,cepfile,blksize); fflush(stdout); fclose(sfp); for (i=0;i<nsamp;i+=blksize){ buflen = i+blksize < nsamp ? blksize : nsamp-i; endutt = i+blksize <= nsamp-1 ? 0 : 1; nhypwds = live_utt_decode_block(samps+i,buflen,endutt,&parthyp); E_INFO("PARTIAL HYP:"); if (nhypwds > 0) for (j=0; j < nhypwds; j++) fprintf(stderr," %s",parthyp[j].word); fprintf(stderr,"\n"); } } return 0; } <file_sep>/SphinxTrain/src/programs/kdtree/main.c /* ==================================================================== * Copyright (c) 2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * Main program for kdtree(1) * * Author: * <NAME> <<EMAIL>> *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/common.h> #include <s3/s3gau_io.h> #include <s3/kdtree.h> #include <stdio.h> #include <math.h> #include <string.h> int main(int argc, char *argv[]) { const char *meanfn, *varfn; vector_t ***means, ***variances; uint32 n_mgau, n_feat, n_density; uint32 r_n_mgau, r_n_feat, r_n_density; const uint32 *veclen, *r_veclen; uint32 i; kd_tree_node_t **root; parse_cmd_ln(argc, argv); meanfn = cmd_ln_access("-meanfn"); varfn = cmd_ln_access("-varfn"); if (meanfn == NULL || varfn == NULL) E_FATAL("You must specify -meanfn and -varfn\n"); if (s3gau_read(meanfn, &means, &n_mgau, &n_feat, &n_density, &veclen) != S3_SUCCESS) E_FATAL("Failed to read means from %s\n", meanfn); if (s3gau_read(varfn, &variances, &r_n_mgau, &r_n_feat, &r_n_density, &r_veclen) != S3_SUCCESS) E_FATAL("Failed to read variances from %s\n", varfn); if (n_mgau != r_n_mgau) E_FATAL("Number of GMMs in variances doesn't match means: %d != %d\n", r_n_mgau, n_mgau); if (n_mgau != 1) E_FATAL("Only semi-continuous models are currently supported\n"); if (n_density != r_n_density) E_FATAL("Number of Gaussians in variances doesn't match means: %d != %d\n", r_n_density, n_density); if (n_feat != r_n_feat) E_FATAL("Number of feature streams in variances doesn't match means: %d != %d\n", r_n_feat, n_feat); for (i = 0; i < n_feat; ++i) if (veclen[i] != r_veclen[i]) E_FATAL("Size of feature stream %d in variances doesn't match means: %d != %d\n", i, r_veclen[i], veclen[i]); /* Build one kd-tree for each feature stream. */ root = ckd_calloc(n_feat, sizeof(*root)); for (i = 0; i < n_feat; ++i) { root[i] = build_kd_tree(means[0][i], variances[0][i], n_density, veclen[i], cmd_ln_float32("-threshold"), cmd_ln_int32("-depth"), cmd_ln_int32("-absolute")); } if (cmd_ln_access("-outfn")) write_kd_trees(cmd_ln_access("-outfn"), root, n_feat); for (i = 0; i < n_feat; ++i) free_kd_tree(root[i]); ckd_free(root); return 0; } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/propedit/CellSpecificRenderTable.java package edu.cmu.sphinx.tools.confdesigner.propedit; import javax.swing.*; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * DOCUMENT ME! * * @author <NAME> */ class CellSpecificRenderTable extends JTable { private SimplePropEditor simplePropEditor; public CellSpecificRenderTable(SimplePropEditor simplePropEditor, EditorTableModel tableModel) { super(tableModel); this.simplePropEditor = simplePropEditor; } public TableCellRenderer getCellRenderer(int row, int column) { TableProperty tableProperty = simplePropEditor.getProperty(row); if (row >= 0 && column >= 0) { if (column == 0) { return tableProperty.getPropNameRenderer(); } else { return tableProperty.getValueRenderer(); } } else { super.getCellRenderer(row, column); } return null; } public TableCellEditor getCellEditor(int row, int column) { assert column == 1; return simplePropEditor.getProperty(row).getValueEditor(); } } <file_sep>/SphinxTrain/include/sys_compat/posixsock.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * posixsock.h * * <NAME> Speech Group Carnegie Mellon University 5-Mar-95 An include file to hide posix socket differences. * $Log$ * Revision 1.4 2004/07/21 17:46:10 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * * 02-May-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added errno handling. * */ #ifndef _POSIXSOCK_H_ #define _POSIXSOCK_H_ #include <sys/socket.h> #include <sys/ioctl.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> /* * Windows NT uses a different socket interface and return values from BSD. * For compatibility and portability, use the following even with BSD. */ #define SOCKET int32 /* Returned by socket/accept */ #define INVALID_SOCKET -1 /* Returned by socket/accept */ #define SOCKET_ERROR -1 /* Returned by most socket operations */ #define SOCKET_ERRNO errno #define SOCKET_WOULDBLOCK EWOULDBLOCK #define SOCKET_IOCTL ioctl #define closesocket close /* To close a SOCKET */ #define BOOL int32 #endif <file_sep>/SphinxTrain/src/programs/init_gau/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * These routines define and parse the command line for init_gau. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/s3.h> #include <sys_compat/misc.h> #include <stdio.h> #include <assert.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: (Copy from Rita's web manual) To initialize the means and variances, global values of \n\ these parameters are first estimated and then copied into appropriate \n\ positions in the parameter files. The global mean is computed using \n\ all the vectors you have in your feature files. This is usually a \n\ very large number, so the job is divided into many parts. At this \n\ stage you tell the Sphinx how many parts you want it to divide this \n\ operation into (depending on the computing facilities you have) and \n\ the Sphinx \"accumulates\" or gathers up the vectors for each part \n\ separately and writes it into an intermediate buffer on your \n\ machine. The executable init_gau is used for this purpose."; const char examplestr[]= "Example:\n\ \n\ init_gau -accumdir accumdir -ctlfn controlfn -part 1 -npart 1 -cepdir cepdir -feat 1s_12c_12d_3p_12dd -ceplen 13 "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition file for the single density HMM's to initialize"}, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied-state-to-codebook mapping file"}, { "-accumdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Where to write mean/var counts"}, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Mean file for variance initialization"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Accumulate for full covariance matrices"}, { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Control file of the training corpus"}, { "-nskip", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of lines to skip in the control file"}, { "-runlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "# of lines to process in the control file (after any skip)"}, { "-part", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Identifies the corpus part number (range 1..NPART)" }, { "-npart", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Partition the corpus into this many equal sized subsets" }, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "All word transcripts for the training corpus (consistent order w/ -ctlfn!)"}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary for the content words"}, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dictionary for the filler words"}, { "-segdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the training corpus state segmentation files."}, { "-segext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "v8_seg", "Extension of the training corpus state segmentation files."}, /* ADDED BY BHIKSHA, 7 JAN 98; SCALE SEGMENTATIONS FOR FEATURE STREAMS OF A DIFFERENT LENGTH THAN CEPSTRA */ { "-scaleseg", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Scale existing segmentation to fit new parameter stream length."}, /* END CHANGES BY BHIKSHA */ { "-cepdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Root directory of the training corpus cepstrum files."}, { "-cepext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_EXTENSION, "Extension of the training corpus cepstrum files."}, { "-silcomp", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "none", "Controls silence compression."}, { "-cmn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "current", "Controls cepstral mean normalization."}, { "-varnorm", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "no", "Controls variance normalization."}, { "-agc", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "max", "Controls automatic gain control."}, { "-feat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_TYPE, "Controls which feature extraction algorithm is used."}, { "-svspec", CMD_LN_STRING, CMD_LN_NO_VALIDATION, NULL, "Split single stream features into subvectors according to this specification."}, { "-ceplen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_CEP_LENGTH, "# of components in cepstrum vector"}, { "-cepwin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "sliding window of features to concatenate (for -feat 1s_c ONLY)"}, { "-ldafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File containing an LDA transformation matrix."}, { "-ldadim", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "29", "# of output dimensions for LDA"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ E_FATAL("Unable to validate command line\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(0); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2004/11/29 01:43:45 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/08/08 04:21:00 arthchan2003 * help and example for init_gau * * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 96/08/06 14:43:02 eht * Added error output * * Revision 1.6 1996/08/06 14:15:34 eht * Create prototype for parse_cmd_ln() * * Revision 1.5 1996/03/25 15:44:11 eht * reformatting * * Revision 1.4 1996/01/26 18:22:07 eht * Add the "-feat" argument * * Revision 1.3 1995/12/14 20:02:49 eht * Added arguments for front end processing (-cmn, -silcomp, -agc) * * Revision 1.2 1995/12/01 20:55:40 eht * interim development version * * Revision 1.1 1995/12/01 17:01:50 eht * Initial revision * * Revision 1.1 1995/10/05 12:54:02 eht * Initial revision * * Revision 1.2 1995/09/07 19:59:50 eht * Include defn for TRUE/FALSE * * Revision 1.1 1995/06/02 20:55:11 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/ddcep_frame.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: ddcep.c * * Description: * * Author: * *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include "ddcep_frame.h" #include "dcep_frame.h" #include <s3/feat.h> uint32 dd_wsize = 1; uint32 d_wsize = 2; void ddcep_frame_set_window_size(uint32 ws) { d_wsize = dcep_frame_short_window_size(); dd_wsize = ws; } uint32 ddcep_frame_window_size() { return dd_wsize; } void ddcep_frame(vector_t ddcep, vector_t power, vector_t mfcc) { int32 d_w; int32 dd_w; int32 mfcc_frame_len; int32 k; float32 d1; float32 d2; mfcc_frame_len = feat_mfcc_len(); /* compute dcep window offset in terms of coefficients */ d_w = d_wsize * mfcc_frame_len; /* compute ddcep window offset in terms of coefficients */ dd_w = dd_wsize * mfcc_frame_len; /* compute 2nd diff of c[0] */ d1 = mfcc[d_w + dd_w] - mfcc[-d_w + dd_w]; /* dcep[0] of dd_wsize frames in future */ d2 = mfcc[d_w - dd_w] - mfcc[-d_w - dd_w]; /* dcep[0] of dd_wsize frames in past */ power[2] = d1 - d2; /* ddcep[0] is third component of power feature */ for (k = 1; k < mfcc_frame_len; k++) { /* compute 2nd diff of mfcc[k] */ /* dcep[k] of dd_wsize frames in future */ d1 = mfcc[k + d_w + dd_w] - mfcc[k - d_w + dd_w]; /* dcep[k] of dd_wsize frames in past */ d2 = mfcc[k + d_w - dd_w] - mfcc[k - d_w - dd_w]; ddcep[k-1] = d1 - d2; } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 1996/01/26 18:04:51 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/feat.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: feat.c * * Description: * Allows a caller to select an acoustic feature set and * dispatches the functions to implement the selected set. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$";*/ #include "s2_feat.h" #include "v1_feat.h" #include "v2_feat.h" #include "v3_feat.h" #include "v4_feat.h" #include "v5_feat.h" #include "v6_feat.h" #include "v7_feat.h" #include "v8_feat.h" #include "cep_frame.h" #include <s3/feat.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/ckd_alloc.h> #include <s3/lda.h> #include <stdio.h> #include <string.h> #include <assert.h> static uint32 fid = FEAT_ID_NONE; static unsigned int mfcc_len = 13; /** * Variables related to LDA/MLLT. */ static struct { float32 ***lda; uint32 n_lda, lda_rows, lda_cols, lda_dim; } lda; /** * Variables related to subvector projection. */ static struct { uint32 *sv_len; int32 **subvecs; float32 *sv_buf; int32 sv_dim; int32 n_sv; } sv; static char *__name2id[] = { "4s_12c_24d_3p_12dd", "1s_12c_12d_3p_12dd", "1s_c_d_dd", "1s_c_d", "1s_c", "1s_c_dd", "1s_d", "1s_dd", "1s_c_d_ld_dd", NULL }; static char *name2id[] = { "c/1..L-1/,d/1..L-1/,c/0/d/0/dd/0/,dd/1..L-1/", "c/1..L-1/d/1..L-1/c/0/d/0/dd/0/dd/1..L-1/", "c/0..L-1/d/0..L-1/dd/0..L-1/", "c/0..L-1/d/0..L-1/", "c/0..L-1/", "c/0..L-1/dd/0..L-1/", "d/0..L-1/", "dd/0..L-1/", NULL }; static feat_conf_t feat_conf[FEAT_ID_MAX+1] = { { s2_feat_set_in_veclen, s2_feat_doc, s2_feat_id, s2_feat_n_stream, s2_feat_blksize, s2_feat_vecsize, s2_feat_compute, s2_feat_print }, /* FEAT_ID_SPHINX_II_STD */ { v1_feat_set_in_veclen, v1_feat_doc, v1_feat_id, v1_feat_n_stream, v1_feat_blksize, v1_feat_vecsize, v1_feat_compute, v1_feat_print }, /* FEAT_ID_V1 */ { v2_feat_set_in_veclen, v2_feat_doc, v2_feat_id, v2_feat_n_stream, v2_feat_blksize, v2_feat_vecsize, v2_feat_compute, v2_feat_print }, /* FEAT_ID_V2: 1s_c_d_dd */ { v3_feat_set_in_veclen, v3_feat_doc, v3_feat_id, v3_feat_n_stream, v3_feat_blksize, v3_feat_vecsize, v3_feat_compute, v3_feat_print }, /* FEAT_ID_V3: 1s_c_d */ { v4_feat_set_in_veclen, v4_feat_doc, v4_feat_id, v4_feat_n_stream, v4_feat_blksize, v4_feat_vecsize, v4_feat_compute, v4_feat_print }, /* FEAT_ID_V4: 1s_c */ { v5_feat_set_in_veclen, v5_feat_doc, v5_feat_id, v5_feat_n_stream, v5_feat_blksize, v5_feat_vecsize, v5_feat_compute, v5_feat_print }, /* FEAT_ID_V5: 1s_c_dd */ { v6_feat_set_in_veclen, v6_feat_doc, v6_feat_id, v6_feat_n_stream, v6_feat_blksize, v6_feat_vecsize, v6_feat_compute, v6_feat_print }, /* FEAT_ID_V5: 1s_d */ { v7_feat_set_in_veclen, v7_feat_doc, v7_feat_id, v7_feat_n_stream, v7_feat_blksize, v7_feat_vecsize, v7_feat_compute, v7_feat_print }, /* FEAT_ID_V5: 1s_dd */ { v8_feat_set_in_veclen, v8_feat_doc, v8_feat_id, v8_feat_n_stream, v8_feat_blksize, v8_feat_vecsize, v8_feat_compute, v8_feat_print } /* FEAT_ID_V8: 1s_c_d_ld_dd */ }; int feat_set(const char *id_name) { uint32 i; /* HACK: "s2_4x" is an alias for sphinx-II features. */ if (strcmp(id_name, "s2_4x") == 0) { fid = FEAT_ID_SPHINX_II_STD; return S3_SUCCESS; } /* HACK, continued: "s3_1x39" is an alias for one of the sphinx-III variants. */ if (strcmp(id_name, "s3_1x39") == 0) { fid = FEAT_ID_V1; return S3_SUCCESS; } for (i = 0; name2id[i]; i++) { if (strcmp(id_name, name2id[i]) == 0) { fid = i; break; } } if (name2id[i] == NULL) { for (i = 0; __name2id[i]; i++) { if (strcmp(id_name, __name2id[i]) == 0) { fid = i; break; } } if (__name2id[i] == NULL) { E_ERROR("Unimplemented feature %s\n", id_name); E_ERROR("Implemented features are:\n"); for (i = 0; name2id[i]; i++) { fprintf(stderr, "\t%s\n", name2id[i]); } fid = FEAT_ID_NONE; return S3_ERROR; } } return S3_SUCCESS; } void feat_set_in_veclen(uint32 len) { mfcc_len = len; if (fid <= FEAT_ID_MAX) { feat_conf[fid].set_in_veclen(len); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } } int32 feat_read_lda(const char *ldafile, uint32 dim) { if (lda.lda != NULL) ckd_free_3d((void ***)lda.lda); lda.lda = lda_read(ldafile, &lda.n_lda, &lda.lda_rows, &lda.lda_cols); if (lda.lda == NULL) return S3_ERROR; lda.lda_dim = dim; assert(lda.lda_cols == feat_conf[fid].blksize()); return S3_SUCCESS; } /** * Project feature components to subvectors (if any). */ static void feat_subvec_project(vector_t **inout_feat, uint32 nfr) { uint32 i; for (i = 0; i < nfr; ++i) { float32 *out; int32 j; out = sv.sv_buf; for (j = 0; j < sv.n_sv; ++j) { int32 *d; for (d = sv.subvecs[j]; d && *d != -1; ++d) { *out++ = inout_feat[i][0][*d]; } } memcpy(inout_feat[i][0], sv.sv_buf, sv.sv_dim * sizeof(*sv.sv_buf)); } } static void subvecs_free(int32 **subvecs) { int32 **sv; for (sv = subvecs; sv && *sv; ++sv) ckd_free(*sv); ckd_free(subvecs); } static int32 ** feat_set_subvecs_internal(int32 **subvecs) { int32 **s; int32 n_sv, n_dim, i; uint32 n_stream = feat_conf[fid].n_stream(); uint32 feat_n_dim = feat_conf[fid].blksize(); if (subvecs == NULL) { subvecs_free(sv.subvecs); ckd_free(sv.sv_buf); ckd_free(sv.sv_len); sv.n_sv = 0; sv.subvecs = NULL; sv.sv_len = NULL; sv.sv_buf = NULL; sv.sv_dim = 0; return NULL; } if (n_stream != 1) { E_ERROR("Subvector specifications require single-stream features!"); return NULL; } n_sv = 0; n_dim = 0; for (s = subvecs; s && *s; ++s) { int32 *d; for (d = *s; d && *d != -1; ++d) { ++n_dim; } ++n_sv; } if (n_dim > feat_n_dim) { E_ERROR("Total dimensionality of subvector specification %d " "> feature dimensionality %d\n", n_dim, feat_n_dim); return NULL; } sv.n_sv = n_sv; sv.subvecs = subvecs; sv.sv_len = ckd_calloc(n_sv, sizeof(*sv.sv_len)); sv.sv_buf = ckd_calloc(n_dim, sizeof(*sv.sv_buf)); sv.sv_dim = n_dim; for (i = 0; i < n_sv; ++i) { int32 *d; for (d = subvecs[i]; d && *d != -1; ++d) { ++sv.sv_len[i]; } } return sv.subvecs; } int32 ** feat_set_subvecs(char const *str) { char const *strp; int32 n, n2, l; /* Grumble. */ struct int_list { int32 x; struct int_list *next; }; struct int_list *dimlist; /* List of dimensions in one subvector */ struct int_list *il; struct int_list_list { struct int_list *x; struct int_list_list *next; }; struct int_list_list *veclist; /* List of dimlists (subvectors) */ struct int_list_list *ill; int32 **subvec; int32 n_sv; if (str == NULL) return feat_set_subvecs_internal(NULL); veclist = NULL; strp = str; n_sv = 0; for (;;) { dimlist = NULL; for (;;) { if (sscanf(strp, "%d%n", &n, &l) != 1) E_FATAL("'%s': Couldn't read int32 @pos %d\n", str, strp - str); strp += l; if (*strp == '-') { strp++; if (sscanf(strp, "%d%n", &n2, &l) != 1) E_FATAL("'%s': Couldn't read int32 @pos %d\n", str, strp - str); strp += l; } else n2 = n; if ((n < 0) || (n > n2)) E_FATAL("'%s': Bad subrange spec ending @pos %d\n", str, strp - str); for (; n <= n2; n++) { for (il = dimlist; il; il = il->next) if (il->x == n) break; if (il != NULL) E_FATAL("'%s': Duplicate dimension ending @pos %d\n", str, strp - str); il = ckd_calloc(1, sizeof(*il)); il->x = n; il->next = dimlist; dimlist = il; } if ((*strp == '\0') || (*strp == '/')) break; if (*strp != ',') E_FATAL("'%s': Bad delimiter @pos %d\n", str, strp - str); strp++; } ill = ckd_calloc(1, sizeof(*ill)); ill->x = dimlist; ill->next = veclist; veclist = ill; ++n_sv; if (*strp == '\0') break; assert(*strp == '/'); strp++; } /* Convert the glists to arrays; remember the glists are in reverse order of the input! */ subvec = (int32 **) ckd_calloc(n_sv + 1, sizeof(int32 *)); /* +1 for sentinel */ subvec[n_sv] = NULL; /* sentinel */ n = n_sv; for (--n, ill = veclist; (n >= 0) && ill; ill = ill->next, --n) { n2 = 0; for (il = ill->x; il; il = il->next) ++n2; if (n2 <= 0) E_FATAL("'%s': 0-length subvector\n", str); subvec[n] = (int32 *) ckd_calloc(n2 + 1, sizeof(int32)); /* +1 for sentinel */ subvec[n][n2] = -1; /* sentinel */ il = ill->x; for (--n2; (n2 >= 0) && il; il = il->next, --n2) subvec[n][n2] = il->x; assert((n2 < 0) && (il == NULL)); } assert((n < 0) && (ill == NULL)); /* Free the glists */ { struct int_list_list *illn; struct int_list *iln; for (ill = veclist; ill; ill = illn) { illn = ill->next; for (il = ill->x; il; il = iln) { iln = il->next; ckd_free(il); } ckd_free(ill); } } if (feat_set_subvecs_internal(subvec) == NULL) { subvecs_free(subvec); return NULL; } return subvec; } uint32 feat_mfcc_len() { return mfcc_len; } const char * feat_doc() { if (fid <= FEAT_ID_MAX) { return feat_conf[fid].doc(); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return NULL; } uint32 feat_id() { if (fid <= FEAT_ID_MAX) { assert(fid == feat_conf[fid].id()); return fid; } else if (fid != FEAT_ID_NONE) { E_FATAL("feat module misconfigured with invalid fid %u\n", fid); } return FEAT_ID_NONE; } uint32 feat_n_stream() { if (sv.subvecs != NULL) { return sv.n_sv; } else if (fid <= FEAT_ID_MAX) { return feat_conf[fid].n_stream(); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return 0; } uint32 feat_blksize() { if (sv.subvecs != NULL) { return sv.sv_dim; } else if (lda.lda != NULL) { return lda.lda_dim; } else if (fid <= FEAT_ID_MAX) { return feat_conf[fid].blksize(); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return 0; } const uint32 * feat_vecsize() { if (sv.subvecs != NULL) { return sv.sv_len; } else if (lda.lda != NULL) { return &lda.lda_dim; } else if (fid <= FEAT_ID_MAX) { return feat_conf[fid].vecsize(); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return NULL; } int feat_ck_vecsize(const char *tag, const uint32 *vecsize, uint32 n_stream) { uint32 f_n_s = feat_n_stream(); uint32 i, e; const uint32 *f_vecsize = feat_vecsize(); if (n_stream != f_n_s) { E_ERROR("%s: n_stream==%u not consistent w/ feature module (n_stream==%u)\n", n_stream, f_n_s); return S3_ERROR; } for (i = 0, e = 0; i < n_stream; i++) { if (vecsize[i] != f_vecsize[i]) { e = 1; E_ERROR("%s: given vecsize[%u]==%u != feature vecsize[%u]==%u\n", i, vecsize[i], i, f_vecsize[i]); } } if (e) return S3_ERROR; else return S3_SUCCESS; } static vector_t ** feat_alloc_internal(uint32 n_frames, uint32 n_feat, uint32 const *vecsize) { vector_t **out; float *data, *d; uint32 len; uint32 i, j; uint32 frame_size; out = (vector_t **)ckd_calloc_2d(n_frames, n_feat, sizeof(vector_t)); /* Take the maximum of the original block size (do NOT call feat_blksize() because it will give the LDA output dimensionality) and the subvector block size. */ frame_size = feat_conf[fid].blksize(); if (sv.subvecs != NULL) { if (sv.sv_dim > frame_size) frame_size = sv.sv_dim; } len = n_frames * frame_size; data = ckd_calloc(len, sizeof(float32)); for (i = 0; i < n_frames; i++) { d = data + i * frame_size; for (j = 0; j < n_feat; j++) { out[i][j] = d; d += vecsize[j]; } } return out; } vector_t ** feat_alloc(uint32 n_frames) { if (fid <= FEAT_ID_MAX) { return feat_alloc_internal(n_frames, feat_n_stream(), feat_vecsize()); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return NULL; } void feat_free(vector_t **f) { if (fid <= FEAT_ID_MAX) { ckd_free(f[0][0]); /* frees the data block */ ckd_free_2d((void **)f); /* frees the access overhead */ } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } } vector_t ** feat_compute(vector_t *mfcc, uint32 *inout_n_frame) { vector_t **feat; if (fid <= FEAT_ID_MAX) { feat = feat_conf[fid].compute(mfcc, inout_n_frame); if (lda.lda) lda_transform(feat, *inout_n_frame, lda.lda, lda.lda_cols, lda.lda_dim); if (sv.subvecs) feat_subvec_project(feat, *inout_n_frame); return feat; } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } return NULL; } void feat_print_mfcc(vector_t *mfcc, uint32 n_frame) { uint32 i, j; for (i = 0; i < n_frame; i++) { printf("mfcc[%u]:", i); for (j = 0; j < mfcc_len; j++) { printf(" %.3e", mfcc[i][j]); } printf("\n"); } printf("\n"); } void feat_print(const char *label, vector_t **f, uint32 n_frame) { if (fid <= FEAT_ID_MAX) { feat_conf[fid].print(label, f, n_frame); } else if (fid == FEAT_ID_NONE) { E_FATAL("feat module must be configured w/ a valid ID\n"); } else { E_FATAL("feat module misconfigured with invalid feat_id %u\n", fid); } } <file_sep>/pocketsphinx/src/libpocketsphinx/vithist.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 1999-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * vithist.c -- Viterbi history * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * $Log: vithist.c,v $ * Revision 1.9 2006/02/23 16:56:12 arthchan2003 * Merged from the branch SPHINX3_5_2_RCI_IRII_BRANCH * 1, Split latticehist_t from flat_fwd.c to here. * 2, Introduced vithist_entry_cp. This is much better than the direct * copy we have been using. (Which could cause memory problem easily) * * Revision 1.8.4.12 2006/01/16 18:11:39 arthchan2003 * 1, Important Bug fixes, a local pointer is used when realloc is needed. This causes invalid writing of the memory, 2, Acoustic scores of the last segment in IBM lattice generation couldn't be found in the past. Now, this could be handled by the optional acoustic scores in the node of lattice. Application code is not yet checked-in * * Revision 1.8.4.11 2005/11/17 06:46:02 arthchan2003 * 3 changes. 1, Code was added for full triphone implementation, not yet working. 2, Senone scale is removed from vithist table. This was a bug introduced during some fixes in CALO. * * Revision 1.8.4.10 2005/10/17 04:58:30 arthchan2003 * vithist.c is the true source of memory leaks in the past for full cwtp expansion. There are two changes made to avoid this happen, 1, instead of using ve->rc_info as the indicator whether something should be done, used a flag bFullExpand to control it. 2, avoid doing direct C-struct copy (like *ve = *tve), it becomes the reason of why memory are leaked and why the code goes wrong. * * Revision 1.8.4.9 2005/10/07 20:05:05 arthchan2003 * When rescoring in full triphone expansion, the code should use the score for the word end with corret right context. * * Revision 1.8.4.8 2005/09/26 07:23:06 arthchan2003 * Also fixed a bug such SINGLE_RC_HISTORY=0 compiled. * * Revision 1.8.4.7 2005/09/26 02:28:00 arthchan2003 * Remove a E_INFO in vithist.c * * Revision 1.8.4.6 2005/09/25 19:33:40 arthchan2003 * (Change for comments) Added support for Viterbi history. * * Revision 1.8.4.5 2005/09/25 19:23:55 arthchan2003 * 1, Added arguments for turning on/off LTS rules. 2, Added arguments for turning on/off composite triphones. 3, Moved dict2pid deallocation back to dict2pid. 4, Tidying up the clean up code. * * Revision 1.8.4.4 2005/09/11 03:00:15 arthchan2003 * All lattice-related functions are not incorporated into vithist. So-called "lattice" is essentially the predecessor of vithist_t and fsg_history_t. Later when vithist_t support by right context score and history. It should replace both of them. * * Revision 1.8.4.3 2005/07/26 02:20:39 arthchan2003 * merged hyp_t with srch_hyp_t. * * Revision 1.8.4.2 2005/07/17 05:55:45 arthchan2003 * Removed vithist_dag_write_header * * Revision 1.8.4.1 2005/07/04 07:25:22 arthchan2003 * Added vithist_entry_display and vh_lmstate_display in vithist. * * Revision 1.8 2005/06/22 02:47:35 arthchan2003 * 1, Added reporting flag for vithist_init. 2, Added a flag to allow using words other than silence to be the last word for backtracing. 3, Fixed doxygen documentation. 4, Add keyword. * * Revision 1.9 2005/06/16 04:59:10 archan * Sphinx3 to s3.generic, a gentle-refactored version of Dave's change in senone scale. * * Revision 1.8 2005/05/26 00:46:59 archan * Added functionalities that such that <sil> will not be inserted at the end of the utterance. * * Revision 1.7 2005/04/25 23:53:35 archan * 1, Some minor modification of vithist_t, vithist_rescore can now support optional LM rescoring, vithist also has its own reporting routine. A new argument -lmrescore is also added in decode and livepretend. This can switch on and off the rescoring procedure. 2, I am reaching the final difficulty of mode 5 implementation. That is, to implement an algorithm which dynamically decide which tree copies should be entered. However, stuffs like score propagation in the leave nodes and non-leaves nodes are already done. 3, As briefly mentioned in 2, implementation of rescoring , which used to happened at leave nodes are now separated. The current implementation is not the most clever one. Wish I have time to change it before check-in to the canonical. * * Revision 1.6 2005/04/21 23:50:26 archan * Some more refactoring on the how reporting of structures inside kbcore_t is done, it is now 50% nice. Also added class-based LM test case into test-decode.sh.in. At this moment, everything in search mode 5 is already done. It is time to test the idea whether the search can really be used. * * Revision 1.5 2005/04/20 03:46:30 archan * factor dag header writer into vithist.[ch], do the corresponding change for lm_t * * Revision 1.4 2005/03/30 01:08:38 archan * codebase-wide update. Performed an age-old trick: Adding $Log into all .c and .h files. This will make sure the commit message be preprended into a file. * * 20.Apr.2001 RAH (<EMAIL>, <EMAIL>) * Added vithist_free() to free allocated memory * * 30-Dec-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Added vithist_partialutt_end() to allow backtracking in * the middle of an utterance * * 13-Aug-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added maxwpf handling. * * 24-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <listelem_alloc.h> #include <pio.h> #include <heap.h> #include "vithist.h" void vh_lmstate_display(vh_lmstate_t * vhl, s3dict_t * dict) { /* TODO: Also translate wid to string if dict is not NULL */ E_INFO("lwid[0] %d\n", vhl->lm3g.lwid[0]); E_INFO("lwid[1] %d\n", vhl->lm3g.lwid[1]); E_INFO("lwid[2] %d\n", vhl->lm3g.lwid[2]); } void vithist_entry_display(vithist_entry_t * ve, s3dict_t * dict) { E_INFO("Word ID %d \n", ve->wid); E_INFO("Sf %d Ef %d \n", ve->sf, ve->ef); E_INFO("Ascr %d Lscr %d \n", ve->ascr, ve->lscr); E_INFO("Score %d \n", ve->path.score); E_INFO("Type %d\n", ve->type); E_INFO("Valid for LM rescoring? %d\n", ve->valid); vh_lmstate_display(&(ve->lmstate), dict); } vithist_t * vithist_init(int32 max, int32 n_ci, int32 wbeam, int32 bghist, int32 report) { vithist_t *vh; if (report) E_INFO("Initializing Viterbi-history module\n"); vh = (vithist_t *) ckd_calloc(1, sizeof(vithist_t)); vh->entry = (vithist_entry_t **) ckd_calloc(VITHIST_MAXBLKS, sizeof(vithist_entry_t *)); vh->n_entry = 0; vh->frame_start = (int32 *) ckd_calloc(S3_MAX_FRAMES + 1, sizeof(int32)); vh->bestscore = (int32 *) ckd_calloc(S3_MAX_FRAMES + 1, sizeof(int32)); vh->bestvh = (int32 *) ckd_calloc(S3_MAX_FRAMES + 1, sizeof(int32)); vh->wbeam = wbeam; vh->bghist = bghist; E_INFO("Allocation for Viterbi history, lmset-final size: %d\n", max); vh->lms2vh_root = (vh_lms2vh_t **) ckd_calloc(max, sizeof(vh_lms2vh_t *)); vh->n_ci = n_ci; vh->lwidlist = NULL; vithist_report(vh); return vh; } /** This function cleans up rc_info */ static void clean_up_rc_info(backpointer_t * rc_info, int32 n_rc_info) { int32 i; for (i = 0; i < n_rc_info; i++) { rc_info[i].score = S3_LOGPROB_ZERO; rc_info[i].pred = -1; } } /** Copy vithist entry from the source vb to to destination va without copying rc_info. This is a specific function and please don't use it for copying if you haven't traced it. */ static void vithist_entry_dirty_cp(vithist_entry_t * va, vithist_entry_t * vb, int32 n_rc_info) { backpointer_t *tmpshp; assert(vb->rc == NULL); tmpshp = va->rc; /* Do a direct copy */ *va = *vb; va->rc = tmpshp; va->n_rc = n_rc_info; } /** Whole thing copying. */ static void vithist_entry_cp(vithist_entry_t * va, vithist_entry_t * vb) { int i; /* Do a direct copy */ va->wid = vb->wid; va->sf = vb->sf; va->ef = vb->ef; va->ascr = vb->ascr; va->lscr = vb->lscr; va->path.score = vb->path.score; va->path.pred = vb->path.pred; va->type = vb->type; va->valid = vb->valid; va->lmstate.lm3g.lwid[0] = vb->lmstate.lm3g.lwid[0]; va->lmstate.lm3g.lwid[1] = vb->lmstate.lm3g.lwid[1]; va->n_rc = vb->n_rc; if (va->rc) { for (i = 0; i < vb->n_rc; i++) va->rc[i] = vb->rc[i]; } } /* * Allocate a new entry at vh->n_entry if one doesn't exist and return ptr to it. */ static vithist_entry_t * vithist_entry_alloc(vithist_t * vh) { int32 b, l; vithist_entry_t *ve; b = VITHIST_ID2BLK(vh->n_entry); l = VITHIST_ID2BLKOFFSET(vh->n_entry); if (l == 0) { /* Crossed block boundary; allocate a new block of vithist space */ if (b >= VITHIST_MAXBLKS) E_FATAL ("Viterbi history array exhausted; increase VITHIST_MAXBLKS\n"); assert(vh->entry[b] == NULL); ve = (vithist_entry_t *) ckd_calloc(VITHIST_BLKSIZE, sizeof(vithist_entry_t)); vh->entry[b] = ve; } else ve = vh->entry[b] + l; vh->n_entry++; return ve; } int32 vithist_utt_begin(vithist_t * vh, int32 startwid, int32 lwid) { vithist_entry_t *ve; assert(vh->n_entry == 0); assert(vh->entry[0] == NULL); assert(vh->lwidlist == NULL); /* Create an initial dummy <s> entry. This is the root for the utterance */ ve = vithist_entry_alloc(vh); ve->wid = startwid; ve->sf = -1; ve->ef = -1; ve->ascr = 0; ve->lscr = 0; ve->path.score = 0; ve->path.pred = -1; ve->type = 0; ve->valid = 1; ve->lmstate.lm3g.lwid[0] = lwid; ve->lmstate.lm3g.lwid[1] = NGRAM_INVALID_WID; vh->n_frm = 0; vh->frame_start[0] = 1; vh->bestscore[0] = MAX_NEG_INT32; vh->bestvh[0] = -1; return 0; } static int32 vh_lmstate_find(vithist_t * vh, vh_lmstate_t * lms) { vh_lms2vh_t *lms2vh; s3lmwid32_t lwid; gnode_t *gn; lwid = lms->lm3g.lwid[0]; if ((lms2vh = vh->lms2vh_root[lwid]) == NULL) return -1; assert(lms2vh->state == lwid); lwid = lms->lm3g.lwid[1]; for (gn = lms2vh->children; gn; gn = gnode_next(gn)) { lms2vh = (vh_lms2vh_t *) gnode_ptr(gn); if (lms2vh->state == lwid) return lms2vh->vhid; } return -1; } /* * Enter a new LMstate into the current frame LMstates trees; called ONLY IF not already * present. */ static void vithist_lmstate_enter(vithist_t * vh, int32 vhid, vithist_entry_t * ve) { vh_lms2vh_t *lms2vh, *child; s3lmwid32_t lwid; lwid = ve->lmstate.lm3g.lwid[0]; if ((lms2vh = vh->lms2vh_root[lwid]) == NULL) { lms2vh = (vh_lms2vh_t *) ckd_calloc(1, sizeof(vh_lms2vh_t)); vh->lms2vh_root[lwid] = lms2vh; lms2vh->state = lwid; lms2vh->children = NULL; vh->lwidlist = glist_add_int32(vh->lwidlist, (int32) lwid); } else { assert(lms2vh->state == lwid); } child = (vh_lms2vh_t *) ckd_calloc(1, sizeof(vh_lms2vh_t)); child->state = ve->lmstate.lm3g.lwid[1]; child->children = NULL; child->vhid = vhid; child->ve = ve; lms2vh->children = glist_add_ptr(lms2vh->children, (void *) child); } /* Rclist is separate from tve because C structure copying is used in *ve = *tve */ void vithist_enter(vithist_t * vh, /**< The history table */ s3dict_t *dict, /**< Dictionary */ dict2pid_t *dict2pid, /**< Context table mapping thing */ vithist_entry_t * tve, /**< an input vithist element */ int32 comp_rc /**< a compressed rc. If it is the actual rc, it won't work. */ ) { vithist_entry_t *ve; int32 vhid; int32 n_ci; int32 n_rc_info; int32 old_n_rc_info; n_ci = vh->n_ci; /* Check if an entry with this LM state already exists in current frame */ vhid = vh_lmstate_find(vh, &(tve->lmstate)); n_rc_info = 0; /* Just fill in something if not using crossword triphon */ assert(comp_rc < n_rc_info); if (vhid < 0) { /* Not found; allocate new entry */ vhid = vh->n_entry; ve = vithist_entry_alloc(vh); vithist_entry_dirty_cp(ve, tve, n_rc_info); vithist_lmstate_enter(vh, vhid, ve); /* Enter new vithist info into LM state tree */ /* E_INFO("Start a new entry wid %d\n",ve->wid); */ if (ve->rc != NULL) clean_up_rc_info(ve->rc, ve->n_rc); if (comp_rc != -1) { if (ve->rc == NULL) { ve->n_rc = get_rc_nssid(dict2pid, ve->wid, dict); /* Always allocate n_ci for rc_info */ ve->rc = ckd_calloc(vh->n_ci, sizeof(*ve->rc)); clean_up_rc_info(ve->rc, ve->n_rc); } assert(comp_rc < ve->n_rc); if (ve->rc[comp_rc].score < tve->path.score) { ve->rc[comp_rc].score = tve->path.score; ve->rc[comp_rc].pred = tve->path.pred; } } } else { ve = vithist_id2entry(vh, vhid); /* E_INFO("Replace the old entry\n"); */ /* E_INFO("Old entry wid %d, New entry wid %d\n",ve->wid, tve->wid); */ if (comp_rc == -1) { if (ve->path.score < tve->path.score) { vithist_entry_dirty_cp(ve, tve, n_rc_info); assert(comp_rc < n_rc_info); if (ve->rc != NULL) clean_up_rc_info(ve->rc, ve->n_rc); } } else { /* This is wrong, the score Alright, how vhid was searched in the first place? */ if (ve->path.score < tve->path.score) { old_n_rc_info = ve->n_rc; vithist_entry_dirty_cp(ve, tve, n_rc_info); assert(comp_rc < n_rc_info); assert(ve->rc); clean_up_rc_info(ve->rc, ve->n_rc); ve->rc[comp_rc].score = tve->path.score; ve->rc[comp_rc].pred = tve->path.pred; } } } /* Update best exit score in this frame */ if (vh->bestscore[vh->n_frm] < tve->path.score) { vh->bestscore[vh->n_frm] = tve->path.score; vh->bestvh[vh->n_frm] = vhid; } } void vithist_rescore(vithist_t * vh, ngram_model_t *lm, s3dict_t *dict, dict2pid_t *dict2pid, fillpen_t *fp, s3wid_t wid, int32 ef, int32 score, int32 pred, int32 type, int32 rc) { vithist_entry_t *pve, tve; int32 lwid; int32 se, fe; int32 i; assert(vh->n_frm == ef); if (pred == -1) { /* Always do E_FATAL assuming upper level function take care of error checking. */ E_FATAL ("Hmm->out.history equals to -1 with score %d, some active phone was not computed?\n", score); } /* pve is the previous entry before word with wid or, se an fe is the first to the last entry before pve. So pve is w_{n-1} */ pve = vithist_id2entry(vh, pred); /* Create a temporary entry with all the info currently available */ tve.wid = wid; tve.sf = pve->ef + 1; tve.ef = ef; tve.type = type; tve.valid = 1; tve.ascr = score - pve->path.score; tve.lscr = 0; tve.rc = NULL; tve.n_rc = 0; /* Filler words only have unigram language model scores, so not * much special needs to be done for them. vithist_prune() is * going to prune out most of these later on, anyway. */ if (s3dict_filler_word(dict, wid)) { tve.path.score = score; tve.lscr = fillpen(fp, wid); tve.path.score += tve.lscr; if ((tve.path.score - vh->wbeam) >= vh->bestscore[vh->n_frm]) { tve.path.pred = pred; /* Note that they just propagate the same LM state since * they are not in the LM. */ tve.lmstate.lm3g = pve->lmstate.lm3g; vithist_enter(vh, dict, dict2pid, &tve, rc); } } else { if (pred == 0) { /* Special case for the initial <s> entry */ se = 0; fe = 1; } else { se = vh->frame_start[pve->ef]; fe = vh->frame_start[pve->ef + 1]; } /* Now if it is a word, backtrack again to get all possible previous word So pve becomes the w_{n-2}. */ lwid = ngram_wid(lm, s3dict_wordstr(dict, s3dict_basewid(dict, wid))); tve.lmstate.lm3g.lwid[0] = lwid; /* FIXME: This loop is completely awful. For each entry in * this frame, we scan every entry in the previous frame, * potentially creating a new history entry. This means that * without pruning, the size of the vithist table (and thus * the time taken here) is exponential in the number of * frames! */ for (i = se; i < fe; i++) { pve = vithist_id2entry(vh, i); if (pve->valid) { int n_used; tve.path.score = pve->path.score + tve.ascr; /* Try at all costs to avoid calling ngram_tg_score() * because it is the main time consuming part here * (but as noted above... ugh...) See below as well. */ if ((tve.path.score - vh->wbeam) < vh->bestscore[vh->n_frm]) continue; /* The trigram cache is supposed to make this fast, * but due to the crazy number of times this could be * called, it's still slow compared to a hash * table. */ tve.lscr = ngram_tg_score(lm, lwid, pve->lmstate.lm3g.lwid[0], pve->lmstate.lm3g.lwid[1], &n_used); tve.path.score += tve.lscr; /* A different word exit threshold - we would have to * be inside the general word beam in order to get * here, now we apply a second beam to the *vithist * entries* in this frame. There can be an ungodly * number of them for reasons that aren't entirely * clear to me, so this is kind of a pre-pruning. * NOTE: the "backwards" math here is because * vh->bestscore is frequently MAX_NEG_INT32. ALSO * NOTE: We can't precompute the threshold since the * best score will be updated by vithist_enter(). */ if ((tve.path.score - vh->wbeam) >= vh->bestscore[vh->n_frm]) { tve.path.pred = i; tve.lmstate.lm3g.lwid[1] = pve->lmstate.lm3g.lwid[0]; vithist_enter(vh, dict, dict2pid, &tve, rc); } } } } } /* * Garbage collect invalid entries in current frame, right after marking invalid entries. */ static void vithist_frame_gc(vithist_t * vh, int32 frm) { vithist_entry_t *ve, *tve; int32 se, fe, te, bs, bv; int32 i, j; int32 l; int32 n_rc_info; n_rc_info = 0; se = vh->frame_start[frm]; fe = vh->n_entry - 1; te = se; bs = MAX_NEG_INT32; bv = -1; E_DEBUG(2,("GC in frame %d, scanning vithist entries from %d to %d\n", frm, se, fe)); for (i = se; i <= fe; i++) { ve = vithist_id2entry(vh, i); if (ve->valid) { E_DEBUG(2,("Valid entry %d score %d\n", i, ve->path.score)); if (i != te) { /* Move i to te */ tve = vithist_id2entry(vh, te); /**tve = *ve;*/ vithist_entry_cp(tve, ve); } if (ve->path.score > bs) { bs = ve->path.score; bv = te; } te++; } } E_DEBUG(2,("GC bs %d vh->bestscore[frm] %d\n", bs, vh->bestscore[frm])); /* Can't assert this any more because history pruning could actually make the best token go away */ assert(bs == vh->bestscore[frm]); vh->bestvh[frm] = bv; /* Free up entries [te..n_entry-1] */ i = VITHIST_ID2BLK(vh->n_entry - 1); j = VITHIST_ID2BLK(te - 1); for (; i > j; --i) { for (l = 0; l < VITHIST_BLKSIZE; l++) { ve = vh->entry[i] + l; if (ve->rc != NULL) { ckd_free(ve->rc); ve->rc = NULL; } } ckd_free((void *) vh->entry[i]); vh->entry[i] = NULL; } vh->n_entry = te; } void vithist_prune(vithist_t * vh, s3dict_t * dict, int32 frm, int32 maxwpf, int32 maxhist, int32 beam) { int32 se, fe, filler_done, th; vithist_entry_t *ve; heap_t h; s3wid_t *wid = NULL; int32 i, nwf, nhf; if (maxwpf == -1 && maxhist == -1) return; nwf = nhf = 0; assert(frm >= 0); se = vh->frame_start[frm]; fe = vh->n_entry - 1; th = vh->bestscore[frm] + beam; h = heap_new(); if (maxwpf > 0) { wid = (s3wid_t *) ckd_calloc(maxwpf + 1, sizeof(s3wid_t)); wid[0] = BAD_S3WID; } E_DEBUG(1, ("vithist_prune frame %d has %d entries\n", frm, fe-se+1)); for (i = se; i <= fe; i++) { ve = vithist_id2entry(vh, i); heap_insert(h, (void *) ve, -(ve->path.score)); ve->valid = 0; } /* Mark invalid entries: beyond maxwpf words and below threshold */ filler_done = 0; while (heap_pop(h, (void **) (&ve), &i) && ve->path.score >= th /* the score (or the cw scores) is above threshold */ && (nhf < maxhist || maxhist == -1)) { if (s3dict_filler_word(dict, ve->wid)) { /* Major HACK!! Keep only one best filler word entry per frame */ if (filler_done) continue; filler_done = 1; } /* Check if this word already valid (e.g., under a different history) */ if (wid) for (i = 0; IS_S3WID(wid[i]) && (wid[i] != ve->wid); i++); if (wid && NOT_S3WID(wid[i])) { /* New word; keep only if <maxwpf words already entered, even if >= thresh */ if (nwf < maxwpf || maxwpf == -1) { if (wid) { wid[i] = ve->wid; wid[i + 1] = BAD_S3WID; } ++nwf; ++nhf; ve->valid = 1; } } else if (!vh->bghist) { ++nhf; ve->valid = 1; } } ckd_free((void *) wid); heap_destroy(h); E_DEBUG(1, ("vithist_prune frame %d retained %d entries\n", frm, nhf)); /* Garbage collect invalid entries */ vithist_frame_gc(vh, frm); } static void vithist_lmstate_reset(vithist_t * vh) { gnode_t *lgn, *gn; int32 i; vh_lms2vh_t *lms2vh, *child; for (lgn = vh->lwidlist; lgn; lgn = gnode_next(lgn)) { i = (int32) gnode_int32(lgn); lms2vh = vh->lms2vh_root[i]; for (gn = lms2vh->children; gn; gn = gnode_next(gn)) { child = (vh_lms2vh_t *) gnode_ptr(gn); ckd_free((void *) child); } glist_free(lms2vh->children); ckd_free((void *) lms2vh); vh->lms2vh_root[i] = NULL; } glist_free(vh->lwidlist); vh->lwidlist = NULL; } void vithist_frame_windup(vithist_t * vh, int32 frm, FILE * fp, ngram_model_t *lm, s3dict_t *dict) { assert(vh->n_frm == frm); vh->n_frm++; vh->frame_start[vh->n_frm] = vh->n_entry; if (fp) vithist_dump(vh, frm, lm, dict, fp); vithist_lmstate_reset(vh); vh->bestscore[vh->n_frm] = MAX_NEG_INT32; vh->bestvh[vh->n_frm] = -1; } int32 vithist_utt_end(vithist_t * vh, ngram_model_t *lm, s3dict_t *dict, dict2pid_t *dict2pid, fillpen_t *fp) { int32 f, i; int32 sv, nsv, scr, bestscore, bestvh, vhid; vithist_entry_t *ve, *bestve = 0; int32 endwid = NGRAM_INVALID_WID; bestscore = MAX_NEG_INT32; bestvh = -1; /* Find last frame with entries in vithist table */ /* by ARCHAN 20050525, it is possible that the last frame will not be reached in decoding */ for (f = vh->n_frm - 1; f >= 0; --f) { sv = vh->frame_start[f]; /* First vithist entry in frame f */ nsv = vh->frame_start[f + 1]; /* First vithist entry in next frame (f+1) */ if (sv < nsv) break; } if (f < 0) return -1; if (f != vh->n_frm - 1) E_WARN("No word exit in frame %d, using exits from frame %d\n", vh->n_frm - 1, f); /* Terminate in a final </s> node (make this optional?) */ endwid = ngram_wid(lm, S3_FINISH_WORD); for (i = sv; i < nsv; i++) { int n_used; ve = vithist_id2entry(vh, i); scr = ve->path.score; scr += ngram_tg_score(lm, endwid, ve->lmstate.lm3g.lwid[0], ve->lmstate.lm3g.lwid[1], &n_used); if (bestscore < scr) { bestscore = scr; bestvh = i; bestve = ve; } } assert(bestvh >= 0); if (f != vh->n_frm - 1) { E_ERROR("No word exit in frame %d, using exits from frame %d\n", vh->n_frm - 1, f); /* Add a dummy silwid covering the remainder of the utterance */ assert(vh->frame_start[vh->n_frm - 1] == vh->frame_start[vh->n_frm]); vh->n_frm -= 1; vithist_rescore(vh, lm, dict, dict2pid, fp, s3dict_silwid(dict), vh->n_frm, bestve->path.score, bestvh, -1, -1); vh->n_frm += 1; vh->frame_start[vh->n_frm] = vh->n_entry; return vithist_utt_end(vh, lm, dict, dict2pid, fp); } /* vithist_dump(vh,-1,kbc,stdout); */ /* Create an </s> entry */ ve = vithist_entry_alloc(vh); ve->wid = s3dict_finishwid(dict); ve->sf = (bestve->ef == BAD_S3FRMID) ? 0 : bestve->ef + 1; ve->ef = vh->n_frm; ve->ascr = 0; ve->lscr = bestscore - bestve->path.score; ve->path.score = bestscore; ve->path.pred = bestvh; ve->type = 0; ve->valid = 1; ve->lmstate.lm3g.lwid[0] = endwid; ve->lmstate.lm3g.lwid[1] = ve->lmstate.lm3g.lwid[0]; vhid = vh->n_entry - 1; /* vithist_dump(vh,-1,kbc,stdout); */ return vhid; } int32 vithist_partialutt_end(vithist_t * vh, ngram_model_t *lm, s3dict_t *dict) { int32 f, i; int32 sv, nsv, scr, bestscore, bestvh; vithist_entry_t *ve, *bestve; int32 endwid; /* Find last frame with entries in vithist table */ for (f = vh->n_frm - 1; f >= 0; --f) { sv = vh->frame_start[f]; /* First vithist entry in frame f */ nsv = vh->frame_start[f + 1]; /* First vithist entry in next frame (f+1) */ if (sv < nsv) break; } if (f < 0) return -1; if (f != vh->n_frm - 1) { E_ERROR("No word exits from in block with last frame= %d\n", vh->n_frm - 1); return -1; } /* Terminate in a final </s> node (make this optional?) */ endwid = ngram_wid(lm, S3_FINISH_WORD); bestscore = MAX_NEG_INT32; bestvh = -1; for (i = sv; i < nsv; i++) { int n_used; ve = vithist_id2entry(vh, i); scr = ve->path.score; scr += ngram_tg_score(lm, endwid, ve->lmstate.lm3g.lwid[0], ve->lmstate.lm3g.lwid[1], &n_used); if (bestscore < scr) { bestscore = scr; bestvh = i; bestve = ve; } } return bestvh; } void vithist_utt_reset(vithist_t * vh) { int32 b; int32 ent; vithist_lmstate_reset(vh); for (b = VITHIST_ID2BLK(vh->n_entry - 1); b >= 0; --b) { /* If rc_info is used, then free them */ if (b != 0) ent = VITHIST_BLKSIZE - 1; else ent = vh->n_entry - 1; ckd_free((void *) vh->entry[b]); vh->entry[b] = NULL; } vh->n_entry = 0; vh->bestscore[0] = MAX_NEG_INT32; vh->bestvh[0] = -1; } void vithist_dump(vithist_t * vh, int32 frm, ngram_model_t *lm, s3dict_t *dict, FILE * fp) { int32 i, j; vithist_entry_t *ve; int32 sf, ef; if (frm >= 0) { sf = frm; ef = frm; fprintf(fp, "VITHIST frame %d #entries %d\n", frm, vh->frame_start[sf + 1] - vh->frame_start[sf]); } else { sf = 0; ef = vh->n_frm - 1; fprintf(fp, "VITHIST #frames %d #entries %d\n", vh->n_frm, vh->n_entry); } fprintf(fp, "\t%7s %5s %5s %11s %9s %8s %7s %4s Word (LM-state)\n", "Seq/Val", "SFrm", "EFrm", "PathScr", "SegAScr", "SegLScr", "Pred", "Type"); for (i = sf; i <= ef; i++) { fprintf(fp, "%5d BS: %11d BV: %8d\n", i, vh->bestscore[i], vh->bestvh[i]); for (j = vh->frame_start[i]; j < vh->frame_start[i + 1]; j++) { int32 lwid; ve = vithist_id2entry(vh, j); fprintf(fp, "\t%c%6d %5d %5d %11d %9d %8d %7d %4d %s", (ve->valid ? ' ' : '*'), j, ve->sf, ve->ef, ve->path.score, ve->ascr, ve->lscr, ve->path.pred, ve->type, s3dict_wordstr(dict, ve->wid)); fprintf(fp, " (%s", ngram_word(lm, ve->lmstate.lm3g.lwid[0])); lwid = ve->lmstate.lm3g.lwid[1]; fprintf(fp, ", %s", ngram_word(lm, lwid)); fprintf(fp, ")\n"); } if (j == vh->frame_start[i]) fprintf(fp, "\n"); } fprintf(fp, "END_VITHIST\n"); fflush(fp); } /* * RAH, free memory allocated in vithist_free */ void vithist_free(vithist_t * v) { if (v) { vithist_utt_reset(v); if (v->entry) { ckd_free((void *) v->entry); } if (v->frame_start) ckd_free((void *) v->frame_start); if (v->bestscore) ckd_free((void *) v->bestscore); if (v->bestvh) ckd_free((void *) v->bestvh); if (v->lms2vh_root) ckd_free((void *) v->lms2vh_root); ckd_free((void *) v); } } void vithist_report(vithist_t * vh) { E_INFO_NOFN("Initialization of vithist_t, report:\n"); if (vh) { E_INFO_NOFN("Word beam = %d\n", vh->wbeam); E_INFO_NOFN("Bigram Mode =%d\n", vh->bghist); E_INFO_NOFN("\n"); } else { E_INFO_NOFN("Viterbi history is (null)\n"); } } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/actionproviders/BackLabelPopUpProvider.java package edu.cmu.sphinx.tools.confdesigner.actionproviders; import edu.cmu.sphinx.tools.confdesigner.ConfigScene; import org.netbeans.api.visual.action.PopupMenuProvider; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.Widget; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A little popup which is used to configure background label areas. * * @author <NAME> */ public class BackLabelPopUpProvider implements PopupMenuProvider { public final String REMOVE_LABEL = "remove"; public final String SET_COLOR_LABEL = "set color"; private LabelWidget parent; public BackLabelPopUpProvider(LabelWidget parent) { assert parent != null; this.parent = parent; } public JPopupMenu getPopupMenu(final Widget widget, Point point) { JPopupMenu menu = new JPopupMenu("test"); ActionListener al = new ActionListener() { JColorChooser colorChooser; public void actionPerformed(ActionEvent e) { JMenuItem sourceItem = (JMenuItem) e.getSource(); if (sourceItem.getText().equals(REMOVE_LABEL)) { ((ConfigScene) parent.getScene()).removeBckndLabel(parent); } else if (sourceItem.getText().equals(SET_COLOR_LABEL)) { colorChooser = new JColorChooser(); colorChooser.getSelectionModel().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { Color newLabelColor = colorChooser.getColor(); widget.setBackground(newLabelColor); } }); JDialog dialog = new JDialog(new Frame()); dialog.getContentPane().add(colorChooser); dialog.setVisible(true); } } }; JMenuItem item = new JMenuItem(REMOVE_LABEL); item.addActionListener(al); menu.add(item); item = new JMenuItem(SET_COLOR_LABEL); item.addActionListener(al); menu.add(item); return menu; } } <file_sep>/SphinxTrain/src/programs/bw/accum.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: accum.h * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef ACCUM_H #define ACCUM_H #include <stdio.h> #include <s3/prim_type.h> #include <s3/vector.h> #include <s3/gauden.h> #include <s3/model_inventory.h> #include <s3/state.h> void accum_den_terms(float32 **acc, float64 **den_terms, uint32 **den_idx, uint32 n_feat, uint32 n_top); int32 accum_gauden(float32 ***cbacc, uint32 *lcl2gbl, uint32 n_lcl2gbl, vector_t *frame, uint32 ***den_idx, gauden_t *g, int32 mean_reest, int32 var_reest, int32 pass2var, float32 ***wacc, int32 var_is_full, FILE *pdumpfh, float32 ***lda); int32 accum_global(model_inventory_t *inv, state_t *state, uint32 n_state, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 var_is_full); int32 accum_dump(const char *out_dir, model_inventory_t *inv, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 pass2var, int32 var_is_full, int ckpt); int32 accum_viterbi(uint32 *vit_sseq, uint32 n_vit_sseq, state_t *state, vector_t **obs, uint32 n_obs, model_inventory_t *inv, float64 ****den, uint32 ****den_idx, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest); void accum_global_gauden(vector_t ***acc, vector_t ***l_acc, gauden_t *g, uint32 *lcl2glb, uint32 n_lcl2glb); void accum_global_gauden_full(vector_t ****acc, vector_t ****l_acc, gauden_t *g, uint32 *lcl2glb, uint32 n_lcl2glb); void accum_global_gauden_dnom(float32 ***dnom, float32 ***l_dnom, gauden_t *g, uint32 *lcl2glb, uint32 n_lcl2glb); void accum_global_mixw(model_inventory_t *inv, gauden_t *g); void accum_global_tmat(model_inventory_t *inv, state_t *state, uint32 n_state); #endif /* ACCUM_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.9 97/07/16 11:38:16 eht * *** empty log message *** * * Revision 1.8 1996/07/29 16:21:12 eht * Got rid of accum_trans() and accum_non_emit_trans() and added * accum_den_terms() * * Revision 1.7 1996/03/26 15:17:51 eht * Fix beam definition bug * * Revision 1.6 1996/01/30 17:12:27 eht * Include a CI codebook (mixture Gaussian) weighted vector accumulators * * Revision 1.5 1995/11/30 20:52:00 eht * Allow tmat_reest to be passed as an argument * * Revision 1.4 1995/10/12 18:22:18 eht * Updated comments and changed <s3/state.h> to "state.h" * * Revision 1.3 1995/10/10 12:44:06 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/08/09 20:19:19 eht * Add mixing weight id argument so that error output count * be more informative * * Revision 1.1 1995/06/02 20:41:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libfbs/s3types.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * s3types.h -- Types specific to s3 decoder. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 12-Jul-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBFBS_S3TYPES_H_ #define _LIBFBS_S3TYPES_H_ #include <libutil/prim_type.h> /* * Size definitions for more semantially meaningful units. */ typedef int16 s3cipid_t; /* Ci phone id */ typedef int32 s3pid_t; /* Phone id (triphone or ciphone) */ typedef int32 s3wid_t; /* Dictionary word id */ typedef uint16 s3lmwid_t; /* LM word id (uint16 for conserving space) */ typedef int32 s3latid_t; /* Lattice entry id */ typedef int16 s3frmid_t; /* Frame id (must be SIGNED integer) */ typedef uint16 s3senid_t; /* Senone id */ typedef int32 s3mgauid_t; /* Mixture-gaussian codebook id */ typedef int32 s3tmatid_t; /* Transition matrix id; there can be as many as pids */ /* * Illegal value definitions and tests for specific types. */ #define BAD_CIPID ((s3cipid_t) -1) #define NOT_CIPID(p) ((p)<0) #define IS_CIPID(p) ((p)>=0) #define BAD_PID ((s3pid_t) -1) #define NOT_PID(p) ((p)<0) #define IS_PID(p) ((p)>=0) #define BAD_TMATID ((s3tmatid_t) -1) #define NOT_TMATID(t) ((t)<0) #define IS_TMATID(t) ((t)>=0) #define BAD_WID ((s3wid_t) -1) #define NOT_WID(w) ((w)<0) #define IS_WID(w) ((w)>=0) #define BAD_LMWID ((s3lmwid_t) 0xffff) #define NOT_LMWID(w) ((w)==BAD_LMWID) #define IS_LMWID(w) ((w)!=BAD_LMWID) #define BAD_LATID ((s3latid_t) -1) #define NOT_LATID(l) ((l)<0) #define IS_LATID(l) ((l)>=0) #define BAD_FRMID ((s3frmid_t) -1) #define NOT_FRMID(f) ((f)<0) #define IS_FRMID(f) ((f)>=0) #define BAD_SENID ((s3senid_t) 0xffff) #define NOT_SENID(s) ((s)==BAD_SENID) #define IS_SENID(s) ((s)!=BAD_SENID) #define BAD_MGAUID ((s3mgauid_t) -1) #define NOT_MGAUID(m) ((m)<0) #define IS_MGAUID(m) ((m)>=0) #endif <file_sep>/archive_s3/s3.2/src/cmn.h /* * cmn.h -- Various forms of cepstral mean normalization * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 28-Apr-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Copied from previous version. */ #ifndef _S3_CMN_H_ #define _S3_CMN_H_ #include <libutil/libutil.h> /* * Apply Cepstral Mean Normalization (CMN) to the set of input mfc frames, by subtracting * the mean of the input from each frame. C0 is also included in this process. * This function operates on an entire utterance at a time. Hence, the entire utterance * must be available beforehand (batchmode). */ void cmn (float32 **mfc, /* In/Out: mfc[f] = mfc vector in frame f */ int32 varnorm, /* In: if not FALSE, variance normalize the input vectors to have unit variance (along each dimension independently); Irrelevant if no cmn is performed */ int32 n_frame, /* In: #frames of mfc vectors */ int32 veclen); /* In: mfc vector length */ #endif <file_sep>/archive_s3/s3/config/common_make_rules ########################################################-*-mode:Makefile-*- # Copyright (c) 2000 Carnegie Mellon University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 3. The names "Sphinx" and "Carnegie Mellon" must not be used to # endorse or promote products derived from this software without # prior written permission. To obtain permission, contact # <EMAIL>. # # 4. Products derived from this software may not be called "Sphinx" # nor may "Sphinx" appear in their names without prior written # permission of Carnegie Mellon University. To obtain permission, # contact <EMAIL>. # # 5. Redistributions of any form whatsoever must retain the following # acknowledgment: # "This product includes software developed by Carnegie # Mellon University (http://www.speech.cs.cmu.edu/)." # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Common make rules included in all Makefiles # ######################################################################## # System type include $(TOP)/config/system.mak ifeq ($(SYSTEM_LOADED),) MACHINETYPE=unknown OSTYPE=unknown OSREV= endif # Include project specific rules -include $(TOP)/config/project.mak ## User defined configuration options include $(TOP)/config/config ## Compile-time directories BINDIR=$(shell test -d $(TOP)/bin.$(PLATFORM) || mkdir $(TOP)/bin.$(PLATFORM); echo $(TOP)/bin.$(PLATFORM);) SCRIPTDIR=$(BINDIR) LIBDIR=$(shell test -d $(TOP)/lib.$(PLATFORM) || mkdir $(TOP)/lib.$(PLATFORM); echo $(TOP)/lib.$(PLATFORM);) ifdef SRCS OBJDIR=$(shell test -d obj.$(PLATFORM) || mkdir obj.$(PLATFORM); echo obj.$(PLATFORM);) OBJS=$(shell echo $(SRCS:.c=.o) | awk '{for (i=1; i<=NF; i++) printf("'$(OBJDIR)'/%s\n",$$i)}';) endif INCLUDES = -I$(TOP)/include CFLAGS += $(EXTRA_CC_FLAGS) $(OPT) $(DBG) $(LOCAL_INCLUDES) $(INCLUDES) LDFLAGS += -L$(LIBDIR) $(EXTRA_LD_FLAGS) STLIBS = -ls3decoder -lutil -ls3audio LIBS = $(STLIBS) -lm $(OBJDIR)/%.o : %.c $(CC) $(CFLAGS) -c $< -o $@ all: .make_build_dirs $(ALL) nothing nothing: @ echo > /dev/null system.mak : config @echo Check system type >&2 @/bin/sh $(TOP)/config/system.sh > system.mak .make_build_dirs: @ echo making in $(DIRNAME) ... ifneq (,$(BUILD_DIRS)) @ for i in $(BUILD_DIRS) ; \ do \ $(MAKE) --no-print-directory -C $$i || exit ; \ done endif # Library build rules .build_lib: $(OBJS) $(AR) cruv $(LIBDIR)/lib$(LIBNAME).a $(OBJS) $(RANLIB) $(LIBDIR)/lib$(LIBNAME).a touch .build_lib # Program build rules $(BINDIR)/$(TARGET): $(OBJS) $(DEP_LIBS) $(CC) -o $@ $(LDFLAGS) $(OBJS) $(LIBS) # Festival Script build rules $(SCRIPTDIR)/%: %.festival @ echo "#!/bin/sh" > $@ @ echo "\"true\"; exec "$(FESTIVAL)' --script $$0 $$*' >>$@ @ cat $< >>$@ @ chmod +x $@ # csh Script build rules $(SCRIPTDIR)/%: %.csh @ echo "#!/bin/csh" > $@ @ cat $< >>$@ @ chmod +x $@ # Perl Script build rules $(SCRIPTDIR)/$(DIRNAME)/%.pl: %.pl @ if [ ! -d $(SCRIPTDIR)/$(DIRNAME) ] ;\ then \ mkdir -p $(SCRIPTDIR)/$(DIRNAME); \ fi @ echo "#!"$(PERL) > $@ @ sed '1d' $< >>$@ @ chmod +x $@ clean: @ echo make clean in $(DIRNAME) ... @rm -f *.o *.a *~ $(OBJDIR)/*.o $(LOCAL_CLEAN) ifneq (,$(ALL_DIRS)) @ for i in $(ALL_DIRS) ; \ do \ $(MAKE) -C $$i --no-print-directory clean; \ done endif DEPEND=make.depend MAKE_DEPEND=$(CC) -MM $(CFLAGS) depend: @ echo make depend in $(DIRNAME) ... @ rm -f $(DEPEND) @ $(MAKE) nothing ifdef ALL_DIRS @ for i in $(ALL_DIRS) ; \ do \ $(MAKE) -C $$i --no-print-directory depend ; \ done endif $(DEPEND): $(SRCS) @ rm -f $(DEPEND) @ for i in $(SRCS) ; \ do \ echo "# $$i" ; \ $(MAKE_DEPEND) $$i ; \ echo ; \ done > $(DEPEND) file-list: @ echo making file-list in $(DIRNAME) ... @ for f in $(FILES) ; \ do \ echo $(DIRNAME)/$$f >>$(TOP)/FileList ; \ done ifneq (,$(ALL_DIRS)) @ for i in $(ALL_DIRS) ; \ do \ $(MAKE) -C $$i --no-print-directory file-list; \ done endif info: @echo Project Name = $(PROJECT_NAME) @echo Project Prefix = $(PROJECT_PREFIX) @echo Project Version = $(PROJECT_VERSION) @echo Project Date = $(PROJECT_DATE) @echo Project State = $(PROJECT_STATE) @echo @echo Configuration Variables @echo none at present # If there are sources in this directory, load in the dependencies ifdef SRCS -include $(DEPEND) endif <file_sep>/CLP/src/Cluster.cc // -*- C++ -*- //-------------------------------------------------------------------------------------------------------- // Cluster.cc // // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //-------------------------------------------------------------------------------------------------------- #include <cstdlib> #include <iomanip> #include <cstdio> #include <cassert> #include <iostream> #include <algorithm> #include <list> using namespace std; #include "common_lattice.h" #include "Link.h" #include "Cluster.h" #include "Lattice.h" Cluster::Cluster(): lat_ptr((Lattice *)0), cid(0), best_link(-1), min_time(100000), max_time(-1){} // ////////////////////////////////////////////////////////////////////// Cluster::Cluster(unsigned idx, const Lattice* from_lattice): lat_ptr(from_lattice), cid(idx), best_link(-1), min_time(100000), max_time(-1){} // ////////////////////////////////////////////////////////////////////// void Cluster::add_link(const Link& l){ clinks.push_front(l.Id()); if (((Lattice* )lat_ptr)->has_time_info()){ // MOD 7/3/2000 - cast added if (min_time > l.start_time()) min_time = l.start_time(); if (max_time < l.end_time()) max_time = l.end_time(); } else{ if (min_time > l.start_node().Max_dist()) min_time = l.start_node().Max_dist(); if (max_time < l.end_node().Max_dist()) max_time = l.end_node().Max_dist(); } if (best_link == -1) best_link = l.Id(); else if (l.Pscore() > lat_ptr->link(best_link).Pscore()) best_link = l.Id(); } // ////////////////////////////////////////////////////////////////////// void Cluster::fill_cwords() { for (IdsListIt it = clinks.begin(); it != clinks.end(); it++){ int widx = (lat_ptr->link(*it)).Word_idx(); IntDblMapIt it1 = cwords.find(widx); LnProb linkprob = (lat_ptr->link(*it)).Pscore(); if (it1 == cwords.end()){ cwords[widx] = linkprob; } else{ (*it1).second = LogPlus((*it1).second,linkprob); } } } // //////////////////////////////////////////////////////////////////////// void Cluster::merge_with(const Cluster& c, const int stage) { copy(c.clinks.begin(), c.clinks.end(),inserter(clinks, clinks.end())); if (lat_ptr->link(best_link).Pscore() < lat_ptr->link(c.best_link).Pscore()) best_link = c.best_link; if (stage == 2 || stage == 3 || stage == 4){ for (IntDblMapConstIt it = c.cwords.begin(); it != c.cwords.end(); it++){ IntDblMapIt it1 = cwords.find((*it).first); if (it1 != cwords.end()){ // this is a common word for the two clusters, add their posterior probabilities (*it1).second = LogPlus((*it1).second, (*it).second); } else cwords[(*it).first]=(*it).second; } } if (min_time > c.min_time) min_time = c.min_time; if (max_time < c.max_time) max_time = c.max_time; } // //////////////////////////////////////////////////////////////////////////// bool Cluster::match_start_word(float starttime, unsigned widx){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); float start = lat_ptr->link(id).start_time(); unsigned idx = lat_ptr->link(id).Word_idx(); return (starttime == start && widx == idx); } // /////////////////////////////////////////////////////////////////////////////// unsigned Cluster::wordidx(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).Word_idx(); } // ///////////////////////////////////////////////////////////////////////////////// float Cluster::end_time(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).end_time(); } // ///////////////////////////////////////////////////////////////////////////////// float Cluster::start_time(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).start_time(); } // ///////////////////////////////////////////////////////////////////////////////// int Cluster::approx_end_time(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).end_node().Max_dist(); } // ///////////////////////////////////////////////////////////////////////////////// int Cluster::approx_start_time(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).start_node().Max_dist(); } // ///////////////////////////////////////////////////////////////////////////////// int Cluster::max_dist(){ assert(clinks.size() != 0); LinkId id = *(clinks.begin()); return lat_ptr->link(id).end_node().Max_dist(); } // ///////////////////////////////////////////////////////////////////////////////// unsigned Cluster::compare_less(const Cluster& c, IntIntIntMap& are_less, unsigned MAX_DIST){ IdsList& cl = (IdsList& )c.clinks; // MOD 6/30/2000 - cast added for(IdsListIt it1 = clinks.begin(); it1 != clinks.end(); ++it1){ NodeId firstnode = lat_ptr->link(*it1).End_node_id(); for(IdsListIt it2 = cl.begin(); it2 != cl.end(); ++it2){ NodeId secondnode = lat_ptr->link(*it1).Start_node_id(); if (firstnode == secondnode) return 1; else { if (firstnode > secondnode) continue; else{ IntIntIntMapIt it = are_less.find(pair<int,int>(firstnode,secondnode)); if (it != are_less.end()){ if ((*it).second == 1) return 1; } else { if (MAX_DIST > 1){ bool answer = ((Lattice* )lat_ptr)->less_nodes(firstnode, secondnode, MAX_DIST); // MOD 7/3/2000 - cast added are_less[pair<int,int>(firstnode,secondnode)] = answer; if (answer) return 1; } } } } } } return 0; } // /////////////////////////////////////////////////////////////////// int Cluster::is_less(const Cluster& c, const IntIntIntMap& removed){ IdsList& cl = (IdsList& )c.clinks; // MOD 6/30/2000 - cast added for(IdsListIt it1 = clinks.begin(); it1 != clinks.end(); ++it1){ NodeId endnode1 = lat_ptr->link(*it1).End_node_id(); for(IdsListIt it2 = cl.begin(); it2 != cl.end(); ++it2){ NodeId startnode2 = lat_ptr->link(*it2).Start_node_id(); if (endnode1 == startnode2) return 1; else if (endnode1 > startnode2) continue; else if (((IntIntIntMap&) removed)[(IntInt) pair<int,int>(endnode1,startnode2)]) // MOD 7/3/2000 - cast added return 1; } } return 0; } // /////////////////////////////////////////////////////////////////////////////////// void Cluster::print(const Prons& P, bool print_links, bool print_words){ cout.setf(ios::left, ios::adjustfield); cout << "Cluster no " << setw(6) << cid ; cout << " " << min_time << " -- " << max_time << endl; cout << "-----------------\n"; if (print_links){ if (print_words) cout << "Links:" << endl; for (IdsListConstIt it = clinks.begin(); it != clinks.end(); it++) ((Lattice* )lat_ptr)->link(*it).print_it(P); // MOD 7/3/2000 - cast added } if (print_words){ if (print_links) cout << "Words:" << endl; for (IntDblMapConstIt it = cwords.begin(); it != cwords.end(); it++){ if ((*it).first == -1) cout << " " << "eps" << "\t" << (*it).second << endl; else cout << " " << P.get_word((*it).first) << "\t" << (*it).second << endl; } } cout.setf(ios::internal, ios::adjustfield); } // ///////////////////////////////////////////////////////////////////////////////////////////// ostream& operator<<(ostream& os, const Cluster& c) { os.setf(ios::left, ios::adjustfield); os << "Cluster no " << setw(6) << c.cid << endl; for (IdsListConstIt it = c.clinks.begin(); it != c.clinks.end(); it++) os << c.lat_ptr->link(*it) << endl; for (IntDblMapConstIt it = c.cwords.begin(); it != c.cwords.end(); it++) os << (*it).first << setw(20) << (*it).second << endl; os.setf(ios::internal, ios::adjustfield); assert(os.good()); return os; } // //////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/archive_s3/s3/src/misc/stseg-read.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * stseg.c -- Read and display .stseg file created by s3align. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 19-Jul-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /* "\nCI.8 LC.8 RC.8 POS.3(HI)-ST.5(LO) SCR(32)" */ static char *phone[100]; static int n_phone; static char *posname = "besiu"; static skip_line (FILE *fp) { int c; while (((c = fgetc (fp)) >= 0) && (c != '\n')); } main () { int c, i, k, nf, scr; FILE *fp; char str[1024]; fp = stdin; n_phone = 0; /* Skip version# string */ skip_line (fp); /* Read CI phone names */ for (;;) { for (i = 0;; i++) { if (((c = fgetc(fp)) == ' ') || (c == '\n')) break; str[i] = c; } str[i] = '\0'; if (c == ' ') { phone[n_phone] = (char *) malloc (i+1); strcpy (phone[n_phone], str); n_phone++; } else break; } printf ("%d phones\n", n_phone); /* Skip format line */ skip_line (fp); /* Skip end-comment line */ skip_line (fp); /* Read byteorder magic no. */ fread (&i, sizeof(int), 1, fp); assert (i == 0x11223344); /* Read no. frames */ fread (&nf, sizeof(int), 1, fp); printf ("#frames = %d\n", nf); /* Read state info per frame */ for (i = 0; i < nf; i++) { k = fread (str, sizeof(char), 4, fp); assert (k == 4); k = fread (&scr, sizeof(int), 1, fp); assert (k == 1); c = str[0]; assert ((c >= 0) && (c < n_phone)); printf ("%5d %11d %2d %s", i, scr, str[3] & 0x001f, phone[c]); c = str[1]; if (c != -1) { assert ((c >= 0) && (c < n_phone)); printf (" %s", phone[c]); } c = str[2]; if (c != -1) { assert ((c >= 0) && (c < n_phone)); printf (" %s", phone[c]); } c = (str[3] >> 5) & 0x07; if ((c >= 0) && (c < 4)) printf (" %c", posname[c]); printf ("\n"); } } <file_sep>/SphinxTrain/src/libs/libs2io/areadfloat.c /* ==================================================================== * Copyright (c) 1989-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* 30 May 1989 <NAME> (drf) updated to do byte order conversions when necessary. */ #include <s2/byteorder.h> #include <s3/s2io.h> #include <sys_compat/file.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> /* Macro to byteswap an int variable. x = ptr to variable */ #define MYSWAP_INT(x) *(x) = ((0x000000ff & (*(x))>>24) | \ (0x0000ff00 & (*(x))>>8) | \ (0x00ff0000 & (*(x))<<8) | \ (0xff000000 & (*(x))<<24)) /* Macro to byteswap a float variable. x = ptr to variable */ #define MYSWAP_FLOAT(x) MYSWAP_INT((int *) x) int get_length(char *file, int *byterev) { FILE *fp; int length; int n; struct stat statbuf; *byterev = 0; if (stat(file, &statbuf) < 0) { printf("stat_retry(%s) failed\n", file); return -1; } if ((fp = fopen(file, "rb")) == NULL) { printf("fopen(%s,rb) failed\n", file); return -1; } /* Read #floats in header */ if (fread(&length, sizeof(int), 1, fp) != 1) { fclose (fp); return -1; } /* Check if length matches file size */ if ((length*sizeof(float) + 4) != statbuf.st_size) { n = length; MYSWAP_INT(&n); if ((n*sizeof(float) + 4) != statbuf.st_size) { printf("Header size field: %d(%08x); filesize: %d(%08x)\n", length, length, (int)statbuf.st_size, (int)statbuf.st_size); fflush(stdout); fclose (fp); return -1; } length = n; *byterev = 1; } if (length <= 0) { printf("Header size field: %d\n", length); fflush(stdout); fclose (fp); return -1; } fclose(fp); return length; } int areadfloat (char *file, float **data_ref, int *length_ref) { FILE *fp; int length; int ret, byterev; int offset; float *data; int dummy_length; /* Get the file length and whether the file needs to be byte-reversed */ if ((length = get_length(file, &byterev)) < 0) { return -1; } if ((fp = fopen(file, "rb")) == NULL) { printf("fopen(%s,rb) failed\n", file); return -1; } /* Read #floats in header, so we start reading at the right position */ if (fread(&dummy_length, sizeof(int), 1, fp) != 1) { fclose (fp); return -1; } /* Just get the file size if we were not given a buffer. */ if (data_ref == NULL) { fclose(fp); if (length_ref) *length_ref = length; return length; } if ((data = (float *) calloc (length,sizeof(float))) == NULL) { fprintf (stderr, "areadfloat: %s: can't alloc data\n", file); fflush(stdout); fclose (fp); return -1; } if ((ret = fread(data,sizeof(float),length,fp)) != length) { fprintf (stderr,"areadfloat: %s: expected %d, got %d\n",file,length,ret); fflush(stdout); fclose (fp); free (data); return -1; } fclose (fp); *data_ref = (float *) data; if (byterev==1) for(offset = 0; offset < length; offset++) MYSWAP_FLOAT(*data_ref+offset); *length_ref = length; return length; } int areadfloat_part (char *file, int s_coeff, int e_coeff, float **data_ref, int *length_ref) { static char p_file[MAXPATHLEN] = ""; static FILE *fp = NULL; static int len; static int byterev; int r_len; float *r_buf; int i; int dummy_length; assert(s_coeff <= e_coeff); if (strcmp(file, p_file) != 0) { if (fp) { fclose(fp); } /* Get the file length and whether the file needs to be byte-reversed */ if ((len = get_length(file, &byterev)) < 0) { return -1; } fp = fopen(file, "rb"); if (fp == NULL) { fprintf(stderr, "areadfloat_part: unable to open %s for reading;", file); perror(""); *data_ref = NULL; *length_ref = 0; return -1; } strcpy(p_file, file); if (fread(&dummy_length, sizeof(int), 1, fp) != 1) { fprintf(stderr, "areadfloat_part: unable to read length from %s;", file); perror(""); *data_ref = NULL; *length_ref = 0; return -1; } } if (s_coeff >= len) { fprintf(stderr, "areadfloat_part: start of data beyond end of file\n"); *data_ref = NULL; *length_ref = 0; return 0; } if (e_coeff >= len) { fprintf(stderr, "areadfloat_part: end of data beyond end of file; resetting\n"); e_coeff = len-1; } if (fseek(fp, s_coeff * sizeof(float) + sizeof(int), SEEK_SET) < 0) { fprintf(stderr, "areadfloat_part: seek fail;"); perror(""); fprintf(stderr, "offset == %zu in %s\n", s_coeff * sizeof(float) + sizeof(int), file); *data_ref = NULL; *length_ref = 0; return -1; } r_len = e_coeff - s_coeff + 1; assert(s_coeff + r_len <= len); /* Just get the file size if we were not given a buffer. */ if (data_ref == NULL) { if (length_ref) *length_ref = r_len; return r_len; } r_buf = calloc(r_len, sizeof(float)); if (fread(r_buf, sizeof(float), r_len, fp) != r_len) { fprintf(stderr, "areadfloat_part: unable to read %d coeff @ %d from %s\n", r_len, s_coeff, file); free(r_buf); *data_ref = NULL; *length_ref = 0; return -1; } if (byterev==1) for (i = 0; i < r_len; i++) { MYSWAP_FLOAT(&r_buf[i]); } *data_ref = r_buf; *length_ref = r_len; return r_len; } <file_sep>/archive_s3/s3.2/src/libutil/case.c /* * case.c -- Upper/lower case conversion routines * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 18-Jun-97 <NAME> (<EMAIL>) at Carnegie Mellon * Added strcmp_nocase. Moved UPPER_CASE and LOWER_CASE definitions to .h. * * 16-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #include "case.h" void lcase(register char *cp) { for (; *cp; cp++) *cp = LOWER_CASE(*cp); } void ucase(register char *cp) { for (; *cp; cp++) *cp = UPPER_CASE(*cp); } int32 strcmp_nocase (const char *str1, const char *str2) { char c1, c2; for (;;) { c1 = *(str1++); c1 = UPPER_CASE(c1); c2 = *(str2++); c2 = UPPER_CASE(c2); if (c1 != c2) return (c1-c2); if (c1 == '\0') return 0; } } <file_sep>/SphinxTrain/src/programs/agg_seg/agg_st_seg.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: agg_st_seg.c * * Description: * * Author: * *********************************************************************/ #include "agg_st_seg.h" #include <s3/lexicon.h> #include <s3/corpus.h> #include <s3/segdmp.h> #include <s3/mllr.h> #include <s3/matrix.h> #include <s3/feat.h> #include <s3/ck_seg.h> #include <s3/mk_sseq.h> #include <s3/mk_phone_seq.h> #include <s3/ckd_alloc.h> static void xfrm_feat(float32 ***ainv, float32 **b, float32 **f, uint32 n_stream, const uint32 *veclen) { uint32 s, i, j; float32 *o; for (s = 0; s < n_stream; s++) { for (i = 0; i < veclen[s]; i++) { f[s][i] -= b[s][i]; } o = ckd_calloc(veclen[s], sizeof(float32)); for (i = 0; i < veclen[s]; i++) { for (j = 0; j < veclen[s]; j++) { o[i] += ainv[s][i][j] * f[s][j]; } } for (j = 0; j < veclen[s]; j++) { f[s][j] = o[j]; } ckd_free((void *)o); } } static uint32 * get_sseq(model_def_t *mdef, lexicon_t *lex, uint32 n_frame_in) { char *trans; uint16 *seg; uint32 n_frame; acmod_id_t *phone; uint32 n_phone; uint32 *sseq; corpus_get_sent(&trans); corpus_get_seg(&seg, &n_frame); if (n_frame_in != n_frame) { E_WARN("# frames in feature stream, %u != # frames in seg file %u; skipping\n", n_frame_in, n_frame); ckd_free(seg); ckd_free(trans); return NULL; } mk_phone_seq(&phone, &n_phone, trans, mdef->acmod_set, lex); /* ck_seg(mdef->acmod_set, phone, n_phone, seg, n_frame, corpus_utt()); */ sseq = mk_sseq(seg, n_frame, phone, n_phone, mdef); ckd_free(phone); ckd_free(seg); ckd_free(trans); return sseq; } int agg_st_seg(model_def_t *mdef, lexicon_t *lex, uint32 *ts2cb, int32 *cb2mllr, segdmp_type_t type) { uint32 seq_no; vector_t *mfcc = NULL; uint32 mfc_veclen; uint32 n_frame; vector_t **feat = NULL; uint32 *sseq = NULL; uint32 i, j; uint32 t; int32 sv_feat = FALSE; int32 sv_mfcc = FALSE; int32 sv_vq = FALSE; uint32 n_stream=0; uint32 n_stream_tmp; const uint32 *veclen = 0; const uint32 *veclen_tmp; uint32 n_mllr_cls; float32 ****a = NULL; float32 ****ainv = NULL; float32 ***b = NULL; uint32 mcls; /*eov*/ if (type == SEGDMP_TYPE_FEAT) { sv_feat = TRUE; n_stream = feat_n_stream(); veclen = feat_vecsize(); } else if (type == SEGDMP_TYPE_MFCC) { sv_mfcc = TRUE; } else if (type == SEGDMP_TYPE_VQ) { sv_vq = TRUE; } if (sv_vq) { E_FATAL("VQ aggregation of states not supported\n"); } for (seq_no = corpus_get_begin(); corpus_next_utt(); seq_no++) { if (!(seq_no % 250)) { fprintf(stderr, " [%u]", seq_no); fflush(stderr); } if (sv_feat || sv_mfcc) { if (mfcc) { free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } /* get the MFCC data for the utterance */ if (corpus_get_mfcc(&mfcc, &n_frame, &mfc_veclen) < 0) { E_FATAL("Can't read input features\n"); } } if (sseq != NULL) { ckd_free((void *)sseq); sseq = NULL; } /* read transcript and convert it into a senone sequence */ sseq = get_sseq(mdef, lex, n_frame); if (sseq == NULL) { E_WARN("senone sequence not produced; skipping.\n"); free(mfcc[0]); ckd_free((void *)mfcc); feat_free(feat); continue; } if (sv_feat) { if (feat) { feat_free(feat); feat = NULL; } if (n_frame < 9) { E_WARN("utt %s too short\n", corpus_utt()); if (mfcc) { ckd_free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } continue; } feat = feat_compute(mfcc, &n_frame); if (corpus_has_xfrm()) { if (a) { for (i = 0; i < n_mllr_cls; i++) { for (j = 0; j < n_stream; j++) { ckd_free_2d((void **)a[i][j]); } } ckd_free_2d((void **)a); } if (b) { for (i = 0; i < n_mllr_cls; i++) { for (j = 0; j < n_stream; j++) { ckd_free((void *)b[i][j]); } } } corpus_get_xfrm(&a, &b, &veclen_tmp, &n_mllr_cls, &n_stream_tmp); if (n_stream != n_stream_tmp) { E_FATAL("Feature module # of streams, %u, is inconsistent w/ MLLR matrix, %u\n", n_stream, n_stream_tmp); } /* Free the prior A^(-1) if any */ if (ainv) { for (i = 0; i < n_mllr_cls; i++) { for (j = 0; j < n_stream; j++) { ckd_free_2d((void **)ainv[i][j]); } } ckd_free_2d((void **)ainv); } /* Compute A^(-1) for the current transform */ ainv = (float32 ****)ckd_calloc_2d(n_mllr_cls, n_stream, sizeof(float32 **)); for (i = 0; i < n_mllr_cls; i++) { for (j = 0; j < n_stream; j++) { ainv[i][j] = (float32 **)ckd_calloc_2d(veclen[j], veclen[j], sizeof(float32)); invert(ainv[i][j], a[i][j], veclen[j]); } } } for (t = 0; t < n_frame; t++) { if (corpus_has_xfrm()) { /* determine the MLLR class for the frame */ mcls = cb2mllr[ts2cb[sseq[t]]]; /* Transform the feature space using the inverse MLLR transform */ xfrm_feat(ainv[mcls], b[mcls], feat[t], n_stream, veclen); } segdmp_add_feat(sseq[t], &feat[t], 1); } } else if (sv_mfcc) { for (t = 0; t < n_frame; t++) { segdmp_add_mfcc(sseq[t], &mfcc[t], 1, mfc_veclen); } } } if (mfcc) { free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; } if (feat) { feat_free(feat); feat = NULL; } if (sseq) { ckd_free((void *)sseq); sseq = NULL; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2006/03/27 03:30:14 dhdfu * Fix some minor signedness issues to keep the compiler happy * * Revision 1.5 2005/09/27 02:02:47 arthchan2003 * Check whether utterance is too short in init_gau, bw and agg_seg. * * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/liblapack_lite/test.c #include <stdio.h> #include <s3/mllr.h> #include <s3/matrix.h> #include <s3/ckd_alloc.h> /* cc -I../../../include test.c -L../../../lib.i686-pc-linux-gnu -lutil -lmllr -llapack_lite -lcommon -lio -lm */ int main(int argc, char *argv[]) { float32 **a, **ainv, d; int i, j; a = ckd_calloc_2d(3, 3, sizeof(float32)); ainv = ckd_calloc_2d(3, 3, sizeof(float32)); a[0][0] = a[1][1] = a[2][2] = 2.0; a[1][0] = 1.0; invert(ainv, a, 3); /* Should see: 0.500000 0.000000 0.000000 \ -0.250000 0.500000 0.000000 0.000000 0.000000 0.500000 */ for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { printf("%f ", ainv[i][j]); } printf("\n"); } /* Should see 8.0 */ printf("%f\n", determinant(a, 3)); ckd_free_2d(a); ckd_free_2d(ainv); return 0; } <file_sep>/archive_s3/s3.3/src/tests/feat_dump.c /* ==================================================================== * Copyright (c) 1999-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * feat.c -- Feature vector description and cepstra->feature computation. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 20.Apr.2001 RAH (<EMAIL>, <EMAIL>) * Adding feat_free() to free allocated memory * * 02-Jan-2001 <NAME> (<EMAIL>) at Carnegie Mellon University * Modified feat_s2mfc2feat_block() to handle empty buffers at * the end of an utterance * * 30-Dec-2000 <NAME> (<EMAIL>) at Carnegie Mellon University * Added feat_s2mfc2feat_block() to allow feature computation * from sequences of blocks of cepstral vectors * * 12-Jun-98 <NAME> (<EMAIL>) at Carnegie Mellon University * Major changes to accommodate arbitrary feature input types. Added * feat_read(), moved various cep2feat functions from other files into * this one. Also, made this module object-oriented with the feat_t type. * Changed definition of s2mfc_read to let the caller manage MFC buffers. * * 03-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added unistd.h include. * * 02-Oct-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added check for sf argument to s2mfc_read being within file size. * * 18-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added sf, ef parameters to s2mfc_read(). * * 10-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Added feat_cepsize(). * Added different feature-handling (s2_4x, s3_1x39 at this point). * Moved feature-dependent functions to feature-dependent files. * * 09-Jan-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Moved constant declarations from feat.h into here. * * 04-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ /* * This module encapsulates different feature streams used by the Sphinx group. New * stream types can be added by augmenting feat_init() and providing an accompanying * compute_feat function. It also provides a "generic" feature vector definition for * handling "arbitrary" speech input feature types (see the last section in feat_init()). * In this case the speech input data should already be feature vectors; no computation, * such as MFC->feature conversion, is available or needed. */ #include <libutil/libutil.h> #include "libs3decoder/feat.h" #include "feat_dump.h" #include "fe_dump.h" #include "libs3decoder/bio.h" #include "libs3decoder/cmn.h" #include "libs3decoder/agc.h" #include "s3types.h" #if (! WIN32) #include <sys/file.h> #include <sys/errno.h> #include <sys/param.h> #else #include <fcntl.h> #endif #define FEAT_VERSION "1.0" /* Feature computation module for live mode decoder. Computes featuers * for incoming blocks of data. Maintains a cyclic buffer of size 256 * for computing cross-block deltas etc. Needs explicit begin-utterance * and end-of-utterance flags to be set to indicate the beginning of * a new utterance or the end of an utterance in order to function * properly * The cyclic buffer of size 256 was controlled by using an unsigned * char. Replaced it so that the pointers into the buffer cycle, according * to the variable LIVEBUFBLOCKSIZE. This was, if one day we decide * to change this variable from 256 to something else, the cyclic buffer * will still work. (ebg) */ int32 feat_dump_s2mfc2feat_block(feat_t *fcb, float32 **uttcep, int32 nfr, int32 beginutt, int32 endutt, float32 ***ofeat) { static float32 **feat=NULL; static float32 **cepbuf=NULL; static int32 bufpos; /* RAH 4.15.01 upgraded unsigned char variables to int32*/ static int32 curpos; /* RAH 4.15.01 upgraded unsigned char variables to int32*/ static int32 jp1, jp2, jp3, jf1, jf2, jf3; /* RAH 4.15.01 upgraded unsigned char variables to int32 */ int32 win, cepsize; int32 i, j, nfeatvec, residualvecs; float32 *w, *_w, *f; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; /* If this assert fails, you're risking overwriting elements * in the buffer. -EBG */ assert(nfr < LIVEBUFBLOCKSIZE); win = feat_window_size(fcb); /* CMN stuff */ metricsStart("cmn"); if (fcb->cmn) { /* Only cmn_prior in block computation mode */ cmn_prior (uttcep, fcb->varnorm, nfr, fcb->cepsize, endutt); } metricsStop("cmn"); if (fe_dump) { fe_dump2d_float_frame(fe_dumpfile, uttcep, nfr, fcb->cepsize, "CMN", "CMN_CEPSTRUM"); } /* Feature Extraction */ metricsStart("FeatureExtractor"); if (fcb->cepsize <= 0) E_FATAL("Bad cepsize: %d\n", fcb->cepsize); cepsize = feat_cepsize(fcb); if (feat == NULL) feat = (float32 **)ckd_calloc_2d(LIVEBUFBLOCKSIZE, feat_stream_len(fcb,0), sizeof(float32)); if (cepbuf == NULL){ cepbuf = (float32 **)ckd_calloc_2d(LIVEBUFBLOCKSIZE, cepsize, sizeof(float32)); beginutt = 1; /* If no buffer was present we are beginning an utt */ if (! feat) E_FATAL("Unable to allocate feat ckd_calloc_2d(%ld,%d,%d)\n", LIVEBUFBLOCKSIZE,feat_stream_len(fcb,0),sizeof(float32)); if (! cepbuf) E_FATAL("Unable to allocate cepbuf ckd_calloc_2d(%ld,%d,%d)\n", LIVEBUFBLOCKSIZE,cepsize,sizeof(float32)); E_INFO("Feature buffers initialized to %d vectors\n",LIVEBUFBLOCKSIZE); } residualvecs = 0; if (beginutt) { /* Replicate first frame into the first win frames */ for (i=0;i<win;i++) memcpy(cepbuf[i],uttcep[0],cepsize*sizeof(float32)); /* beginutt = 0; */ /* Removed by <NAME> around 02-Jan-2001 */ /* See History at the top of this file */ bufpos = win; bufpos %= LIVEBUFBLOCKSIZE; curpos = bufpos; jp1 = curpos - 1; jp1 %= LIVEBUFBLOCKSIZE; jp2 = curpos - 2; jp2 %= LIVEBUFBLOCKSIZE; jp3 = curpos - 3; jp3 %= LIVEBUFBLOCKSIZE; jf1 = curpos + 1; jf1 %= LIVEBUFBLOCKSIZE; jf2 = curpos + 2; jf2 %= LIVEBUFBLOCKSIZE; jf3 = curpos + 3; jf3 %= LIVEBUFBLOCKSIZE; residualvecs -= win; } for (i=0;i<nfr;i++){ assert(bufpos < LIVEBUFBLOCKSIZE); memcpy(cepbuf[bufpos++],uttcep[i],cepsize*sizeof(float32)); bufpos %= LIVEBUFBLOCKSIZE; } if (endutt){ /* Replicate last frame into the last win frames */ if (nfr > 0) { for (i=0;i<win;i++) { assert(bufpos < LIVEBUFBLOCKSIZE); memcpy(cepbuf[bufpos++],uttcep[nfr-1],cepsize*sizeof(float32)); bufpos %= LIVEBUFBLOCKSIZE; } } else { int16 tpos = bufpos-1; tpos %= LIVEBUFBLOCKSIZE; for (i=0;i<win;i++) { assert(bufpos < LIVEBUFBLOCKSIZE); memcpy(cepbuf[bufpos++],cepbuf[tpos],cepsize*sizeof(float32)); bufpos %= LIVEBUFBLOCKSIZE; } } residualvecs += win; } /* Create feature vectors */ nfeatvec = 0; nfr += residualvecs; for (i = 0; i < nfr; i++,nfeatvec++){ memcpy (feat[i], cepbuf[curpos], (cepsize) * sizeof(float32)); /* * DCEP: mfc[2] - mfc[-2]; */ f = feat[i] + cepsize; w = cepbuf[jf2]; _w = cepbuf[jp2]; for (j = 0; j < cepsize; j++) f[j] = w[j] - _w[j]; /* D2CEP: (mfc[3] - mfc[-1]) - (mfc[1] - mfc[-3]) */ f += cepsize; w1 = cepbuf[jf3]; _w1 = cepbuf[jp1]; w_1 = cepbuf[jf1]; _w_1 = cepbuf[jp3]; for (j = 0; j < cepsize; j++) { d1 = w1[j] - _w1[j]; d2 = w_1[j] - _w_1[j]; f[j] = d1 - d2; } jf1++; jf2++; jf3++; jp1++; jp2++; jp3++; curpos++; jf1 %= LIVEBUFBLOCKSIZE; jf2 %= LIVEBUFBLOCKSIZE; jf3 %= LIVEBUFBLOCKSIZE; jp1 %= LIVEBUFBLOCKSIZE; jp2 %= LIVEBUFBLOCKSIZE; jp3 %= LIVEBUFBLOCKSIZE; curpos %= LIVEBUFBLOCKSIZE; } *ofeat = feat; metricsStop("FeatureExtractor"); return(nfeatvec); } <file_sep>/SphinxTrain/src/libs/libclust/kdtree.c /* ==================================================================== * Copyright (c) 2005 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: kdtree.c * * Description: * Implement kd-trees using the BBI algorithm as detailed in * <NAME> and <NAME>, "The Bucket Box Intersection * Algorithm for fast approximate evaluation of Diagonal Mixture * Gaussians", Proceedings of ICASSP 1996. * * Author: * <NAME> <<EMAIL>> *********************************************************************/ #include <s3/common.h> #include <s3/kdtree.h> #include <sys_compat/misc.h> #include <string.h> #include <math.h> static int build_kdtree_level(kd_tree_node_t *node, uint32 n_levels); static int compare_float32(const void *a, const void *b); #define KDTREE_VERSION 1 kd_tree_node_t * build_kd_tree(const vector_t *means, const vector_t *variances, uint32 n_density, uint32 n_comp, float32 threshold, int32 n_levels, int32 absolute) { kd_tree_node_t *node; int i, j; if (threshold < 0 || threshold > 1) E_FATAL("Threshold must be between 0 and 1\n"); node = ckd_calloc(1, sizeof(*node)); node->means = means; node->variances = variances; node->n_density = n_density; node->n_comp = n_comp; /* Precompute Gaussian boxes for all components */ node->boxes = (float32 **)ckd_calloc_2d(n_density, n_comp, sizeof(**node->boxes)); if (absolute) { for (i = 0; i < n_density; ++i) { float32 det = n_comp * log(2 * M_PI); for (j = 0; j < n_comp; ++j) det += log(node->variances[i][j]); for (j = 0; j < n_comp; ++j) node->boxes[i][j] = sqrt(-2 * node->variances[i][j] * (threshold + 0.5 * det)); } } else { for (i = 0; i < n_density; ++i) for (j = 0; j < n_comp; ++j) node->boxes[i][j] = sqrt(-2 * node->variances[i][j] * log(threshold)); } node->threshold = threshold; node->n_level = n_levels; /* Initialize projection for root node. */ node->upper = vector_alloc(n_comp); node->lower = vector_alloc(n_comp); for (j = 0; j < n_comp; ++j) { /* BIG NUMBERS */ node->upper[j] = 1e-50; node->lower[j] = 1e+50; } /* Node projection is the union of all Gaussians. */ for (i = 0; i < n_density; ++i) { for (j = 0; j < n_comp; ++j) { float32 a, b; a = node->means[i][j] - node->boxes[i][j]; b = node->means[i][j] + node->boxes[i][j]; if (node->lower[j] > a) node->lower[j] = a; if (node->upper[j] < b) node->upper[j] = b; } } build_kdtree_level(node, n_levels); return node; } static int compare_float32(const void *a, const void *b) { if ((*(float32 *)a) < (*(float32 *)b)) return -1; if ((*(float32 *)a) > (*(float32 *)b)) return 1; return 1; } static int build_kdtree_level(kd_tree_node_t *node, uint32 n_levels) { int i, j, k; uint32 best_split; printf("Gaussian box for node at level %d:\n", n_levels); printf(" ("); for (j = 0; j < node->n_comp; ++j) printf("%.3f ", node->lower[j]); printf(")\n"); printf(" ("); for (j = 0; j < node->n_comp; ++j) printf("%.3f ", node->upper[j]); printf(")\n"); /* Find all Gaussians that intersect the current node's projection. */ node->bbi = ckd_calloc(node->n_density, sizeof(*node->bbi)); for (k = i = 0; i < node->n_density; ++i) { for (j = 0; j < node->n_comp; ++j) { float32 a, b; a = node->means[i][j] - node->boxes[i][j]; b = node->means[i][j] + node->boxes[i][j]; /* Is it ouside the projection on some dimension? */ if (a > node->upper[j] || b < node->lower[j]) { goto next_density; } } /* Otherwise it intersects. */ node->bbi[i] = 1; ++k; next_density: ; } printf("Intersects %d Gaussians: ", k); for (i = 0; i < node->n_density; ++i) if (node->bbi[i]) printf("%d ", i); printf("\n"); /* Terminate the recursion. */ if (--n_levels == 0) return 0; /* Now find the median hyperplane for each component. */ best_split = 0x7fffffff; for (j = 0; j < node->n_comp; ++j) { float32 plane, *axis; uint32 split; axis = ckd_calloc(node->n_density*2, sizeof(*axis)); for (i = 0, k = 0; i < node->n_density; ++i) { float32 a, b; if (node->bbi[i] == 0) continue; a = node->means[i][j] - node->boxes[i][j]; b = node->means[i][j] + node->boxes[i][j]; axis[k++] = a; axis[k++] = b; } qsort(axis, k, sizeof(*axis), compare_float32); /* The hyperplane with the same number of Ls to the * left as Rs to the right is just the median of all * the Ls and Rs. To see why this is, first note that * the total number of Ls is the same as the total * number of Rs which is k/2. Now consider that at any * point n in the array you have l Ls to the the left, * n-l Rs to the left, and thus r = k/2-n-l Rs to the * right. At n=k/2, r = k/2-n-l = l. Therefore k/2 * is the point at which there is the equal number of * Ls to the left as Rs to the right. */ plane = (k & 0x1) ? ((axis[k/2]+axis[k/2+1])/2) : axis[k/2]; free(axis); /* How many Gaussian boxes does this plane split? */ for (split = 0, i = 0; i < node->n_density; ++i) { float32 a, b; if (node->bbi[i] == 0) continue; a = node->means[i][j] - node->boxes[i][j]; b = node->means[i][j] + node->boxes[i][j]; if (a < plane && b > plane) ++split; } printf("Component %d plane %f splits %d boxes\n", j, plane, split); if (split < best_split) { best_split = split; node->split_comp = j; node->split_plane = plane; } } printf("Splitting node at component %d on plane %f\n", node->split_comp, node->split_plane); node->left = ckd_calloc(1, sizeof(*node->left)); memcpy(node->left, node, sizeof(*node->left)); node->left->left = node->left->right = NULL; node->left->n_level = 0; /* Mark it as non-root */ node->left->lower = vector_alloc(node->n_comp); node->left->upper = vector_alloc(node->n_comp); memcpy(node->left->lower, node->lower, sizeof(*node->left->lower) * node->n_comp); memcpy(node->left->upper, node->upper, sizeof(*node->left->upper) * node->n_comp); node->left->upper[node->split_comp] = node->split_plane; node->right = ckd_calloc(1, sizeof(*node->right)); memcpy(node->right, node, sizeof(*node->right)); node->right->left = node->right->right = NULL; node->right->n_level = 0; /* Mark it as non-root */ node->right->lower = vector_alloc(node->n_comp); node->right->upper = vector_alloc(node->n_comp); memcpy(node->right->lower, node->lower, sizeof(*node->right->lower) * node->n_comp); memcpy(node->right->upper, node->upper, sizeof(*node->right->upper) * node->n_comp); node->right->lower[node->split_comp] = node->split_plane; build_kdtree_level(node->left, n_levels); build_kdtree_level(node->right, n_levels); return 0; } void free_kd_tree(kd_tree_node_t *tree) { if (tree == NULL) return; free_kd_tree(tree->left); free_kd_tree(tree->right); if (tree->n_level) ckd_free(tree->boxes); ckd_free(tree->bbi); ckd_free(tree->lower); ckd_free(tree->upper); ckd_free(tree); } typedef struct bbi_bucket_s bbi_bucket_t; struct bbi_bucket_s { uint32 idx; float32 box; }; static int compare_boxes(const void *a, const void *b) { if (((bbi_bucket_t *)a)->box < ((bbi_bucket_t *)b)->box) return -1; if (((bbi_bucket_t *)a)->box > ((bbi_bucket_t *)b)->box) return 1; return 0; } static int32 write_bbi_list(FILE *fp, kd_tree_node_t *node) { int i, j, k; bbi_bucket_t *bbi; bbi = ckd_calloc(node->n_density, sizeof(*bbi)); for (i = 0, k = 0; i < node->n_density; ++i) { if (node->bbi[i]) { float64 box, inter; /* Sort them by the ratio of the size of the * Gaussian box to the size of its overlap * with the current node's projection. */ bbi[k].idx = i; box = inter = 0.0; for (j = 0; j < node->n_comp; ++j) box += log(node->boxes[i][j] * 2); for (j = 0; j < node->n_comp; ++j) { float32 a, b; a = node->means[i][j] - node->boxes[i][j]; b = node->means[i][j] + node->boxes[i][j]; if (b >= node->upper[j]) inter += log(node->upper[j] - a); else if (a <= node->lower[j]) inter += log(b - node->lower[j]); else inter += log(node->boxes[i][j] * 2); } bbi[k].box = (float32)(box - inter); ++k; } } qsort(bbi, k, sizeof(*bbi), compare_boxes); for (i = 0; i < k; ++i) fprintf(fp, "%d ", bbi[i].idx); return 0; } static int32 write_kd_nodes(FILE *fp, kd_tree_node_t *node, uint32 level) { if (node == NULL) return 0; fprintf(fp, "NODE %d\n", level); fprintf(fp, "split_comp %d\n", node->split_comp); fprintf(fp, "split_plane %f\n", node->split_plane); fprintf(fp, "bbi "); write_bbi_list(fp, node); fprintf(fp, "\n\n"); write_kd_nodes(fp, node->left, level-1); write_kd_nodes(fp, node->right, level-1); return 0; } int32 write_kd_trees(const char *outfile, kd_tree_node_t **trees, uint32 n_trees) { FILE *fp; uint32 i; if ((fp = fopen(outfile, "w")) == NULL) { E_ERROR_SYSTEM("Failed to open %s", outfile); return -1; } fprintf(fp, "KD-TREES\n"); fprintf(fp, "version %d\n", KDTREE_VERSION); fprintf(fp, "n_trees %d\n", n_trees); for (i = 0; i < n_trees; ++i) { fprintf(fp, "TREE %d\n", i); fprintf(fp, "n_density %d\n", trees[i]->n_density); fprintf(fp, "n_comp %d\n", trees[i]->n_comp); fprintf(fp, "n_level %d\n", trees[i]->n_level); fprintf(fp, "threshold %f\n", trees[i]->threshold); /* Output the nodes in depth-first ordering */ write_kd_nodes(fp, trees[i], trees[i]->n_level); fprintf(fp, "\n"); } fclose(fp); return 0; } static int32 read_tree_int(FILE *fp, const char *name, uint32 *out, int32 optional) { char line[256]; int n; n = fscanf(fp, "%255s %u", line, out); if ((optional == 0 && n != 2) || strcmp(line, name)) { E_ERROR("%s not found: %d %s %u\n", name, n, line, out); return -1; } return n; } static int32 read_tree_float(FILE *fp, const char *name, float32 *out, int32 optional) { char line[256]; int n; n = fscanf(fp, "%255s %f", line, out); if ((optional == 0 && n != 2) || strcmp(line, name)) { E_ERROR("%s not found: %d %s %f\n", name, n, line, out); return -1; } return n; } int32 read_kd_nodes(FILE *fp, kd_tree_node_t *node, uint32 level) { uint32 n; int i; if (read_tree_int(fp, "NODE", &n, FALSE) < 0) return -1; if (n != level) { E_ERROR("Levels for node don't match (%d != %d)\n", n, level); return -1; } if (read_tree_int(fp, "split_comp", &node->split_comp, FALSE) < 0) return -1; if (read_tree_float(fp, "split_plane", &node->split_plane, FALSE) < 0) return -1; if ((i = read_tree_int(fp, "bbi", &n, TRUE)) < 0) return -1; node->bbi = ckd_calloc(node->n_density, sizeof(*node->bbi)); if (i > 1) { if (n >= node->n_density) { E_ERROR("BBI Gaussian %d out of range! %d\n", n); return -1; } node->bbi[n] = 1; while ((i = fscanf(fp, "%d", &n))) { if (feof(fp)) break; if (n >= node->n_density) { E_ERROR("BBI Gaussian %d out of range! %d\n", n, i); return -1; } node->bbi[n] = 1; } } if (level == 1) return 0; node->left = ckd_calloc(1, sizeof(*node->left)); node->left->n_density = node->n_density; node->left->n_comp = node->n_comp; if (read_kd_nodes(fp, node->left, level-1) < 0) return -1; node->right = ckd_calloc(1, sizeof(*node->left)); node->right->n_density = node->n_density; node->right->n_comp = node->n_comp; if (read_kd_nodes(fp, node->right, level-1) < 0) return -1; return 0; } int32 read_kd_trees(const char *infile, kd_tree_node_t ***out_trees, uint32 *out_n_trees) { FILE *fp; char line[256]; int n, version; uint32 i, m; if ((fp = fopen(infile, "r")) == NULL) { E_ERROR_SYSTEM("Failed to open %s", infile); return -1; } n = fscanf(fp, "%256s", line); if (n != 1 || strcmp(line, "KD-TREES")) { E_ERROR("Doesn't appear to be a kd-tree file: %s\n"); return -1; } n = fscanf(fp, "%256s %d", line, &version); if (n != 2 || strcmp(line, "version") || version > KDTREE_VERSION) { E_ERROR("Unsupported kd-tree file format %s %d\n", line, version); return -1; } if (read_tree_int(fp, "n_trees", out_n_trees, FALSE) < 0) return -1; *out_trees = ckd_calloc(*out_n_trees, sizeof(kd_tree_node_t **)); for (i = 0; i < *out_n_trees; ++i) { kd_tree_node_t *tree; if (read_tree_int(fp, "TREE", &m, FALSE) < 0) goto error_out; if (m != i) { E_ERROR("Tree number %u out of sequence\n", m); goto error_out; } (*out_trees)[i] = tree = ckd_calloc(1, sizeof(*tree)); if (read_tree_int(fp, "n_density", &tree->n_density, FALSE) < 0) goto error_out; if (read_tree_int(fp, "n_comp", &tree->n_comp, FALSE) < 0) goto error_out; if (read_tree_int(fp, "n_level", &tree->n_level, FALSE) < 0) goto error_out; if (read_tree_float(fp, "threshold", &tree->threshold, FALSE) < 0) goto error_out; if (read_kd_nodes(fp, tree, tree->n_level) < 0) goto error_out; } fclose(fp); return 0; error_out: fclose(fp); for (i = 0; i < *out_n_trees; ++i) { free_kd_tree((*out_trees)[i]); (*out_trees)[i] = NULL; } ckd_free(*out_trees); *out_trees = NULL; return -1; } <file_sep>/SphinxTrain/scripts_pl/sphinxDocGen.sh.in #!/bin/bash mkdir -p tmpdoc/ for i in agg_seg bldtree bw cp_parm delint dict2tri inc_comp \ init_gau init_mixw kmeans_init make_quests mixw_interp \ mk_flat mk_mdef_gen mk_mllr_class mk_model_def map_adapt \ mk_s2cb mk_s2hmm mk_s2phone mk_s2phonemap mk_s2sendump \ mk_s3gau mk_s3mixw mk_ts2cb mllr_solve mllr_transform \ norm param_cnt printp prunetree tiestate QUICK_COUNT do echo $i ./bin.@host@/$i > tmp 2>&1 ./bin.@host@/$i -help yes > help ./bin.@host@/$i -example yes > example @PERL@ ./scripts_pl/texFormat.pl tmp tmpdoc/${i}.tex $i help example done rm tmp help example<file_sep>/archive_s3/s3.0/src/libmain/lm.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * lm.h - Disk/memory based word-trigram backoff LM * * * HISTORY * * 24-Jun-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Added lm_t.log_bg_seg_sz and lm_t.bg_seg_sz. * * 13-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Created from original S3 version. */ #ifndef _LIBMAIN_LM_H_ #define _LIBMAIN_LM_H_ #include "s3types.h" /* Log quantities represented in either floating or integer format */ typedef union { float32 f; int32 l; } lmlog_t; typedef struct { s3wid_t dictwid; /* Dictionary word id, or BAD_WID if unknown. However, the LM module merely sets this field to BAD_WID. It is upto the application to fill in this field (HACK!!), so that this module can be independent of a dictionary. */ lmlog_t prob; lmlog_t bowt; int32 firstbg; /* 1st bigram entry on disk */ } ug_t; typedef struct { s3lmwid_t wid; /* LM wid (index into lm_t.ug) */ uint16 probid; uint16 bowtid; uint16 firsttg; /* 1st trigram entry on disk (see tg_segbase below) */ } bg_t; typedef struct { s3lmwid_t wid; /* LM wid (index into lm_t.ug) */ uint16 probid; } tg_t; /* * Management of in-memory bigrams. Not used if all bigrams in memory. */ typedef struct { bg_t *bg; /* Bigrams for a specific unigram; see lm_t.membg */ int32 used; /* Whether used since last lm_reset. If not used, at the next lm_reset bg are freed */ } membg_t; /* * The following trigram information cache eliminates most traversals of 1g->2g->3g * tree to locate trigrams for a given bigram (w1,w2). The organization is optimized * for locality of access. All bigrams (*,w2) for a given w2, for which trigrams have * been accessed "recently", form a linear linked list, pointed to by lm_t.tginfo[w2]. * If disk-based, all trigrams for the given bg loaded upon request. Cached info (and * tg if disk-based) freed at lm_reset if not used since last such reset. */ typedef struct tginfo_s { s3lmwid_t w1; /* w1 component of bigram w1,w2. All bigrams with same w2 linked together. */ int32 n_tg; /* #tg for parent bigram w1,w2 */ tg_t *tg; /* Trigrams for w1,w2 */ int32 bowt; /* tg bowt for w1,w2 */ int32 used; /* whether used since last lm_reset */ struct tginfo_s *next; /* Next w1 with same parent w2 */ } tginfo_t; /* * To conserve space, bg/tg probs/ptrs kept in many tables. Since the number of * distinct prob values << #bg/#tg, these table indices can be easily fit into * 16 bits. bgprob and bgbowt are such indices. The firsttg entry for a bigram * is harder. It is supposed to be the index of the first trigram entry for each * bigram. But #tg can be >> 2^16. Hence the following segmentation scheme: * Partition bigrams into segments of lm_t.bg_seg_sz consecutive entries, such that * #trigrams in each segment <= 2**16 (the corresponding trigram segment). The * bigram_t.firsttg value is then a 16-bit relative index within the trigram * segment. A separate table--lm_t.tg_segbase--has the absolute index of the * 1st trigram for each segment. */ /* Default values for lm_t.log_bg_seg.sz */ #define LOG2_BG_SEG_SZ 9 #define BG_SEG_SZ (1 << (LOG2_BG_SEG_SZ)) /* * The language model. * All unigrams are read into memory on initialization. * Bigrams and trigrams read in on demand. */ typedef struct lm_s { int32 n_ug; /* #unigrams in LM */ int32 n_bg; /* #bigrams in entire LM */ int32 n_tg; /* #trigrams in entire LM */ int32 max_ug; /* To which n_ug can grow with dynamic addition of words */ char **wordstr; /* The LM word list (in unigram order) */ int32 log_bg_seg_sz;/* See big comment above */ int32 bg_seg_sz; ug_t *ug; /* Unigrams */ bg_t *bg; /* NULL iff disk-based */ tg_t *tg; /* NULL iff disk-based */ membg_t *membg; /* membg[w1] = bigrams for lm wid w1 (used iff disk-based) */ tginfo_t **tginfo; /* tginfo[w2] = fast trigram access info for bigrams (*,w2) */ lmlog_t *bgprob; /* Table of actual bigram probs */ lmlog_t *tgprob; /* Table of actual trigram probs */ lmlog_t *tgbowt; /* Table of actual trigram backoff weights */ int32 *tg_segbase; /* tg_segbase[i>>lm_t.log_bg_seg_sz] = index of 1st trigram for bigram segment (i>>lm_t.log_bg_seg_sz) */ int32 n_bgprob; int32 n_tgprob; int32 n_tgbowt; FILE *fp; int32 byteswap; /* Whether this file is in the WRONG byte order */ int32 bgoff; /* BG and TG offsets into DMP file (used iff disk-based) */ int32 tgoff; float32 lw; /* Language weight currently in effect for this LM */ int32 wip; /* logs3(word insertion penalty) in effect for this LM */ /* Statistics */ int32 n_bg_fill; /* #bg fill operations */ int32 n_bg_inmem; /* #bg in memory */ int32 n_bg_score; /* #bg_score operations */ int32 n_bg_bo; /* #bg_score ops backed off to ug */ int32 n_tg_fill; /* Similar stats for trigrams */ int32 n_tg_inmem; int32 n_tg_score; int32 n_tg_bo; } lm_t; /* * Read an LM (dump) file; return pointer to LM structure created. */ lm_t *lm_read (char *file, /* In: LM file being read */ float64 lw, /* In: Language weight */ float64 wip); /* In: Word insertion penalty */ /* * Return trigram followers for given two words. Both w1 and w2 must be valid. * Return value: #trigrams in returned list. */ int32 lm_tglist (lm_t *lmp, /* In: LM being queried */ s3lmwid_t w1, /* In: LM word id of the first of a 2-word history */ s3lmwid_t w2, /* In: LM word id of the second of the 2-word history */ tg_t **tg, /* Out: *tg = array of trigrams for <w1,w2> */ int32 *bowt); /* Out: *bowt = backoff-weight for <w1, w2> */ /* * Return the bigram followers for the given word w. * Return value: #bigrams in returned list. */ int32 lm_bglist (lm_t *lmp, /* In: LM being queried */ s3lmwid_t w, /* In: LM word id of the 1-word history */ bg_t **bg, /* Out: *bg = array of bigrams for w */ int32 *bowt); /* Out: *bowt = backoff-weight for w */ /* Return the unigrams in LM. Return value: #unigrams in returned list. */ int32 lm_uglist (lm_t *lmp, /* In: LM being queried */ ug_t **ug); /* Out: *ug = unigram array */ /* Return unigram score for the given word */ int32 lm_ug_score (lm_t *lmp, s3lmwid_t w); /* * Return bigram score for the given two word sequence. If w1 is BAD_LMWID, return * lm_ug_score (w2). */ int32 lm_bg_score (lm_t *lmp, s3lmwid_t w1, s3lmwid_t w2); /* * Return trigram score for the given three word sequence. If w1 is BAD_LMWID, return * lm_bg_score (w2, w3). If both w1 and w2 are BAD_LMWID, return lm_ug_score (w3). */ int32 lm_tg_score (lm_t *lmp, s3lmwid_t w1, s3lmwid_t w2, s3lmwid_t w3); /* * Set the language-weight and insertion penalty parameters for the LM, after revoking * any earlier set of such parameters. */ void lm_set_param (lm_t *lm, float64 lw, float64 wip); /* LM cache related */ void lm_cache_reset (lm_t *lmp); void lm_cache_stats_dump (lm_t *lmp); /* Macro versions of access functions */ #define LM_TGPROB(lm,tgptr) ((lm)->tgprob[(tgptr)->probid].l) #define LM_BGPROB(lm,bgptr) ((lm)->bgprob[(bgptr)->probid].l) #define LM_UGPROB(lm,ugptr) ((ugptr)->prob.l) #define LM_RAWSCORE(lm,score) ((score - (lm)->wip) / ((lm)->lw)) #endif <file_sep>/archive_s3/s3/src/misc/dag.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * dag.h -- DAG structure containing word instances and edges defining adjacency. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 07-Feb-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _DAG_H_ #define _DAG_H_ #include <libutil/libutil.h> #include <main/s3types.h> #include <main/dict.h> /* * DAG structure representation of word lattice. A unique <wordid,startframe> is a node. * Edges are formed if permitted by time adjacency. */ typedef struct dagnode_s { s3wid_t wid; int32 seqid; /* Running sequence no. for identification */ int32 reachable; /* Whether DAG end points reachable from here */ s3frmid_t sf; /* Start frame for this occurrence of wid */ s3frmid_t fef, lef; /* First and last end frames */ struct dagnode_s *next; /* Next in linear list of allocated nodes */ struct daglink_s *succlist; /* List of successor nodes (adjacent in time) */ struct daglink_s *predlist; /* List of preceding nodes (adjacent in time) */ } dagnode_t; /* * A DAG node can have several successor or predecessor nodes, each represented by a link */ typedef struct daglink_s { dagnode_t *src; /* Source node of link */ dagnode_t *dst; /* Target node of link */ struct daglink_s *next; /* Next in same dagnode_t.succlist or dagnode_t.predlist */ } daglink_t; /* Summary of DAG structure information */ typedef struct { dagnode_t **node_sf; /* node_sf[f] = list of dagnodes with start time = f */ daglink_t entry; /* Entering (<s>,0) */ daglink_t exit; /* Exiting (</s>,finalframe) */ int32 nfrm; /* #Frames in utterance */ int32 nnode; /* #Nodes in DAG */ int32 nlink; /* #Links in DAG */ } dag_t; /* * Mark d and all successors along path to end as reachable. */ void dag_reachable_fwd (dagnode_t *d); /* * Mark d and all predecessors along path to root as reachable. */ void dag_reachable_bwd (dagnode_t *d); /* * Add a dummy node with the given wid to the end of the DAG; link all ending nodes to it. */ void dag_append_sentinel (dag_t *dag, s3wid_t wid); /* * Link two DAG nodes: dst is in succlist of src and src is in predlist of dst. */ void dag_link (dagnode_t *src, dagnode_t *dst); /* * Destroy the given DAG and deallocate its space. */ void dag_destroy (dag_t *dag); #endif <file_sep>/SphinxTrain/src/programs/bw/baum_welch.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: baum_welch.c * * Description: * This file contains the code to update the HMM reestimation * equations given a model and an observation sequence of * in a collection of multiple observation sequences (i.e. an * utterance in a corpus of utterances). * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "baum_welch.h" #include "forward.h" #include "viterbi.h" #include "backward.h" #include "accum.h" #include <s3/state_seq.h> #include <s3/model_inventory.h> #include <s3/ckd_alloc.h> #include <s3/profile.h> #include <s3/corpus.h> #include <s3/cmd_ln.h> #include <s3/s2_param.h> #include <s3/s3.h> #include <math.h> #include <assert.h> #include <string.h> /********************************************************************* * * Function: baum_welch_update() * * Description: * This routine updates the HMM reestimation equations given a * model and an observation sequence of in a collection of * multiple observation sequences (i.e. an utterance in a * corpus of utterances). * * Function Inputs: * float64 *log_forw_prob- * log() of the probability of observation sequence * given the model. * * vector_t **feature - * The observed feature vectors. feature[t][f] * is the feature vector for time t, feature f. * * uint32 n_obs - * The number of observations. Defines the * number of rows in the feature matrix. * * state_t *state - * The set of HMM states of the HMM to train. * * uint32 n_state - * The number of states present in the HMM. * * model_inventory_t *inv - * A structure containing pointers to the initial * model parameters and reestimation sums. * * int32 mixw_reest - * A boolean value to indicate whether mixing weights * should be reestimated. * * int32 tmat_reest - * A boolean value to indicate whether transition matrices * should be reestimated. * * int32 mean_reest - * A boolean value to indicate whether means * should be reestimated. * * int32 var_reest - * A boolean value to indicate whether variances * should be reestimated. * * s3phseg_t *phseg - * An optional phone segmentation to use to constrain the * forward lattice. * Global Inputs: * None * * Return Values: * * Global Outputs: * None * *********************************************************************/ int32 baum_welch_update(float64 *log_forw_prob, vector_t **feature, uint32 n_obs, state_t *state, uint32 n_state, model_inventory_t *inv, float64 a_beam, float64 b_beam, float32 spthresh, s3phseg_t *phseg, int32 mixw_reest, int32 tmat_reest, int32 mean_reest, int32 var_reest, int32 pass2var, int32 var_is_full, FILE *pdumpfh, float32 ***lda) { float64 *scale = NULL; float64 **dscale = NULL; float64 **active_alpha; uint32 **active_astate; uint32 **bp; uint32 *n_active_astate; float64 log_fp; /* accumulator for the log of the probability * of observing the input given the model */ uint32 t; /* time */ int ret; timing_t *fwd_timer = NULL; timing_t *bwd_timer = NULL; timing_t *rstu_timer = NULL; uint32 i,j; /* caller must ensure that there is some non-zero amount of work to be done here */ assert(n_obs > 0); assert(n_state > 0); fwd_timer = timing_get("fwd"); bwd_timer = timing_get("bwd"); rstu_timer = timing_get("rstu"); scale = (float64 *)ckd_calloc(n_obs, sizeof(float64)); dscale = (float64 **)ckd_calloc(n_obs, sizeof(float64 *)); n_active_astate = (uint32 *)ckd_calloc(n_obs, sizeof(uint32)); active_alpha = (float64 **)ckd_calloc(n_obs, sizeof(float64 *)); active_astate = (uint32 **)ckd_calloc(n_obs, sizeof(uint32 *)); bp = (uint32 **)ckd_calloc(n_obs, sizeof(uint32 *)); /* Compute the scaled alpha variable and scale factors * for all states and time subject to the pruning constraints */ if (fwd_timer) timing_start(fwd_timer); /* * Debug? * E_INFO("Before Forward search\n"); */ ret = forward(active_alpha, active_astate, n_active_astate, bp, scale, dscale, feature, n_obs, state, n_state, inv, a_beam, phseg); #if BW_DEBUG for (i=0 ; i < n_obs;i++){ E_INFO("Number of active states %d at time %d\n",n_active_astate[i],i); E_INFO("Scale of time %d is %e \n",i,scale[i]); for(j=0 ; j < n_active_astate[i];j++){ E_INFO("Active state: %d Active alpha: %e\n",active_astate[i][j], active_alpha[i][j]); } } i=0; j=0; #endif /* Dump a phoneme segmentation if requested */ if (cmd_ln_str("-outphsegdir")) { const char *phsegdir; char *segfn, *uttid; phsegdir = cmd_ln_str("-outphsegdir"); uttid = (cmd_ln_int32("-outputfullpath") ? corpus_utt_full_name() : corpus_utt()); segfn = ckd_calloc(strlen(phsegdir) + 1 + strlen(uttid) + strlen(".phseg") + 1, 1); strcpy(segfn, phsegdir); strcat(segfn, "/"); strcat(segfn, uttid); strcat(segfn, ".phseg"); write_phseg(segfn, inv, state, active_astate, n_active_astate, n_state, n_obs, active_alpha, scale, bp); ckd_free(segfn); } if (fwd_timer) timing_stop(fwd_timer); if (ret != S3_SUCCESS) { /* Some problem with the utterance, release per utterance storage and * forget about adding the utterance accumulators to the global accumulators */ goto error; } /* Compute the scaled beta variable and update the reestimation * sums */ if (bwd_timer) timing_start(bwd_timer); #if BW_DEBUG E_INFO("Before Backward search\n"); #endif ret = backward_update(active_alpha, active_astate, n_active_astate, scale, dscale, feature, n_obs, state, n_state, inv, b_beam, spthresh, mixw_reest, tmat_reest, mean_reest, var_reest, pass2var, var_is_full, pdumpfh, lda); if (bwd_timer) timing_stop(bwd_timer); if (ret != S3_SUCCESS) { /* Some problem with the utterance, release per utterance storage and * forget about adding the utterance accumulators to the global accumulators */ goto error; } #if BW_DEBUG E_INFO("Before Global Accumulation\n"); #endif /* If no error was found in the forward or backward procedures, * add the resulting utterance reestimation accumulators to the * global reestimation accumulators */ if (rstu_timer) timing_start(rstu_timer); accum_global(inv, state, n_state, mixw_reest, tmat_reest, mean_reest, var_reest, var_is_full); if (rstu_timer) timing_stop(rstu_timer); for (i = 0; i < n_active_astate[n_obs-1] && active_astate[n_obs-1][i] != (n_state-1); i++); assert(i < n_active_astate[n_obs-1]); /* Calculate log[ p( O | \lambda ) ] */ assert(active_alpha[n_obs-1][i] > 0); log_fp = log(active_alpha[n_obs-1][i]); for (t = 0; t < n_obs; t++) { assert(scale[t] > 0); log_fp -= log(scale[t]); for (j = 0; j < inv->gauden->n_feat; j++) { log_fp += dscale[t][j]; } } *log_forw_prob = log_fp; ckd_free((void *)scale); ckd_free(n_active_astate); for (i = 0; i < n_obs; i++) { ckd_free((void *)active_alpha[i]); ckd_free((void *)active_astate[i]); ckd_free((void *)dscale[i]); ckd_free((void *)bp[i]); } ckd_free((void *)active_alpha); ckd_free((void *)active_astate); ckd_free((void **)dscale); return S3_SUCCESS; error: ckd_free((void *)scale); for (i = 0; i < n_obs; i++) { if (dscale[i]) ckd_free((void *)dscale[i]); } ckd_free((void **)dscale); ckd_free(n_active_astate); for (i = 0; i < n_obs; i++) { ckd_free((void *)active_alpha[i]); ckd_free((void *)active_astate[i]); ckd_free((void *)bp[i]); } ckd_free((void *)active_alpha); ckd_free((void *)active_astate); E_ERROR("%s ignored\n", corpus_utt_brief_name()); return S3_ERROR; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.9 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.8 2005/03/30 16:43:46 egouvea * Commented E_INFO calls that seemed to be there for debug/trace purpose only, not for a user * * Revision 1.7 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.6 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.4 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.14 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.13 1996/07/29 16:13:03 eht * - MLLR reestimation * - float64 rep for alpha, outprob, scale * - Got rid of 4D den and den_idx arrays as that they were using up * too much memory. * * Revision 1.12 1996/03/26 13:49:54 eht * - Fixed beam bug where defined as float32 rather than float64 * - Deal w/ case when # of densities referenced per utterances is much less than * the total # of densities to train * * Revision 1.11 1996/03/05 12:47:45 eht * Fixed forward timer bug * * Revision 1.10 1996/03/04 17:32:07 eht * Add cpu usage counters * * Revision 1.9 1996/02/02 17:38:17 eht * Added alpha and beta beams. * * Revision 1.8 1996/01/26 18:23:49 eht * Local accumulators are now freed and reeallocated after each utterance. * No longer a need to clear them. * * Revision 1.7 1995/12/14 19:46:38 eht * - Added type casts for pointer types so that ANSI-hyper compilers desist about * generating warning messages. * - Added a clr of the Gaussian density accumulators when an error condition * happens. Before the next utterance would get (possible) garbage from the * prior utterance. * * Revision 1.6 1995/11/30 20:47:43 eht * Allow a tmat_reest flag to be given and passed to lower level functions * * Revision 1.5 1995/10/10 12:43:50 eht * Changed to use <s3/prim_type.h> * * Revision 1.4 1995/10/09 14:55:33 eht * Change interface to new ckd_alloc routines * * Revision 1.3 1995/09/14 15:05:41 eht * Update comments * * Revision 1.2 1995/08/09 20:16:50 eht * Fix where Gaussian density reestimation accumulators were not cleared * * Revision 1.1 1995/06/02 20:41:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/matrix.h /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: matrix.h * * Description: Matrix and linear algebra functions * * Author: * *********************************************************************/ #ifndef MATRIX_H #define MATRIX_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/prim_type.h> #include <s3/vector.h> void norm_3d(float32 ***arr, uint32 d1, uint32 d2, uint32 d3); void accum_3d(float32 ***out, float32 ***in, uint32 d1, uint32 d2, uint32 d3); void floor_3d(float32 ***m, uint32 d1, uint32 d2, uint32 d3, float32 floor); void floor_nz_3d(float32 ***m, uint32 d1, uint32 d2, uint32 d3, float32 floor); void floor_nz_1d(float32 *v, uint32 d1, float32 floor); void band_nz_1d(float32 *v, uint32 d1, float32 band); /* These can be vanishingly small hence the float64 */ float64 determinant(float32 **a, int32 len); /* Returns S3_ERROR for a singular matrix. */ int32 invert(vector_t *ainv, vector_t *a, int32 len); void outerproduct(vector_t *a, vector_t x, vector_t y, int32 len); int32 eigenvectors(float32 **a, float32 *out_ur, float32 *out_ui, float32 **out_vr, float32 **out_vi, int32 len); void matrixmultiply(vector_t *c, /* = */ vector_t *a, /* * */ vector_t *b, int32 m, /**< #rows of a. */ int32 n, /**< #cols of b. */ int32 k /**< #cols of a, #rows of b. */ ); void scalarmultiply(vector_t *a, float32 x, int32 m, int32 n); void matrixadd(vector_t *a, vector_t *b, int32 m, int32 n); #ifdef __cplusplus } #endif #endif /* MATRIX_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:39:10 eht * Initial revision * * */ <file_sep>/share/cepview/cepview.c /* ==================================================================== * Copyright (c) 1994-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * * * HISTORY * * circa 1994 <NAME> at Carnegie Mellon * Created. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #define TRUE (1) #define FALSE (0) #define IO_ERR (-1) /* Macro to byteswap an int variable. x = ptr to variable */ #define SWAP_INT(x) *(x) = ((0x000000ff & (*(x))>>24) | \ (0x0000ff00 & (*(x))>>8) | \ (0x00ff0000 & (*(x))<<8) | \ (0xff000000 & (*(x))<<24)) /* Macro to byteswap a float variable. x = ptr to variable */ #define SWAP_FLOAT(x) SWAP_INT((int *) x) #define NUM_COEFF (13) #define DISPLAY_SIZE (10) #define QUIT(X) {printf X; fflush(stdout); exit(1);} #define CMD_USAGE "Usage: %s [-i <# input coeff>] [-d <# display coeff>] <cepfile>\n" char **alloc2d(int dim1, int dim2, int size); int read_cep(char *file, float ***cep, int *nframes, int numcep); main(int argc, char *argv[]) { int i, j, offset; int len, vsize, dsize, column; float *z, **cep; char cepfile[1024]; if (argc == 1) QUIT((CMD_USAGE, argv[0])) vsize = NUM_COEFF; dsize = DISPLAY_SIZE; for (i = 1; i < argc - 1; ++i) { if (argv[i][0] != '-') QUIT((CMD_USAGE, argv[0])) switch (argv[i][1]) { case 'i': case 'I': vsize = atoi (argv[++i]); break; case 'd': case 'D': dsize = atoi (argv[++i]); break; default: QUIT((CMD_USAGE, argv[0])) break; } } strcpy(cepfile, argv[argc-1]); if (read_cep(cepfile,&cep,&len,vsize) == IO_ERR) QUIT(("ERROR opening %s for reading\n",cepfile)) z = cep[0]; printf("%d frames\n", len); offset = 0; column = (vsize > dsize) ? dsize : vsize; for (i = 0; i < len; ++i) { for ( j =0 ; j < column; ++j) printf("%7.3f ", z[offset + j]); printf("\n"); offset += vsize; } } int read_cep(char *file, float***cep, int *numframes, int cepsize) { FILE *fp; int n_float; struct stat statbuf; int i, n, byterev, sf, ef; float **mfcbuf; if (stat(file, &statbuf) < 0) { printf("stat_retry(%s) failed\n", file); return -1; } if ((fp = fopen(file, "rb")) == NULL) { printf("fopen(%s,rb) failed\n", file); return -1; } /* Read #floats in header */ if (fread(&n_float, sizeof(int), 1, fp) != 1) { fclose (fp); return -1; } /* Check if n_float matches file size */ byterev = FALSE; if ((int)(n_float*sizeof(float) + 4) != statbuf.st_size) { n = n_float; SWAP_INT(&n); if ((int)(n*sizeof(float) + 4) != statbuf.st_size) { printf("Header size field: %d(%08x); filesize: %d(%08x)\n", n_float,n_float,(int)statbuf.st_size,(int)statbuf.st_size); fclose (fp); return -1; } n_float = n; byterev = TRUE; } if (n_float <= 0) { printf("Header size field: %d\n", n_float); fclose (fp); return -1; } /* n = #frames of input */ n = n_float/cepsize; if (n * cepsize != n_float) { printf("Header size field: %d; not multiple of %d\n", n_float, cepsize); fclose (fp); return -1; } sf = 0; ef = n; mfcbuf = (float **) alloc2d (n, cepsize, sizeof(float)); /* Read mfc data and byteswap if necessary */ n_float = n * cepsize; if ((int)fread (mfcbuf[0], sizeof(float), n_float, fp) != n_float) { printf("Error reading mfc data\n"); fclose (fp); return -1; } if (byterev) { for (i = 0; i < n_float; i++) SWAP_FLOAT(&(mfcbuf[0][i])); } fclose (fp); *numframes = n; *cep = mfcbuf; return (1); } char **alloc2d(int dim1, /* "x" dimension */ int dim2, /* "y" dimension */ int size /* number of bytes each entry takes */ ) { int i; /* loop control variable */ unsigned nelem; /* total number of elements */ char *p, /* pointer to matrix memory */ **pp; /* pointer to matrix mem table */ /* * Compute total number of elements needed for the two-dimensional * matrix */ nelem = (unsigned) dim1 * dim2; /* * Allocate the memory needed for the matrix */ p = (char *) calloc(nelem, (unsigned) size); /* * If the allocation were not successful, return a NULL pointer */ if (p == NULL) return (NULL); /* * Now allocate a table for referencing the matrix memory */ pp = (char **) calloc((unsigned) dim1, (unsigned) sizeof(char *)); /* * If the allocation were not successful, return a NULL pointer * and free the previously allocated memory */ if (pp == NULL) { free(p); return (NULL); } /* * Fill the table with locations to where each row begins */ for (i = 0; i < dim1; i++) pp[i] = p + (i * dim2 * size); return (pp); } void free2d(void **p) { if (p!=NULL) { free(p[0]); free(p); } return; } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/propedit/TableStringProperty.java package edu.cmu.sphinx.tools.confdesigner.propedit; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4String; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * DOCUMENT ME! * * @author <NAME> */ public class TableStringProperty extends TableProperty { private S4String s4String; private String NOT_DEFINED = "Not defined"; private JComboBox comboBox; private boolean isRanged; private TableCellRenderer renderer; public TableStringProperty(JTable myTable, PropertySheet currentPS, String propName) { super(propName, myTable, currentPS); this.s4String = (S4String) currentPS.getProperty(propName, S4String.class).getAnnotation(); if (currentPS.getRaw(propName) != null) { setValue(currentPS.getString(propName)); renderer = new DefaultTableCellRenderer(); } else { String defValue = s4String.defaultValue(); String[] range = s4String.range(); if (range.length != 0) { isRanged = true; String[] comboRange = new String[range.length + 1]; comboRange[0] = NOT_DEFINED; System.arraycopy(range, 0, comboRange, 1, range.length); comboBox = new JComboBox(comboRange); setValue(comboBox); renderer = new ComboTableCellRenderer(); comboBox.setRenderer((ListCellRenderer) renderer); } else { if (defValue.equals(S4String.NOT_DEFINED)) setValue(NOT_DEFINED); renderer = new DefaultTableCellRenderer(); } // set color to gray to indicate the defaultness } } public boolean isDefault() { String curValue = (String) getValue(); if ((curValue.equals(NOT_DEFINED) && s4String.defaultValue().equals(S4String.NOT_DEFINED))) return true; return curValue.equals(s4String.defaultValue()); } public void restoreDefault() { setValue(s4String.defaultValue()); } public void setValue(Object value) { myTable.repaint(); // don't change anything if nothing has changed Object oldValue = propSheet.getString(getPropName()); if ((value == null && oldValue == null) || (value != null && value.equals(oldValue))) return; // range checking is automatically done by the attached cell editor if (comboBox != null) { String comboValue = (String) comboBox.getModel().getSelectedItem(); if (comboValue.equals(NOT_DEFINED)) { propSheet.setString(getPropName(), null); setUndefinedButMandatory(s4String.mandatory()); } else { propSheet.setString(getPropName(), comboValue); setUndefinedButMandatory(false && s4String.mandatory()); } } else { propSheet.setString(getPropName(), (String) value); setUndefinedButMandatory((value == null || ((String) value).trim().length() == 0) && s4String.mandatory()); } } public Object getValue() { if (comboBox != null) return comboBox.getSelectedItem(); else return propSheet.getString(getPropName()); } public TableCellRenderer getValueRenderer() { return renderer; } public TableCellEditor getValueEditor() { if (isRanged) { return new DefaultCellEditor(comboBox); } else { return new DefaultCellEditor(new JTextField()); } } } <file_sep>/SphinxTrain/src/programs/mk_s2sendump/another_senone.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * senone.h -- Weights associated with each mixture gaussian. * * $Log$ * Revision 1.3 2004/07/21 19:17:24 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.2 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.1 2001/02/20 00:23:38 awb * *** empty log message *** * * * 19-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started based on original S3 implementation. */ #ifndef _LIBMAIN_SENONE_H_ #define _LIBMAIN_SENONE_H_ #include "s3types.h" typedef uint8 senprob_t; /* Senone logprob, truncated to 8 bits */ /* * Mixture weights for a group of senones that share a single mixture Gaussian. Split * into two structures: mixw_t and mgau2sen_t. mgau2sen_t identifies the set of senones * that share each mixture Gaussian codebook. But since a codebook consists of multiple * feature streams, with a separate mixture Gaussian of independent size for each stream, * the actual mixing weights for each stream are given by mixw_t. */ typedef struct { int32 n_wt; /* #mixture weights (== parent mixture Gaussian mgau_t.n_mean) */ senprob_t **prob; /* prob[senone][mixture-component]; #row: parent mgau2sen_t.n_sen and #col: n_wt */ } mixw_t; typedef struct { int32 n_sen; /* #Senones sharing this codebook */ s3senid_t *sen; /* List of senones sharing this codebook */ mixw_t *feat_mixw; /* Mixture weights for these senones for each feature */ } mgau2sen_t; /* The main senones data structure */ typedef struct { int32 n_sen; /* Total #senones */ int32 n_feat; /* #Features */ int32 n_mgau; /* #Parent codebooks (mixture Gaussians for multiple features count as one codebook) */ int32 shift; /* LSB bits truncated from original logs3 value */ mgau2sen_t *mgau2sen; /* Set of senones for each parent codebook */ int32 *sen2mgau; /* Unique parent codebook for each senone */ int32 *mgau2sen_idx; /* mgau2sen_idx[s] = index into mgau2sen.sen[] for senone s */ } senone_t; /* Access macros */ #define senone_n_sen(s) ((s)->n_sen) #define senone_n_mgau(s) ((s)->n_mgau) #define senone_n_stream(s) ((s)->n_feat) /* * Load a set of senones (mixing weights and mixture gaussian codebook mappings) from * the given files. Normalize weights for each codebook, apply the given floor, convert * PDF values to logs3 domain and quantize to 8-bits. * Return value: pointer to senone structure created. Caller MUST NOT change its contents. */ senone_t *senone_init (char *mixwfile, /* In: mixing weights file */ char *mgau_mapfile, /* In: file specifying mapping from each senone to mixture gaussian codebook. If NULL all senones map to codebook 0 */ float64 mixwfloor); /* In: Floor value for senone weights */ /* * Compute senone scores for all senones sharing the given mixture Gaussian. The computed * scores are ACCUMULATED into senscr (because of the need to accumulate over multiple * feature streams). (Scores are computed in logs3 domain.) */ void senone_eval_all (senone_t *s, /* In: Senone structure */ int32 m, /* In: Parent mgau for which senones evaluated */ int32 f, /* In: Feature stream for which evaluated */ int32 *dist, /* In: Gaussian density values to be weighted */ int32 *valid, /* In: Optional list of valid indexes in dist[] */ int32 n_dist, /* In: #density values in dist[] if valid is NULL, or in valid[] otherwise */ int32 *senscr); /* In/Out: Senone scores array (one entry/senone, allocated by caller). Computed senone scores accumulated into this array */ /* * Like senone_eval_all above, but computed only for a single given senone. Furthermore, * the weighted result is not accumulated anywhere automatically. Rather, it's the * return value. */ int32 senone_eval (senone_t *s, /* In: Senone structure */ int32 sid, /* In: Senone id for which score is computed */ int32 f, /* In: Feature stream under consideration */ int32 *dist, /* In: Gaussian density values to be weighted */ int32 *valid, /* In: #density values in dist[] if valid is NULL, or in valid[] otherwise */ int32 n_dist); /* In: #density values in dist above */ /* * Mark the given array of senone-ids as active in the given bitvector. */ #if 0 void senone_set_active (bitvec_t flags, /* In/Out: Bit-vector to be marked */ s3senid_t *sen, /* In: Array of senone IDs to be activated */ int32 n_sen); /* In: No. of elements in the above ID array */ #endif /* * Return the cumulative scaling applied to senone scores in the given segment. */ int32 senone_get_senscale (int32 *sc, /* In: sc[f] = scaling applied in frame f */ int32 sf, /* In: Start frame of segment (inclusive) */ int32 ef); /* In: End frame of segment (inclusive) */ #endif <file_sep>/archive_s3/s3.2/src/s3types.h /* * s3types.h -- Types specific to s3 decoder. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 13-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Changed typedef source for s3ssid_t from int32 to s3pid_t. * Changed s3senid_t from int16 to int32 (to conform with composite senid * which is int32). * * 04-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added senone sequence ID (s3ssid_t). * * 12-Jul-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _S3_S3TYPES_H_ #define _S3_S3TYPES_H_ #include <libutil/libutil.h> /* * Size definitions for more semantially meaningful units. * Illegal value definitions, limits, and tests for specific types. * NOTE: Types will be either int32 or smaller; only smaller ones may be unsigned (i.e., * no type will be uint32). */ typedef int8 s3cipid_t; /* Ci phone id */ #define BAD_S3CIPID ((s3cipid_t) -1) #define NOT_S3CIPID(p) ((p)<0) #define IS_S3CIPID(p) ((p)>=0) #define MAX_S3CIPID 127 typedef int32 s3pid_t; /* Phone id (triphone or ciphone) */ #define BAD_S3PID ((s3pid_t) -1) #define NOT_S3PID(p) ((p)<0) #define IS_S3PID(p) ((p)>=0) #define MAX_S3PID ((int32)0x7ffffffe) typedef s3pid_t s3ssid_t; /* Senone sequence id (triphone or ciphone) */ #define BAD_S3SSID ((s3ssid_t) -1) #define NOT_S3SSID(p) ((p)<0) #define IS_S3SSID(p) ((p)>=0) #define MAX_S3SSID ((int32)0x7ffffffe) typedef int32 s3tmatid_t; /* Transition matrix id; there can be as many as pids */ #define BAD_S3TMATID ((s3tmatid_t) -1) #define NOT_S3TMATID(t) ((t)<0) #define IS_S3TMATID(t) ((t)>=0) #define MAX_S3TMATID ((int32)0x7ffffffe) typedef int32 s3wid_t; /* Dictionary word id */ #define BAD_S3WID ((s3wid_t) -1) #define NOT_S3WID(w) ((w)<0) #define IS_S3WID(w) ((w)>=0) #define MAX_S3WID ((int32)0x7ffffffe) typedef uint16 s3lmwid_t; /* LM word id (uint16 for conserving space) */ #define BAD_S3LMWID ((s3lmwid_t) 0xffff) #define NOT_S3LMWID(w) ((w)==BAD_S3LMWID) #define IS_S3LMWID(w) ((w)!=BAD_S3LMWID) #define MAX_S3LMWID ((uint32)0xfffe) typedef int32 s3latid_t; /* Lattice entry id */ #define BAD_S3LATID ((s3latid_t) -1) #define NOT_S3LATID(l) ((l)<0) #define IS_S3LATID(l) ((l)>=0) #define MAX_S3LATID ((int32)0x7ffffffe) typedef int16 s3frmid_t; /* Frame id (must be SIGNED integer) */ #define BAD_S3FRMID ((s3frmid_t) -1) #define NOT_S3FRMID(f) ((f)<0) #define IS_S3FRMID(f) ((f)>=0) #define MAX_S3FRMID ((int32)0x7ffe) typedef int16 s3senid_t; /* Senone id */ #define BAD_S3SENID ((s3senid_t) -1) #define NOT_S3SENID(s) ((s)<0) #define IS_S3SENID(s) ((s)>=0) #define MAX_S3SENID ((int16)0x7ffe) typedef int16 s3mgauid_t; /* Mixture-gaussian codebook id */ #define BAD_S3MGAUID ((s3mgauid_t) -1) #define NOT_S3MGAUID(m) ((m)<0) #define IS_S3MGAUID(m) ((m)>=0) #define MAX_S3MGAUID ((int32)0x00007ffe) #define S3_START_WORD "<s>" #define S3_FINISH_WORD "</s>" #define S3_SILENCE_WORD "<sil>" #define S3_UNKNOWN_WORD "<UNK>" #define S3_SILENCE_CIPHONE "SIL" #define S3_LOGPROB_ZERO ((int32) 0xc8000000) /* Approx -infinity!! */ #define S3_MAX_FRAMES 30000 /* Frame = 10msec */ #endif <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/mk_mdef_gen.c /* ==================================================================== * Copyright (c) 2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * Various functions used in mk_mdef_gen * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3.h> #include <s3/acmod_set.h> #include <s3/model_def_io.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/err.h> #include <s3/s3.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #include "parse_cmd_ln.h" #include "heap.h" #include "hash.h" #define MAXLINESIZE 10000 #define CEILING 10000 #define IS_FILLER(X) ((X[0]=='+'||strcmp(X,"SIL")==0) ? 1 : 0) int32 make_ci_list_frm_mdef(char *mdeffile, char ***CIlist, int32 *cilistsize) { char **cilist; int32 nciphns, id, maxphnsize, phnsize; model_def_t *mdef; if (model_def_read(&mdef, mdeffile) != S3_SUCCESS) E_ERROR("Unable to read mdef file %s\n",mdeffile); *cilistsize = nciphns = mdef->acmod_set->n_ci; /* Find phone length */ maxphnsize = 0; for (id = 0; id < nciphns; id++){ phnsize = strlen(acmod_set_id2name(mdef->acmod_set,id)); if (phnsize > maxphnsize) maxphnsize = phnsize; } *CIlist = cilist = (char**)ckd_calloc_2d(nciphns,maxphnsize+1,sizeof(char)); for (id = 0; id < nciphns; id++){ strcpy(cilist[id],acmod_set_id2name(mdef->acmod_set,id)); } return S3_SUCCESS; } int32 make_ci_list_cd_hash_frm_phnlist(char *phnlist, char ***CIlist, int32 *cilistsize, hashelement_t ***CDhash, int32 *NCDphones) { char bphn[1024],lctx[1024], rctx[1024], wdpos[1024]; char line[MAXLINESIZE], **cilist, *silence="SIL"; heapelement_t **heap=NULL, *addciphone; hashelement_t **tphnhash, *tphnptr; phnhashelement_t **phnhash, *phnptr; int32 swdtphs, bwdtphs, ewdtphs, iwdtphs, maxphnsize, phnsize; int32 heapsize, i, nciphns, nwds; FILE *fp; fp = fopen(phnlist,"r"); if (fp==NULL) E_FATAL("Unable to open %s for reading\n",phnlist); /* Initially hash everything to remove duplications */ phnhash = (phnhashelement_t**)calloc(PHNHASHSIZE,sizeof(phnhashelement_t*)); tphnhash = (hashelement_t**) ckd_calloc(HASHSIZE, sizeof(hashelement_t*)); maxphnsize = 0; swdtphs = bwdtphs = ewdtphs = iwdtphs = 0; /* Always install SIL in phonelist */ phninstall(silence,phnhash); while (fgets(line,MAXLINESIZE,fp) != NULL){ nwds = sscanf(line,"%s %s %s %s",bphn,lctx,rctx,wdpos); if (nwds != 1 && nwds != 3 && nwds != 4) E_FATAL("Incorrect format in triphone file %s\n%s\n",phnlist,line); if (strcmp(bphn,"-") == 0) E_FATAL("Bad entry triphone file %s\n%s\n",phnlist,line); if (nwds == 1 || (!strcmp(lctx,"-") && !strcmp(rctx,"-"))) { phnsize = strlen(bphn); if (phnsize > maxphnsize) maxphnsize = phnsize; phninstall(bphn,phnhash); } else { if (nwds == 3) strcpy(wdpos,"i"); /* default */ if (!strcmp(lctx,"-") && !strcmp(rctx,"-") && !strcmp(wdpos,"-")){ E_WARN("Bad entry triphone file %s\n%s\n",phnlist,line); continue; } if (IS_FILLER(lctx) || IS_FILLER(rctx)){ E_WARN("Fillers in triphone, skipping:\n%s\n",line); continue; } if (!strcmp(wdpos,"i") && !strcmp(wdpos,"b") && !strcmp(wdpos,"e") && !strcmp(wdpos,"s")){ E_WARN("Bad word position type %s in triphone list\n",wdpos); E_WARN("Mapping it to word internal triphone\n"); strcpy(wdpos,"i"); } tphnptr = install(bphn,lctx,rctx,wdpos,tphnhash); if (tphnptr->dictcount == 0){ if (strcmp(wdpos,"s")==0) swdtphs++; else if (strcmp(wdpos,"b")==0) bwdtphs++; else if (strcmp(wdpos,"e")==0) ewdtphs++; else if (strcmp(wdpos,"i")==0) iwdtphs++; tphnptr->dictcount++; } } } fclose(fp); /* Heap sort CI phones */ heapsize = 0; for (i = 0; i < PHNHASHSIZE; i++) { phnptr = phnhash[i]; while (phnptr != NULL) { addciphone = (heapelement_t *) ckd_calloc(1,sizeof(heapelement_t)); addciphone->basephone = strdup(phnptr->phone); heapsize = insert(&heap, heapsize, addciphone); phnptr = phnptr->next; } } freephnhash(phnhash); *cilistsize = nciphns = heapsize; *CIlist = cilist = (char**)ckd_calloc_2d(nciphns,maxphnsize+1,sizeof(char)); for (i = 0; i < nciphns; i++){ addciphone = yanktop(&heap,heapsize,&heapsize); strcpy(cilist[i],addciphone->basephone); free_heapelement(addciphone); } assert(heapsize == 0); E_INFO("%d single word triphones in input phone list\n",swdtphs); E_INFO("%d word beginning triphones in input phone list\n",bwdtphs); E_INFO("%d word internal triphones in input phone list\n",iwdtphs); E_INFO("%d word ending triphones in input phone list\n",ewdtphs); *CDhash = tphnhash; *NCDphones = swdtphs + bwdtphs + iwdtphs + ewdtphs; return S3_SUCCESS; } int32 make_ci_list_cd_hash_frm_mdef(char *mdeffile, char ***CIlist, int32 *cilistsize, hashelement_t ***CDhash, int32 *NCDphones) { char bphn[1024],lctx[1024], rctx[1024], wdpos[1024]; char **cilist; hashelement_t **tphnhash, *tphnptr; int32 swdtphs, bwdtphs, ewdtphs, iwdtphs, maxphnsize, phnsize; int32 nciphns, id, n_acmod; model_def_t *mdef; if (model_def_read(&mdef, mdeffile) != S3_SUCCESS) E_ERROR("Unable to read mdef file %s\n",mdeffile); *cilistsize = nciphns = mdef->acmod_set->n_ci; n_acmod = acmod_set_n_acmod(mdef->acmod_set); /* Find Max phone length */ maxphnsize = 0; for (id = 0; id < nciphns; id++){ phnsize = strlen(acmod_set_id2name(mdef->acmod_set,id)); if (phnsize > maxphnsize) maxphnsize = phnsize; } *CIlist = cilist = (char**)ckd_calloc_2d(nciphns,maxphnsize+1,sizeof(char)); for (id = 0; id < nciphns; id++){ strcpy(cilist[id],acmod_set_id2name(mdef->acmod_set,id)); } tphnhash = (hashelement_t**) ckd_calloc(HASHSIZE, sizeof(hashelement_t*)); swdtphs = bwdtphs = ewdtphs = iwdtphs = 0; for (;id < n_acmod; id++){ sscanf(acmod_set_id2name(mdef->acmod_set, id),"%s %s %s %s", bphn,lctx,rctx,wdpos); tphnptr = install(bphn,lctx,rctx,wdpos,tphnhash); if (tphnptr->dictcount == 0){ if (strcmp(wdpos,"s")==0) swdtphs++; else if (strcmp(wdpos,"b")==0) bwdtphs++; else if (strcmp(wdpos,"e")==0) ewdtphs++; else if (strcmp(wdpos,"i")==0) iwdtphs++; tphnptr->dictcount++; } } E_INFO("%d single word triphones in triphone list\n",swdtphs); E_INFO("%d word beginning triphones in triphone list\n",bwdtphs); E_INFO("%d word internal triphones in triphone list\n",iwdtphs); E_INFO("%d word ending triphones in triphone list\n",ewdtphs); *CDhash = tphnhash; *NCDphones = swdtphs + bwdtphs + iwdtphs + ewdtphs; return S3_SUCCESS; } int32 read_dict(char *dictfile, char *fillerdict, dicthashelement_t ***dicthash) { char dictentry[MAXLINESIZE], dictsent[MAXLINESIZE], *dictfn[2]; char *dictword, *word, *phone, *tphn; dicthashelement_t **lhash, *sptr; int32 maxphnlen, vocabsiz=0, nphns, numdicts, idict; FILE *dict; numdicts = 1; dictfn[0] = dictfile; if (fillerdict != NULL){ dictfn[1] = fillerdict; numdicts = 2; } lhash = (dicthashelement_t**)calloc(DICTHASHSIZE,sizeof(dicthashelement_t)); if (lhash == NULL) E_FATAL("Unable to allocate space for dictionary\n"); /* Create hash table with dictionary words as entries */ for (idict = 0; idict < numdicts; idict++){ E_INFO("Reading dict %s\n",dictfn[idict]); if ((dict = fopen(dictfn[idict],"r")) == NULL) E_FATAL("Unable to open dictionary %s\n",dictfile); vocabsiz = 0; while (fgets(dictentry,MAXLINESIZE,dict) != NULL) { strcpy(dictsent,dictentry); /* HACK */ if ((dictword = strtok(dictsent," \t\n")) == NULL) E_FATAL("Empty line in dictionary!\n"); if ((sptr = dictinstall(dictword,lhash)) == NULL) E_FATAL("Unable to install dict word %s\n",dictword); if (sptr->nphns != 0) E_FATAL("Duplicate entry for %s in dictionary\n",dictword); /* Count number of phones in pronunciation */ maxphnlen = 0; for(nphns=0; (tphn=strtok(NULL," \t\n")) != NULL; nphns++){ if (strlen(tphn) > maxphnlen) maxphnlen = strlen(tphn); } if (nphns == 0) E_FATAL("Dictionary word %s has no pronunciation\n",dictword); sptr->nphns = nphns; maxphnlen++; sptr->phones = (char**)ckd_calloc_2d(nphns,maxphnlen,sizeof(char)); word = strtok(dictentry," \t\n"); for(nphns=0;(phone = strtok(NULL," \t\n")) != NULL;nphns++) strcpy(sptr->phones[nphns],phone); ++vocabsiz; } fclose(dict); E_INFO("%d words in dict %s\n",vocabsiz,dictfn[idict]); } *dicthash = lhash; return(vocabsiz); } int32 make_dict_triphone_list (dicthashelement_t **dicthash, hashelement_t ***triphonehash) { hashelement_t **tphnhash, *tphnptr; dicthashelement_t *word_el; phnhashelement_t *bphnptr, **bphnhash, *ephnptr, **ephnhash; char *bphn, *lctx, *rctx, wpos[100]; char *silencephn = "SIL"; int32 totaltphs, totwds, bwdtphs, ewdtphs, iwdtphs, swdtphs, lnphns; int32 i,j,k; tphnhash = (hashelement_t**) ckd_calloc(HASHSIZE, sizeof(hashelement_t)); bphnhash = (phnhashelement_t**)calloc(PHNHASHSIZE,sizeof(phnhashelement_t)); ephnhash = (phnhashelement_t**)calloc(PHNHASHSIZE,sizeof(phnhashelement_t)); if (bphnhash == NULL || ephnhash == NULL) E_FATAL("Unable to alloc %d size phone hashtables!\n",(int)PHNHASHSIZE); /*First count all phones that can begin or end a word (SIL can by default)*/ phninstall(silencephn,bphnhash); phninstall(silencephn,ephnhash); for (i = 0; i < DICTHASHSIZE; i++){ word_el = dicthash[i]; while (word_el != NULL){ if (!IS_FILLER(word_el->phones[0])) phninstall(word_el->phones[0],bphnhash); if (!IS_FILLER(word_el->phones[word_el->nphns - 1])) phninstall(word_el->phones[word_el->nphns - 1],ephnhash); word_el = word_el->next; } } /* Scan dictionary and make triphone list */ totwds = bwdtphs = ewdtphs = iwdtphs = swdtphs = 0; for (i = 0; i < DICTHASHSIZE; i++){ word_el = dicthash[i]; while (word_el != NULL){ totwds++; lnphns = word_el->nphns; if (lnphns == 1) { strcpy(wpos,"s"); bphn = word_el->phones[0]; if (IS_FILLER(bphn)) {word_el = word_el->next; continue;} for (j = 0; j < PHNHASHSIZE; j++){ ephnptr = ephnhash[j]; while (ephnptr != NULL){ lctx = ephnptr->phone; for (k = 0; k < PHNHASHSIZE; k++){ bphnptr = bphnhash[k]; while (bphnptr != NULL){ rctx = bphnptr->phone; tphnptr = install(bphn,lctx,rctx,wpos,tphnhash); if (tphnptr->dictcount == 0) swdtphs++; tphnptr->dictcount++; bphnptr = bphnptr->next; } } ephnptr = ephnptr->next; } } } else { strcpy(wpos,"b"); bphn = word_el->phones[0]; if (IS_FILLER(bphn)) {word_el = word_el->next; continue;} rctx = word_el->phones[1]; if (IS_FILLER(rctx)) rctx = silencephn; for (j = 0; j < PHNHASHSIZE; j++){ ephnptr = ephnhash[j]; while (ephnptr != NULL){ lctx = ephnptr->phone; tphnptr = install(bphn,lctx,rctx,wpos,tphnhash); if (tphnptr->dictcount == 0) bwdtphs++; tphnptr->dictcount++; ephnptr = ephnptr->next; } } strcpy(wpos,"i"); for (j=1;j<lnphns-1;j++){ bphn = word_el->phones[j]; if (IS_FILLER(bphn)) continue; lctx = word_el->phones[j-1]; if (IS_FILLER(lctx)) lctx = silencephn; rctx = word_el->phones[j+1]; if (IS_FILLER(rctx)) rctx = silencephn; tphnptr = install(bphn,lctx,rctx,wpos,tphnhash); if (tphnptr->dictcount == 0) iwdtphs++; tphnptr->dictcount++; } strcpy(wpos,"e"); bphn = word_el->phones[lnphns-1]; if (IS_FILLER(bphn)) {word_el = word_el->next; continue;} lctx = word_el->phones[lnphns-2]; if (IS_FILLER(lctx)) lctx = silencephn; for (j = 0; j < PHNHASHSIZE; j++){ bphnptr = bphnhash[j]; while (bphnptr != NULL){ rctx = bphnptr->phone; tphnptr = install(bphn,lctx,rctx,wpos,tphnhash); if (tphnptr->dictcount == 0) ewdtphs++; tphnptr->dictcount++; bphnptr = bphnptr->next; } } } word_el = word_el->next; } } totaltphs = swdtphs + bwdtphs + iwdtphs + ewdtphs; E_INFO("%d words in dictionary\n",totwds); E_INFO("%d unique single word triphones in dictionary\n",swdtphs); E_INFO("%d unique word beginning triphones in dictionary\n",bwdtphs); E_INFO("%d unique word internal triphones in dictionary\n",iwdtphs); E_INFO("%d unique word ending triphones in dictionary\n",ewdtphs); *triphonehash = tphnhash; freephnhash(bphnhash); freephnhash(ephnhash); return S3_SUCCESS; } int32 count_triphones (char *transfile, dicthashelement_t **dicthash, hashelement_t **tphnhash, phnhashelement_t ***phnhash) { int32 nbwdtphns, newdtphns, niwdtphns, nswdtphns; int32 nwords, lnphns, n_totalwds; char line[MAXLINESIZE], tline[MAXLINESIZE]; char *word, *basephone, *lctxt, *rctxt; char silencephn[4], wordposn[3]; int32 i, j; dicthashelement_t **wordarr; phnhashelement_t **lphnhash, *phnptr; hashelement_t *tphnptr; FILE *fp; strcpy(silencephn,"SIL"); if ((fp = fopen(transfile,"r")) == NULL) E_FATAL("Unable to open transcript file %s for reading!\n",transfile); E_WARN("Out of vocabulary words in transcript will be mapped to SIL!\n"); lphnhash = (phnhashelement_t**)calloc(PHNHASHSIZE,sizeof(phnhashelement_t)); n_totalwds = 0; nbwdtphns = newdtphns = niwdtphns = nswdtphns = 0; while (fgets(line,MAXLINESIZE,fp) != NULL){ strcpy(tline,line); if (strtok(tline," \t\n") == NULL) continue; /* Empty line */ /* Count number of phones in pronunciation */ for(nwords=1; strtok(NULL," \t\n") != NULL; nwords++); n_totalwds += nwords; wordarr = (dicthashelement_t **)ckd_calloc(nwords+2,sizeof(dicthashelement_t*)); word = strtok(line," \t\n"); if ((wordarr[1] = dictlookup(word,dicthash)) == NULL) { E_WARN("Word %s not found in dictionary. Mapping to SIL.\n", word); } for (j=2; (word = strtok(NULL," \t\n")) != NULL; j++) { if ((wordarr[j] = dictlookup(word,dicthash)) == NULL) { /* If word is surrounded by "()", assume it's the * utterance ID, and don't report it as an OOV */ if ((word[0] != '(') && (word[strlen(word) - 1] != ')')) { E_WARN("Word %s not found in dictionary. Mapping to SIL.\n", word); } } } for (i=1; i<=nwords; i++){/* Indices account for padded wordarr array */ if (wordarr[i] == NULL) continue; lnphns = wordarr[i]->nphns; if (lnphns == 1) { strcpy(wordposn,"s"); basephone = wordarr[i]->phones[0]; phnptr = phninstall(basephone,lphnhash); phnptr->count++; if (IS_FILLER(basephone)) continue; if (wordarr[i-1] != NULL){ lctxt = wordarr[i-1]->phones[wordarr[i-1]->nphns - 1]; if (IS_FILLER(lctxt)) lctxt = silencephn; } else lctxt = silencephn; if (wordarr[i+1] != NULL){ rctxt = wordarr[i+1]->phones[0]; if (IS_FILLER(rctxt)) rctxt = silencephn; } else rctxt = silencephn; tphnptr = lookup(basephone,lctxt,rctxt,wordposn,tphnhash); (tphnptr->count)++; nswdtphns++; } else { strcpy(wordposn,"b"); basephone = wordarr[i]->phones[0]; phnptr = phninstall(basephone,lphnhash); phnptr->count++; if (IS_FILLER(basephone)) continue; if (!IS_FILLER(basephone)){ if (wordarr[i-1] != NULL){ lctxt = wordarr[i-1]->phones[wordarr[i-1]->nphns - 1]; if (IS_FILLER(lctxt)) lctxt = silencephn; } else lctxt = silencephn; rctxt = wordarr[i]->phones[1]; if (IS_FILLER(rctxt)) rctxt = silencephn; tphnptr = lookup(basephone,lctxt,rctxt,wordposn,tphnhash); (tphnptr->count)++; nbwdtphns++; } strcpy(wordposn,"i"); for (j=1;j<lnphns-1;j++){ basephone = wordarr[i]->phones[j]; phnptr = phninstall(basephone,lphnhash); phnptr->count++; if (IS_FILLER(basephone)) continue; lctxt = wordarr[i]->phones[j-1]; if (IS_FILLER(lctxt)) lctxt = silencephn; rctxt = wordarr[i]->phones[j+1]; if (IS_FILLER(rctxt)) rctxt = silencephn; tphnptr = lookup(basephone,lctxt,rctxt,wordposn,tphnhash); (tphnptr->count)++; niwdtphns++; } strcpy(wordposn,"e"); basephone = wordarr[i]->phones[lnphns-1]; phnptr = phninstall(basephone,lphnhash); phnptr->count++; if (IS_FILLER(basephone)) continue; lctxt = wordarr[i]->phones[lnphns-2]; if (IS_FILLER(lctxt)) lctxt = silencephn; if (wordarr[i+1] != NULL){ rctxt = wordarr[i+1]->phones[0]; if (IS_FILLER(rctxt)) rctxt = silencephn; } else rctxt = silencephn; tphnptr = lookup(basephone,lctxt,rctxt,wordposn,tphnhash); (tphnptr->count)++; newdtphns++; } } free(wordarr); } fclose(fp); *phnhash = lphnhash; E_INFO("%d words in transcripts\n",n_totalwds); E_INFO("%d single word triphones in transcripts\n",nswdtphns); E_INFO("%d word beginning triphones in transcripts\n",nbwdtphns); E_INFO("%d word internal triphones in transcripts\n",niwdtphns); E_INFO("%d word ending triphones in transcripts\n",newdtphns); return S3_SUCCESS; } int32 find_threshold(hashelement_t **triphonehash) { hashelement_t *triphone_el; int32 tottph, ltottph, mincnt, maxtph, *countofcounts, *lcountofcounts; int32 i, cnt, unique, threshold, ceiling; mincnt = *(int32 *)cmd_ln_access("-minocc"); maxtph = *(int32 *)cmd_ln_access("-maxtriphones"); ceiling = mincnt < CEILING ? CEILING : mincnt+1; tottph = ltottph = unique = 0; countofcounts = (int32 *) ckd_calloc(ceiling+1,sizeof(int32)); lcountofcounts = (int32 *) ckd_calloc(ceiling+1,sizeof(int32)); for (i = 0; i < HASHSIZE; i++){ triphone_el = triphonehash[i]; while (triphone_el != NULL){ cnt = triphone_el->count; if (cnt > 0) { tottph += cnt; if (cnt >= mincnt) { ltottph ++; if (cnt > ceiling) cnt = ceiling; lcountofcounts[cnt]++; } countofcounts[cnt]++; unique++; } triphone_el = triphone_el->next; } } threshold = mincnt; while (ltottph > maxtph) { ltottph -= lcountofcounts[threshold]; threshold++; } E_INFO("%d triphones extracted from transcripts\n",tottph); E_INFO("%d unique triphones extracted from transcripts\n",unique); E_INFO("%d triphones occur once in the transcripts\n",countofcounts[1]); E_INFO("%d triphones occur twice in the transcripts\n",countofcounts[2]); E_INFO("%d triphones occur thrice in the transcripts\n",countofcounts[3]); E_INFO("The rest of the triphones occur more than three times\n"); E_INFO("Count threshold is %d\n",threshold); ckd_free(lcountofcounts); ckd_free(countofcounts); return(threshold); } int32 make_CD_heap(hashelement_t **triphonehash, int32 threshold, heapelement_t ***CDheap, int32 *cdheapsize) { heapelement_t **heap=NULL, *addtriphone; hashelement_t *triphone_el; int32 i, heapsize; heapsize = 0; for (i = 0; i < HASHSIZE; i++){ triphone_el = triphonehash[i]; while (triphone_el != NULL){ if (triphone_el->count >= threshold) { addtriphone = (heapelement_t *) calloc(1,sizeof(heapelement_t)); if (addtriphone == NULL) E_FATAL("Heap install error. Out of memory!\n"); addtriphone->basephone = strdup(triphone_el->basephone); addtriphone->leftcontext = strdup(triphone_el->leftcontext); addtriphone->rightcontext = strdup(triphone_el->rightcontext); addtriphone->wordposition = strdup(triphone_el->wordposition); heapsize = insert(&heap, heapsize, addtriphone); } triphone_el = triphone_el->next; } } *CDheap = heap; *cdheapsize = heapsize; return S3_SUCCESS; } int32 print_counts(char *countfn, phnhashelement_t **CIhash, hashelement_t **CDhash) { heapelement_t **CDheap=NULL, **CIheap=NULL, *addphone, *addtriphone; hashelement_t *triphone_el; phnhashelement_t *ciphone_el; int32 i, heapsize,cdheapsize,ciheapsize; FILE *ofp; if ((ofp = fopen(countfn,"w")) == NULL){ E_WARN("Unable to open %s for writing. Not writing counts!\n",countfn); return S3_ERROR; } fprintf(ofp,"base\tleft\tright\twdpos\tcount\n"); ciheapsize = 0; for (i = 0; i < PHNHASHSIZE; i++){ ciphone_el = CIhash[i]; while (ciphone_el != NULL){ if (ciphone_el->count < 1) { ciphone_el = ciphone_el->next; continue; } addphone = (heapelement_t *) ckd_calloc(1,sizeof(heapelement_t)); addphone->basephone = strdup(ciphone_el->phone); addphone->count = ciphone_el->count; ciheapsize = insert(&CIheap, ciheapsize, addphone); ciphone_el = ciphone_el->next; } } heapsize = ciheapsize; for (i = 0; i < heapsize; i++) { addphone = yanktop(&CIheap,ciheapsize,&ciheapsize); fprintf(ofp,"%s\t-\t-\t-\t%d\n",addphone->basephone,addphone->count); free_heapelement(addphone); } cdheapsize = 0; for (i = 0; i < HASHSIZE; i++){ triphone_el = CDhash[i]; while (triphone_el != NULL){ if (triphone_el->count < 1) { triphone_el = triphone_el->next; continue; } addtriphone = (heapelement_t *) ckd_calloc(1,sizeof(heapelement_t)); addtriphone->basephone = strdup(triphone_el->basephone); addtriphone->leftcontext = strdup(triphone_el->leftcontext); addtriphone->rightcontext = strdup(triphone_el->rightcontext); addtriphone->wordposition = strdup(triphone_el->wordposition); addtriphone->count = triphone_el->count; cdheapsize = insert(&CDheap, cdheapsize, addtriphone); triphone_el = triphone_el->next; } } heapsize = cdheapsize; for (i = 0; i < heapsize; i++) { addtriphone = yanktop(&CDheap,cdheapsize,&cdheapsize); fprintf(ofp,"%s\t%s\t%s\t%s\t%d\n",addtriphone->basephone, addtriphone->leftcontext, addtriphone->rightcontext, addtriphone->wordposition, addtriphone->count); free_heapelement(addtriphone); } fclose(ofp); return S3_SUCCESS; } word_posn_t posnstr2wordpos(char *posn_str) { if (posn_str == NULL) { E_WARN("No word position defined. Assuming word internal\n"); return WORD_POSN_INTERNAL; } if (posn_str[0] == 's') return WORD_POSN_SINGLE; if (posn_str[0] == 'b') return WORD_POSN_BEGIN; if (posn_str[0] == 'i') return WORD_POSN_INTERNAL; if (posn_str[0] == 'e') return WORD_POSN_END; if (posn_str[0] == 'u') return WORD_POSN_UNDEFINED; E_WARN("unknown word position %s; assuming word internal\n", posn_str); return WORD_POSN_INTERNAL; } int32 output_model_def(FILE *fp, char *pgm, char **base_str, char **left_str, char **right_str, char **posn_str, uint32 *tmat, uint32 **state, uint32 n_base, uint32 n_tri, uint32 n_total, uint32 n_state_pm, uint32 n_tied_state, uint32 n_tied_ci_state, uint32 n_tied_tmat) { time_t t; uint32 i, j; char *at; t = time(NULL); at = ctime((const time_t *)&t); at[strlen(at)-1] = '\0'; fprintf(fp, "# Generated by %s on %s\n", pgm, at); fprintf(fp, "%s\n", MODEL_DEF_VERSION); fprintf(fp, "%u n_base\n", n_base); fprintf(fp, "%u n_tri\n", n_tri); fprintf(fp, "%u n_state_map\n", (n_base + n_tri) * n_state_pm); fprintf(fp, "%u n_tied_state\n", n_tied_state); fprintf(fp, "%u n_tied_ci_state\n", n_tied_ci_state); fprintf(fp, "%u n_tied_tmat\n", n_tied_tmat); fprintf(fp, "#\n# Columns definitions\n"); fprintf(fp, "#%4s %3s %3s %1s %6s %4s %s\n", "base", "lft", "rt", "p", "attrib", "tmat", " ... state id's ..."); for (i = 0; i < n_total; i++) { if ((base_str[i][0] == '+') || (strncmp(base_str[i], "SIL", 3) == 0)) { fprintf(fp, "%5s %3s %3s %1s %6s %4d", base_str[i], (left_str[i] != NULL ? left_str[i] : "-"), (right_str[i] != NULL ? right_str[i] : "-"), (posn_str[i] != NULL ? posn_str[i] : "-"), "filler", tmat[i]); } else { fprintf(fp, "%5s %3s %3s %1s %6s %4d", base_str[i], (left_str[i] != NULL ? left_str[i] : "-"), (right_str[i] != NULL ? right_str[i] : "-"), (posn_str[i] != NULL ? posn_str[i] : "-"), "n/a", tmat[i]); } for (j = 0; j < n_state_pm-1; j++) { fprintf(fp, " %4u", state[i][j]); } fprintf(fp, " N\n"); } return S3_SUCCESS; } int32 make_mdef_from_list(char *mdeffile, char **CIlist, int32 nciphones, heapelement_t **CDheap, int32 cdheapsize, char *pgm) { int32 n_base, n_tri, n_state_pm, n_total; int32 n_tied_state_ci, n_tied_state_cd, n_tied_tmat; char **base_str, **left_str, **right_str, **posn_str; acmod_id_t base, left, right; word_posn_t posn; acmod_set_t *acmod_set; int32 i,j,k; const char *filler_attr[] = {"filler", NULL}; const char *base_attr[] = {"base", NULL}; const char *na_attr[] = {"n/a", NULL}; uint32 *tmat; uint32 **smap; heapelement_t *cdphone; FILE *fp; n_state_pm = *(int32*)cmd_ln_access("-n_state_pm") + 1; n_base = nciphones; n_tri = cdheapsize; E_INFO("%d n_base, %d n_tri\n", n_base, n_tri); n_tied_state_ci = n_base * (n_state_pm-1); n_tied_state_cd = n_tri * (n_state_pm-1); n_tied_tmat = n_base; n_total = n_base + n_tri; base_str = ckd_calloc(n_total, sizeof(char *)); left_str = ckd_calloc(n_total, sizeof(char *)); right_str = ckd_calloc(n_total, sizeof(char *)); posn_str = ckd_calloc(n_total, sizeof(char *)); tmat = ckd_calloc(n_total, sizeof(uint32)); smap = (uint32 **)ckd_calloc_2d(n_total, n_state_pm-1, sizeof(uint32)); for (i = 0; i < n_base; i++) { base_str[i] = strdup(CIlist[i]); } for (j = 0; j < n_tri; j++,i++) { cdphone = yanktop(&CDheap,cdheapsize,&cdheapsize); base_str[i] = strdup(cdphone->basephone); left_str[i] = strdup(cdphone->leftcontext); right_str[i] = strdup(cdphone->rightcontext); posn_str[i] = strdup(cdphone->wordposition); free_heapelement(cdphone); } if (cdheapsize != 0) E_FATAL("Error in CD heap! Error in dictionary or phone list!\n"); for (i = 0, k = 0; i < n_total; i++) for (j = 0; j < n_state_pm-1; j++) smap[i][j] = k++; acmod_set = acmod_set_new(); acmod_set_set_n_ci_hint(acmod_set, n_base); acmod_set_set_n_tri_hint(acmod_set, n_tri); for (i = 0; i < n_base; i++) { if (base_str[i][0] == '+') { base = acmod_set_add_ci(acmod_set, base_str[i], filler_attr); } else { base = acmod_set_add_ci(acmod_set, base_str[i], base_attr); } tmat[base] = base; } for (; i < n_total; i++) { if ((base = acmod_set_name2id(acmod_set, base_str[i])) == NO_ACMOD) E_FATAL("Error in dictionary or phonelist. Bad basephone %s in triphone list!\n",base_str[i]); if ((left = acmod_set_name2id(acmod_set, left_str[i])) == NO_ACMOD) E_FATAL("Error in dictionary or phonelist. Bad leftphone %s in triphone list!\n",left_str[i]); if ((right = acmod_set_name2id(acmod_set, right_str[i])) == NO_ACMOD) E_FATAL("Error in dictionary or phonelist. Bad rightphone %s in triphone list!\n",right_str[i]); posn = posnstr2wordpos(posn_str[i]); acmod_set_add_tri(acmod_set, base, left, right, posn, na_attr); tmat[i] = base; } if ((fp = fopen(mdeffile, "w")) == NULL) E_FATAL("Unable to open %s for writing!\n",mdeffile); output_model_def(fp, pgm, base_str, left_str, right_str, posn_str, tmat, smap, n_base, n_tri, n_total, n_state_pm, n_tied_state_ci+n_tied_state_cd, n_tied_state_ci, n_tied_tmat); fclose(fp); E_INFO("Wrote mdef file %s\n",mdeffile); for (j = 0; j < n_tri; j++,i++) { if (base_str[j] != NULL) free(base_str[j]); if (left_str[j] != NULL) free(left_str[j]); if (right_str[j] != NULL) free(right_str[j]); if (posn_str[j] != NULL) free(posn_str[j]); } free(base_str); free(left_str); free(right_str); free(posn_str); ckd_free_2d((void**)smap); return 0; } <file_sep>/README.md * This file is added by me. * Forked this repo to learn source code of voice recognization. <file_sep>/archive_s3/s3/src/programs/main_live_example.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /******************************************************************** * Example program to show usage of the live mode routines * The decoder is initialized with live_initialize_decoder() * Blocks of samples are decoded by live_utt_decode_block() * To compile an excutable compile using * $(CC) -I. -Isrc -Llibutil/linux -Lsrc/linux main_live_example.c -lutil -ldecoder -lm * from the current directory * Note the include directories (-I*) and the library directories (-L*) * ********************************************************************/ #include <libutil/libutil.h> #include <stdio.h> #include "live.h" #include "ad.h" #define MAXSAMPLES 10000 #define LISTENTIME 5.0 #define MAX_RECORD 48000 static int32 last_fr; /* Last frame for which partial result was reported */ static ad_rec_t *ad; /* Determine if the user has indicated end of utterance (keyboard hit at end of utt) */ static void ui_ready ( void ){ #if (WIN32) printf ("\nSystem will listen for ~ %.1f sec of speech\n", LISTENTIME); printf ("Hit <cr> before speaking: "); #else printf ("\nHit <cr> BEFORE and AFTER speaking: "); #endif fflush (stdout); } /* Main utterance processing loop: decode each utt */ static void utterance_loop() { char line[1024]; int16 adbuf[4096]; int32 k; int32 ns; /* #Samples read from audio in this utterance */ int32 hwm; /* High Water Mark: to know when to report partial result */ int32 recording; int j,nhypwds; partialhyp_t *parthyp; for (;;) { /* Loop for each new utterance */ ui_ready (); fgets (line, sizeof(line), stdin); if ((line[0] == 'q') || (line[0] == 'Q')) return; ad_start_rec(ad); /* Start A/D recording for this utterance */ recording = 1; ns = 0; hwm = 4000; /* Next partial result reported after 4000 samples */ last_fr = -1; /* Frame count at last partial result reported */ /* Send audio data to decoder until end of utterance */ for (;;) { /* * Read audio data (NON-BLOCKING). Use your favourite substitute here. * NOTE: In our implementation, ad_read returns -1 upon end of utterance. */ if ((k = ad_read (ad, adbuf, 4096)) < 0) break; // For now, record until MAX_RECORD and then shut off if (ns + k > MAX_RECORD) { ad_close (ad); nhypwds = live_utt_decode_block(adbuf,k,1,&parthyp); E_INFO("\n\nFINAL HYP:"); if (nhypwds > 0) for (j=0; j < nhypwds; j++) printf(" %s",parthyp[j].word); printf("\n"); break; } else nhypwds = live_utt_decode_block(adbuf,k,0,&parthyp); /* Send whatever data was read above to decoder */ // uttproc_rawdata (adbuf, k, 0); ns += k; /* Time to report partial result? (every 4000 samples or 1/4 sec) */ if (ns > hwm) { hwm = ns+4000; E_INFO("PARTIAL HYP:"); if (nhypwds > 0) for (j=0; j < nhypwds; j++) printf(" %s",parthyp[j].word); printf("\n"); } } } } int main (int argc, char *argv[]) { short samps[MAXSAMPLES]; int i, buflen, endutt, blksize, nhypwds, nsamp; char *argsfile, *ctlfile, *indir; char filename[512], cepfile[512]; partialhyp_t *parthyp; FILE *fp, *sfp; argsfile = argv[1]; live_initialize_decoder(argsfile); if (0) { if (argc != 4) E_FATAL("\nUSAGE: %s <ctlfile> <infeatdir> <argsfile>\n",argv[0]); ctlfile = argv[1]; indir = argv[2]; argsfile = argv[3]; blksize = 2000; if ((fp = fopen(ctlfile,"r")) == NULL) E_FATAL("Unable to read %s\n",ctlfile); while (fscanf(fp,"%s",filename) != EOF){ sprintf(cepfile,"%s/%s.raw",indir,filename); if ((sfp = fopen(cepfile,"r")) == NULL) E_FATAL("Unable to read %s\n",cepfile); nsamp = fread(samps, sizeof(short), MAXSAMPLES, sfp); E_INFO("%d samples in file. Will be decoded in blocks of %d\n",nsamp,blksize); fclose(sfp); for (i=0;i<nsamp;i+=blksize){ buflen = i+blksize < nsamp ? blksize : nsamp-i; endutt = i+blksize <= nsamp-1 ? 0 : 1; nhypwds = live_utt_decode_block(samps+i,buflen,endutt,&parthyp); /* E_INFO("PARTIAL HYP:"); if (nhypwds > 0) for (j=0; j < nhypwds; j++) printf(" %s",parthyp[j].word); printf("\n"); */ } } } else { // RAH const int SAMPLE_RATE = 8000; if ((ad = ad_open_sps(SAMPLE_RATE)) == NULL) E_FATAL("ad_open_sps failed\n"); utterance_loop(); } exit(0); } <file_sep>/archive_s3/s3/src/misc/pscr-read.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * pscr.c -- Phone scores processing utility. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 11-Sep-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <libutil/libutil.h> static int32 *pscr; static int32 cmp_pscr (int32 *a, int32 *b) { return (pscr[*b] - pscr[*a]); } main (int32 argc, char *argv[]) { char line[1024], *lp, wd[1024], *filename; FILE *fp; int32 len, np, sf, nf, best, th, beam; int32 p, k, f; char **phone; uint8 *pscr_in; int32 *pscr_id; float64 logf, sump, invsump, tmp, tot_sump; if (argc < 2) E_FATAL("Usage: %s [<beam>] <.pscr-file>\n", argv[0]); if (argc > 2) { if (sscanf (argv[1], "%d", &beam) != 1) E_FATAL("Usage: %s <.pscr-file> [<beam>]\n", argv[0]); if (beam > 0) beam = -beam; filename = argv[2]; } else filename = argv[1]; logf = log(1.0001); if ((fp = fopen (filename, "rb")) == NULL) E_FATAL("fopen(%s,rb) failed\n", filename); /* Read phone names */ if (fgets (line, sizeof(line), fp) == NULL) E_FATAL("fgets(%s) failed\n", filename); assert (line[0] == '#'); if (sscanf (line+1, "%d%n", &np, &len) != 1) E_FATAL("Failed to read header in %s\n", filename); lp = line+1+len; assert (np > 0); phone = (char **) ckd_calloc (np, sizeof(char *)); for (p = 0; p < np; p++) { if (sscanf (lp, "%s%n", wd, &len) != 1) E_FATAL("Failed to read header in %s\n", filename); lp += len; phone[p] = (char *) ckd_salloc (wd); } /* Read scalefactor */ if (fgets (line, sizeof(line), fp) == NULL) E_FATAL("fgets(%s) failed\n", filename); assert (line[0] == '#'); if (sscanf (line+1, "%s%d", wd, &sf) != 2) E_FATAL("Failed to read header in %s\n", filename); if (argc == 2) beam = -sf * 256; E_INFO("Beam = %d\n", beam); /* Skip past end comment marker */ while ((fgets(line, sizeof(line), fp) != NULL) && (strcmp(line, "*end_comment*\n") != 0)); /* Read byte order magic */ if (fread (&k, sizeof(int32), 1, fp) != 1) E_FATAL("Failed to read byte-order magic in %s\n", filename); assert (k == (int32)0x11223344); /* For now assume native byte order */ /* Read #frames */ if (fread (&nf, sizeof(int32), 1, fp) != 1) E_FATAL("Failed to read #frames in %s\n", filename); E_INFO("#frames= %d\n", nf); /* Read #phones */ if (fread (&k, sizeof(int32), 1, fp) != 1) E_FATAL("Failed to read #frames in %s\n", filename); assert (k == np); /* Allocate phone scores / frame */ pscr = (int32 *) ckd_calloc (np, sizeof(int32)); pscr_in = (uint8 *) ckd_calloc (np, sizeof(uint8)); pscr_id = (int32 *) ckd_calloc (np, sizeof(int32)); /* Read phone scores */ tot_sump = 0.0; for (f = 0; f < nf; f++) { if (fread (&best, sizeof(int32), 1, fp) != 1) E_FATAL("Failed to read bestscore in frame %d in %s\n", f, filename); if (fread (pscr_in, sizeof(uint8), np, fp) != np) E_FATAL("Failed to read phone scores in frame %d in %s\n", f, filename); for (p = 0; p < np; p++) { pscr[p] = best - (pscr_in[p] * sf); pscr_id[p] = p; } qsort (pscr_id, np, sizeof(int32), cmp_pscr); assert (pscr[pscr_id[0]] == best); th = best + beam; sump = 0.0; for (p = 0; p < np; p++) { if (pscr_in[p] < 255) { tmp = -logf; tmp *= (float64)(pscr_in[p]); tmp *= (float64)sf; tmp = exp(tmp); sump += tmp; } } invsump = 1.0/sump; sump = 0.0; for (p = 0; p < np; p++) { if (pscr_in[p] < 255) { tmp = -logf; tmp *= (float64)(pscr_in[p]); tmp *= (float64)sf; tmp *= invsump; sump -= (exp(tmp) * tmp); } } printf ("%5d: %12.6f", f, sump); for (p = 0; (p < np) && (pscr[pscr_id[p]] >= th); p++) printf (" %2s", phone[pscr_id[p]]); printf ("\n"); tot_sump += sump; } printf ("Ave. entropy: %12.6f\n", tot_sump / (float64)nf); } <file_sep>/pocketsphinx/src/libpocketsphinx/tst_search.h /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2009 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file tst_search.h Time-conditioned lexicon tree search ("S3") * @author <NAME> and <NAME> */ #ifndef __TST_SEARCH_H__ #define __TST_SEARCH_H__ /* SphinxBase headers. */ #include <cmd_ln.h> #include <logmath.h> #include <ngram_model.h> #include <listelem_alloc.h> #include <err.h> /* Local headers. */ #include "pocketsphinx_internal.h" #include "lextree.h" #include "vithist.h" #include "hmm.h" /** * \struct histprune_t * \brief Structure containing various histogram pruning parameters and internal storage All in integers. * */ typedef struct { int32 maxwpf; /**< Max words per frame*/ int32 maxhistpf; /**< Max histories per frame*/ int32 maxhmmpf; /**< Max active HMMs per frame*/ int32 hmm_hist_binsize;/**< Hmm histogram bin size */ int32 hmm_hist_bins; /**< Number of histogram bins*/ int32 *hmm_hist; /**< Histogram: #frames in which a given no. of HMMs are active */ } histprune_t; /** * \struct beam_t fast_algo_struct.h "fast_algo_struct.h" * \brief Structure that contains all beam parameters for beam pruning in Viterbi algorithm. * * This function include the definition of beam in multiple level of pruning in Viterbi * algorithm. That includes hmm (state-level), ptrans (phone-level), word (word-level). * ptranskip is used to specify how often in the Viterbi algorithm that phoneme level word * beam will be replaced by a word-level beam. */ /** * Structure containing various beamwidth parameters. All logs3 values; -infinite is widest, * 0 is narrowest. */ typedef struct { int32 hmm; /**< For selecting active HMMs, relative to best */ int32 ptrans; /**< For determining which HMMs transition to their successors */ int32 word; /**< For selecting words exited, relative to best HMM score */ int32 ptranskip; /**< Intervals at which wbeam is used for phone transitions */ int32 wordend; /**< For selecting the number of word ends */ int32 n_ciphone; /**< No. of ci phone used to initialized the word best and exits list*/ int32 bestscore; /**< Temporary variable: Best HMM state score in current frame */ int32 bestwordscore; /**< Temporary variable: Best wordexit HMM state score in current frame. */ int32 thres; /**< Temporary variable: The current frame general threshold */ int32 phone_thres; /**< Temporary variable: The current frame phone threshold */ int32 word_thres; /**< Temporary variable: The current frame phone threshold */ int32 *wordbestscores; /**< The word best score list */ int32 *wordbestexits; /**< The word best exits list */ } beam_t; /** * Various statistics for profiling. */ typedef struct tst_stats_s { int32 n_hmm_eval; int32 n_senone_active_utt; } tst_stats_t; /** * Time-switch tree search module structure. */ struct tst_search_s { ps_search_t base; ngram_model_t *lmset; /**< Set of language models. */ fillpen_t *fillpen; /**< Sphinx3 filler penalty structure. */ /** * There can be several unigram lextrees. If we're at the end of frame f, we can only * transition into the roots of lextree[(f+1) % n_lextree]; same for fillertree[]. This * alleviates the problem of excessive Viterbi pruning in lextrees. */ int32 n_lextree; /**< Number of lexical tree for time switching: n_lextree */ lextree_t **curugtree; /**< The current unigram tree that used in the search for this utterance. */ hash_table_t *ugtree; /**< The pool of trees that stores all word trees. */ lextree_t **fillertree; /**< The pool of trees that stores all filler trees. */ int32 n_lextrans; /**< #Transitions to lextree (root) made so far */ int32 epl; /**< The number of entry per lexical tree */ int32 isLMLA; /**< Is LM lookahead used?*/ histprune_t *histprune; /**< Structure that wraps up parameters related to absolute pruning. */ beam_t *beam; /**< Structure that wraps up beam pruning parameters. */ vithist_t *vithist; /**< Viterbi history (backpointer) table */ bitvec_t *ssid_active; /**< Bitvector of active senone sequences. */ bitvec_t *comssid_active; /**< Bitvector of active composite senone sequences. */ int16 *composite_senone_scores; /**< Composite senone scores. */ FILE *hmmdumpfp; /**< File for dumping HMM debugging information. */ int n_frame; /**< Number of frames searched so far. */ int exit_id; /**< History ID of exit word (or -1 if not done). */ tst_stats_t st; /**< Statistics. */ }; typedef struct tst_search_s tst_search_t; /** * Initialize the N-Gram search module. */ ps_search_t *tst_search_init(cmd_ln_t *config, acmod_t *acmod, s3dict_t *dict, dict2pid_t *d2p); /** * Finalize the N-Gram search module. */ void tst_search_free(ps_search_t *search); #endif /* __TST_SEARCH_H__ */ <file_sep>/sphinx_fsttools/dict.h /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 1999-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _DICT_H_ #define _DICT_H_ #ifdef __cplusplus extern "C" { #endif #if 0 } /* Fool Emacs into not indenting things. */ #endif /* SphinxBase headers. */ #include <hash_table.h> #include <glist.h> #include <listelem_alloc.h> #include <cmd_ln.h> /* Local headers. */ #include "mdef.h" #define NO_WORD -1 /* DICT_ENTRY *------------------------------------------------------------* * DESCRIPTION * Each dictionary entry consists of the word pronunciation * and list of next words in this grammar for this word. */ typedef struct dict_entry { char *word; /* Ascii rep of the word */ int32 *phone_ids; /* gt List of the of the Phones */ int32 *ci_phone_ids; /* context independent phone ids */ int16 len; /* Number of Phones in the word */ int16 mpx; /* Is this a multiplexed entry? */ int32 wid; /* Actual word id */ int32 alt; /* Alt word idx */ } dict_entry_t; typedef struct dict_s { cmd_ln_t *config; mdef_t *mdef; hash_table_t *dict; hash_table_t *ciphones; char **ciphone_str; int32 ciphone_count; int32 dict_entry_count; listelem_alloc_t *dict_entry_alloc; dict_entry_t **dict_list; int32 ci_index_len; /* number of indecies */ int32 *ci_index; /* Index to each group */ int32 filler_start; /* Start of filler words */ } dict_t; dict_t *dict_init(cmd_ln_t *config, mdef_t *mdef); void dict_free(dict_t *dict); #define DICT_SILENCE_WORDSTR "<sil>" int32 dict_to_id(dict_t *dict, char const *dict_str); int32 dict_pron (dict_t *dict, int32 w, int32 **pron); int32 dict_next_alt (dict_t *dict, int32 w); int32 dict_get_num_main_words (dict_t *dict); /* Return TRUE if the given wid is a filler word, FALSE otherwise */ int32 dict_is_filler_word (dict_t *dict, int32 wid); int32 dict_ciphone_id(dict_t *dict, char const *phone); char const *dict_ciphone_str(dict_t *dict, int32 pid); int32 dict_n_ciphone(dict_t *dict); #define dict_word_str(d,x) ((x == NO_WORD) ? "" : d->dict_list[x]->word) #define dict_base_str(d,x) ((x == NO_WORD) ? "" : \ d->dict_list[d->dict_list[x]->wid]->word) #define dict_base_wid(d,x) ((x == NO_WORD) ? NO_WORD : \ d->dict_list[x]->wid) #define dict_pronlen(dict,wid) ((dict)->dict_list[wid]->len) #define dict_ciphone(d,w,p) ((d)->dict_list[w]->ci_phone_ids[p]) #define dict_phone(d,w,p) ((d)->dict_list[w]->phone_ids[p]) #define dict_mpx(d,w) ((d)->dict_list[w]->mpx) #define dict_n_words(d) ((d)->dict_entry_count) #if 0 { /* Stop indent from complaining */ #endif #ifdef __cplusplus } #endif #endif <file_sep>/sphinx4/tests/other/EqualsInstanceOfTest.java /* * Copyright 1999-2002 <NAME>ellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package tests.other; /** * A comparison of speed between using the instanceof operation and * a direct object reference comparison. */ public class EqualsInstanceOfTest { private class Apple extends Fruit { public Apple() { super("apple"); } } /** * Time the instanceof operation. * * @param times the number of times instanceof is called * * @return the total amount of time the instanceof operation took */ public long doInstanceOfTest(int times) { Apple apple = new Apple(); long time = System.currentTimeMillis(); for (int i = 0; i < times; i++) { if (apple instanceof Fruit) { } } time = System.currentTimeMillis() - time; return time; } /** * Time the execution of the equals() method. Note that this test * is the best case scenario, since the equals() method should * return immediately (because they are the same object). * * @param times the number of times equals() is called. * * @return the total amount of time the equals() method takes to execute */ public long doEqualsTest(int times) { long time = System.currentTimeMillis(); for (int i = 0; i < times; i++) { if (Fruit.ORANGE.equals(Fruit.ORANGE)) { } } time = System.currentTimeMillis() - time; return time; } /** * Time the execution of the == operator. * * @param times the number of times the == operator is used * * @return the total amount of time the == operator takes to used */ public long doEqualsEqualsTest(int times) { long time = System.currentTimeMillis(); for (int i = 0; i < times; i++) { if (Fruit.ORANGE == Fruit.ORANGE) { } } time = System.currentTimeMillis() - time; return time; } /** * Main program to compare the execution times of the instanceof * operation and the equals() method. To execute: * <code> * java tests.other.EqualsInstanceOfTest * </code> */ public static void main(String[] argv) { EqualsInstanceOfTest test = new EqualsInstanceOfTest(); int times = 100000; long instanceOfTime = test.doInstanceOfTest(times); long equalsTime = test.doEqualsTest(times); long equalsEqualsTime = test.doEqualsEqualsTest(times); System.out.println ("Doing instanceof " + times + " times took " + instanceOfTime + " secs."); System.out.println ("Doing equals " + times + " times took " + equalsTime + " secs."); System.out.println ("Doing == " + times + " times took " + equalsEqualsTime + " secs."); } } <file_sep>/SphinxTrain/src/libs/libs2io/s2_mixing_weights.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_mixing_weights.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_mixing_weights.h> #include <s3/s2_param.h> #include <s3/ckd_alloc.h> #include <s3/int32_io.h> #include <s3/s3.h> #include <s2/log.h> #include <s2/magic.h> #include <stdio.h> #include <assert.h> static void normalize_opdf(int32 *pdf, int n_events) { int i; int32 sum = MIN_LOG; for (i = 0; i < n_events; i++) { sum = ADD(sum, pdf[i]); } for (i = 0; i < n_events; i++) { pdf[i] -= sum; } } static int32 ckd_read_int32(FILE *fp) { if (feof(fp)) { fflush(stdout); fprintf(stderr, "%s(%d): ERROR premature EOF\n", __FILE__, __LINE__); fflush(stderr); exit(1); } return read_int32(fp); } static void read_opdf(int32 *opdf, int32 n_cw, FILE *fp) { int i; for (i = 0; i < n_cw; i++) { opdf[i] = ckd_read_int32(fp); } } static void exp_pdf(float32 *opdf, int32 *ipdf, int n_codewords) { int i; for (i = 0; i < n_codewords; i++) { opdf[i] = EXP(ipdf[i]); } } int32 s2_mixing_weights(float32 ***out_mixw, const char *hmm_file_name) { int magic; /* SPHINX-II hmm file magic number */ int n_cw; /* number of codewords for the model */ int n_omatrix; /* number of output pdfs in the model */ int32 *tmp_opdf; uint32 i; FILE *fp; fp = fopen(hmm_file_name, "rb"); if (fp == NULL) { fflush(stdout); fprintf(stderr, "%s(%d): ERROR cannot open HMM file %s for reading\n", __FILE__, __LINE__, hmm_file_name); perror(hmm_file_name); fflush(stderr); return S3_ERROR; } magic = ckd_read_int32(fp); if (!IS_MAGIC(magic)) { fflush(stdout); fprintf(stderr, "%s(%d): ERROR invalid magic number found. Byteorder? Not an HMM?\n", __FILE__, __LINE__); fflush(stderr); return S3_ERROR; } n_cw = ckd_read_int32(fp); assert(n_cw == S2_N_CODEWORD); tmp_opdf = (int32 *)ckd_calloc(n_cw, sizeof(int32)); n_omatrix = ckd_read_int32(fp); assert(n_omatrix == S2_N_STATE-1); if ((magic == COUNT_F) || (magic == PROB_F)) { for (i = 0; i < n_omatrix; i++) { read_opdf(tmp_opdf, n_cw, fp); if (COUNT_P(magic)) normalize_opdf(tmp_opdf, n_cw); exp_pdf(out_mixw[i][0], tmp_opdf, n_cw); } for (i = 0; i < n_omatrix; i++) { read_opdf(tmp_opdf, n_cw, fp); if (COUNT_P(magic)) normalize_opdf(tmp_opdf, n_cw); exp_pdf(out_mixw[i][1], tmp_opdf, n_cw); } for (i = 0; i < n_omatrix; i++) { read_opdf(tmp_opdf, n_cw, fp); if (COUNT_P(magic)) normalize_opdf(tmp_opdf, n_cw); exp_pdf(out_mixw[i][2], tmp_opdf, n_cw); } for (i = 0; i < n_omatrix; i++) { read_opdf(tmp_opdf, n_cw, fp); if (COUNT_P(magic)) normalize_opdf(tmp_opdf, n_cw); exp_pdf(out_mixw[i][3], tmp_opdf, n_cw); } } ckd_free(tmp_opdf); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/03/07 09:09:13 eht * - changed open mode "r" to "rb" so that will work on PC's * * Revision 1.7 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.6 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.5 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.4 1995/10/09 15:40:24 eht * Included missing <s3/ckd_alloc.h> * * Revision 1.3 1995/10/09 15:08:24 eht * changed ckd_alloc interface to remove need for __FILE__, __LINE__ * arguments * * Revision 1.2 1995/09/07 19:23:56 eht * Changed read_longs to read_int32 to try to be explicit * about int lengths. * * Revision 1.1 95/05/22 19:19:11 19:19:11 eht (<NAME>) * Initial revision * * */ <file_sep>/archive_s3/s3.0/pgm/misc/cepdist.c /* * cepdist.c -- Cepstrum vector distance (Euclidean) between all given vectors * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 16-May-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Started adding variances for each dimension. * * 24-Mar-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <s3.h> #include <libio/libio.h> #include <libfeat/libfeat.h> static char *cepdir; static int32 n_feat, cepsize; static int32 logsc; /* Whether to logscale distance measures */ static int32 featlen; static float64 scale; /* For scaling Euclidean distances */ static float32 **feat; static char *feattype; static FILE *allpfp; static float32 *var; /* Feature dimension variances */ static float64 mfc_smooth; #define EUCL_DIST 1 #define MAHA_DIST 2 static int32 dist_type; typedef struct { char p[16]; int32 sf, nf; } pseg_t; static pseg_t *pseg; static int32 n_pseg; #define XOFF 36.0 #define YOFF 108.0 #if 0 static char *frm2phone (int32 f) { int32 i; for (i = 0; (i < n_pseg) && (f >= pseg[i].sf + pseg[i].nf); i++); return ((i < n_pseg) ? pseg[i].p : NULL); } static void load_allpseg (char *line, char *uttid) { char *lp, wd[1024]; int32 k, len, sf, nf; n_pseg = 0; lp = line; while ((k = sscanf (lp, "%s %d %d%n", wd, &sf, &nf, &len)) == 3) { lp += len; strcpy (pseg[n_pseg].p, wd); pseg[n_pseg].sf = sf; pseg[n_pseg].nf = nf; n_pseg++; } assert (k == 1); assert (wd[0] == '('); k = strlen(wd); assert (wd[k-1] == ')'); wd[k-1] = '\0'; strcpy (uttid, wd+1); } #endif static void add_allpseg (char *uttid, int32 sfspec, int32 efspec) { char line[16384], *lp, wd[1024]; int32 k, len, sf, nf, ef; if (! allpfp) return; rewind (allpfp); lp = NULL; while (fgets (line, sizeof(line), allpfp) != NULL) { /* Obtain uttid */ k = strlen (line)-2; if ((k < 2) || (line[k] != ')')) { E_ERROR("No uttid in: %s\n", line); return; } line[k] = '\0'; for (--k; (k > 0) && (line[k] != '('); --k); if (k <= 0) { E_ERROR("No uttid in: %s\n", line); return; } if (strcmp (line+k+1, uttid) == 0) { lp = line; break; } } if (! lp) return; while ((k = sscanf (lp, "%s %d %d%n", wd, &sf, &nf, &len)) == 3) { lp += len; ef = sf+nf-1; if (sf > efspec) break; if (ef < sfspec) continue; if (sf < sfspec) { nf -= (sfspec - sf); sf = sfspec; } if (ef > efspec) { nf -= (ef - efspec); ef = efspec; } assert (nf >= 0); strcpy (pseg[n_pseg].p, wd); pseg[n_pseg].sf = sf; pseg[n_pseg].nf = nf; n_pseg++; } } static float64 eucl_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = f1[i] - f2[i]; dist += d*d; } return sqrt(dist); } static float64 maha_dist (float32 *f1, float32 *f2, int32 veclen) { int32 i; float64 dist, d; dist = 0.0; for (i = 0; i < veclen; i++) { d = (f1[i] - f2[i]); dist += d*d / var[i]; } return sqrt(dist); } static void cepd1 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; } static void cepd2 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[1][i] - mfc[-1][i]; } static void cepd1_c0 (float32 **mfc, float32 *f) { int32 i; for (i = 1; i < cepsize; i++) f[i-1] = mfc[0][i]; for (i = 1; i < cepsize; i++) f[cepsize+i-2] = mfc[0][i] - mfc[-1][i]; } static void cepd1d2avg (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = 0.5 * ((mfc[0][i] - mfc[-1][i]) + (mfc[1][i] - mfc[0][i])); } static void cepd1d2 (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] = mfc[1][i] - mfc[0][i]; } static void cep_d_dd (float32 **mfc, float32 *f) { int32 i; for (i = 0; i < cepsize; i++) f[i] = mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+i] = mfc[0][i] - mfc[-1][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] = mfc[1][i] - mfc[0][i]; for (i = 0; i < cepsize; i++) f[cepsize+cepsize+i] -= f[cepsize+i]; } static void add_cepfile (char *cepfile, int32 sf, int32 ef, float64 sm) { int32 i, j, w, nfr, tsf, tef; float32 **mfc; tsf = sf-10; tef = ef+10; if (tsf < 0) tsf = 0; if ((nfr = s2mfc_read (cepfile, tsf, tef, &mfc)) <= 0) { E_ERROR("MFC file read (%s) failed\n", cepfile); return; } if (sm != 1.0) { for (i = 0; i < nfr-1; i++) { for (j = 0; j < cepsize; j++) mfc[i][j] = mfc[i][j] * sm + mfc[i+1][j] * (1.0-sm); } } sf -= tsf; ef -= tsf; w = feat_window_size (); if (sf < w) { sf = w; /* E_WARN("%s: sf bumped up to %d\n", cepfile, sf); */ } if (ef >= nfr-w-1) { ef = nfr-w-2; /* E_WARN("%s: ef bumped down to %d\n", cepfile, ef); */ } if (strcmp (feattype, "cep") == 0) { for (i = sf; i <= ef; i++) { for (j = 0; j < featlen; j++) feat[n_feat][j] = mfc[i][j]; n_feat++; } } else if (strcmp (feattype, "cep_c0") == 0) { for (i = sf; i <= ef; i++) { for (j = 0; j < featlen; j++) feat[n_feat][j] = mfc[i][j+1]; n_feat++; } } else if (strcmp (feattype, "d1") == 0) { for (i = sf; i <= ef; i++) { cepd1 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d2") == 0) { for (i = sf; i <= ef; i++) { cepd2 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1_c0") == 0) { for (i = sf; i <= ef; i++) { cepd1_c0 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1d2avg") == 0) { for (i = sf; i <= ef; i++) { cepd1d2avg (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d1d2") == 0) { for (i = sf; i <= ef; i++) { cepd1d2 (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "d_dd") == 0) { for (i = sf; i <= ef; i++) { cep_d_dd (mfc+i, feat[n_feat]); n_feat++; } } else if (strcmp (feattype, "s3") == 0) { for (i = sf; i <= ef; i++) { feat_cep2feat (mfc+i, feat+n_feat); n_feat++; } } else E_FATAL("Unknown feattype: %s\n", feattype); } static void calib (char *ctlfile, int32 ncalib) { FILE *fp; char cepfile[4096], uttid[4096]; float32 *sum, *sumsq, *lsum, *lsumsq, *mean; int32 i, j, nfr, nc; if ((fp = fopen(ctlfile, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", ctlfile); sum = (float32 *) ckd_calloc (featlen, sizeof(float32)); sumsq = (float32 *) ckd_calloc (featlen, sizeof(float32)); lsum = (float32 *) ckd_calloc (featlen, sizeof(float32)); lsumsq = (float32 *) ckd_calloc (featlen, sizeof(float32)); mean = (float32 *) ckd_calloc (featlen, sizeof(float32)); var = (float32 *) ckd_calloc (featlen, sizeof(float32)); E_INFO("Computing means\n"); for (i = 0; i < featlen; i++) sum[i] = 0.0; nfr = 0; for (nc = 0; nc < ncalib; nc++) { if (fscanf (fp, "%s", uttid) != 1) break; sprintf (cepfile, "%s.mfc", uttid); n_feat = 0; add_cepfile (cepfile, 0, (int32)0x7ffffff0, 1.0); for (i = 0; i < featlen; i++) lsum[i] = 0.0; for (i = 0; i < n_feat; i++) { for (j = 0; j < featlen; j++) lsum[j] += feat[i][j]; } for (i = 0; i < featlen; i++) sum[i] += lsum[i]; nfr += n_feat; } rewind (fp); for (i = 0; i < featlen; i++) { mean[i] = sum[i]/(float64)nfr; fprintf (stderr, " %11.3e", mean[i]); } fprintf (stderr, "\n"); fflush (stderr); E_INFO("Computing variances\n"); for (i = 0; i < featlen; i++) sum[i] = 0.0; for (nc = 0; nc < ncalib; nc++) { if (fscanf (fp, "%s", uttid) != 1) break; sprintf (cepfile, "%s.mfc", uttid); n_feat = 0; add_cepfile (cepfile, 0, (int32)0x7ffffff0, 1.0); for (i = 0; i < featlen; i++) lsum[i] = 0.0; for (i = 0; i < n_feat; i++) { for (j = 0; j < featlen; j++) lsum[j] += (feat[i][j] - mean[j]) * (feat[i][j] - mean[j]); } for (i = 0; i < featlen; i++) sum[i] += lsum[i]; } fclose (fp); for (i = 0; i < featlen; i++) { var[i] = sum[i]/(float64)nfr; fprintf (stderr, " %11.3e", var[i]); } fprintf (stderr, "\n"); fflush (stderr); ckd_free (sum); ckd_free (sumsq); ckd_free (lsum); ckd_free (lsumsq); ckd_free (mean); } static void process_ctlfile (FILE *fp) { char cepfile[4096], uttid[4096], pslabel[16384], line[16384], *lp; int32 i, j, k, sf, nf, len; float64 d, maxd, sq, sc; for (;;) { fflush (stdout); fprintf (stderr, "uttid sf nf...> "); fflush (stderr); if (fgets (line, sizeof(line), fp) == NULL) break; k = strlen(line)-1; if (line[k] == '\n') line[k] = '\0'; n_feat = 0; n_pseg = 0; lp = line; while (sscanf (lp, "%s %d %d%n", uttid, &sf, &nf, &len) == 3) { lp += len; sprintf (cepfile, "%s/%s.mfc", cepdir, uttid); add_cepfile (cepfile, sf, sf+nf-1, mfc_smooth); add_allpseg (uttid, sf, sf+nf-1); sprintf (pslabel, "%s %s %s", (dist_type == EUCL_DIST) ? "EUCL" : "MAHA", feattype, line); } /* E_INFO("%d feature vectors\n", n_feat); */ if (n_feat <= 0) continue; maxd = 0.0; for (i = 0; i < n_feat; i++) { for (j = 0; j < n_feat; j++) { if (dist_type == EUCL_DIST) d = eucl_dist (feat[i], feat[j], featlen); else d = maha_dist (feat[i], feat[j], featlen); if (maxd < d) maxd = d; k = (int32)(d*scale); /* fprintf (stderr, " %3d", k); */ } /* fprintf (stderr, "\n"); */ } /* fprintf (stderr, "\n"); */ fflush (stderr); sq = (7.0/(double)n_feat) * 72.0; /* Points/unit square */ printf ("%%!PS-Adobe-2.0 EPSF-1.2\n"); printf ("%%%%Creator: idraw\n"); printf ("%%%%DocumentFonts:\n"); printf ("%%%%Pages: 1\n"); printf ("%%%%BoundingBox: 0 0 650 800\n"); printf ("%%%%EndComments\n\n"); printf ("/box\n"); printf ("{ newpath moveto\n"); printf (" %.2f 0 rlineto\n", sq); printf (" 0 %.2f rlineto\n", sq); printf (" %.2f 0 rlineto\n", -sq); printf (" closepath setgray fill } def\n\n"); printf ("/Helvetica findfont 9 scalefont setfont\n\n"); printf ("/vdash\n"); printf ("{ newpath moveto 0 %.2f rlineto 0.0 setgray stroke} def\n\n", sq+sq); printf ("/hdash\n"); printf ("{ newpath moveto %.2f 0 rlineto 0.0 setgray stroke} def\n\n", sq+sq); printf ("/vdot\n"); printf ("{ newpath moveto 0 %.2f rlineto 0.0 setgray stroke} def\n\n", sq); printf ("/hdot\n"); printf ("{ newpath moveto %.2f 0 rlineto 0.0 setgray stroke} def\n\n", sq); printf ("/lbl\n"); printf ("{ moveto 0.0 setgray show} def\n\n"); printf ("/vlbl\n"); printf ("{ moveto 90.0 rotate 0.0 setgray show -90.0 rotate} def\n\n"); sc = logsc ? 1.0 / log(1.0 + maxd) : 1.0 / maxd; /* Compute and show distances between every pair of frames */ for (i = 0; i < n_feat; i++) { for (j = 0; j < n_feat; j++) { if (dist_type == EUCL_DIST) d = eucl_dist (feat[i], feat[j], featlen); else d = maha_dist (feat[i], feat[j], featlen); d = logsc ? log(1.0 + d) * sc : d * sc; /* Use d or 1.0-d below: */ printf ("%.3f %.2f %.2f box\n", 1.0-d, i*sq + XOFF, j*sq + YOFF); } printf ("\n"); } /* Calibrate axes */ for (i = 0; i <= n_feat; i++) { if (i % 10 == 0) { printf ("%.2f %.2f hdash\n", n_feat*sq + XOFF+sq, i*sq + YOFF); printf ("%.2f %.2f vdash\n", i*sq + XOFF, n_feat*sq + YOFF+sq); } else { printf ("%.2f %.2f hdot\n", n_feat*sq + XOFF+sq, i*sq + YOFF); printf ("%.2f %.2f vdot\n", i*sq + XOFF, n_feat*sq + YOFF+sq); } } /* Write phone segmentation if available */ if (pseg) { sf = 0; for (i = 0; i < n_pseg; i++) { printf ("%.2f %.2f hdash\n", n_feat*sq + XOFF+sq*4.0, sf*sq + YOFF); printf ("%.2f %.2f vdash\n", sf*sq + XOFF, n_feat*sq + YOFF+sq*4.0); if (pseg[i].nf > 2) { printf ("(%s) %.2f %.2f lbl\n", pseg[i].p, n_feat*sq + XOFF + sq*4, (sf + ((pseg[i].nf-2)*0.5))*sq + YOFF); printf ("(%s) %.2f %.2f vlbl\n", pseg[i].p, (sf + ((pseg[i].nf+2)*0.5))*sq + XOFF, n_feat*sq + YOFF + sq*4); } sf += pseg[i].nf; } } printf ("(%s) %.2f %.2f lbl\n\n", pslabel, XOFF + n_feat*sq*0.5, YOFF - 16.0); printf ("showpage\n"); fflush (stdout); } } main (int32 argc, char *argv[]) { int32 *fl; /* temporary featlen */ char *allpfile, *calibfile; int32 i, ncalib; if (argc < 7) { E_FATAL("Usage: %s feattype disttype(e/m) cepdir calibctlfile ncalib mfcsmooth [allpfile]\n", argv[0]); } scale = 10.0; feattype = argv[1]; dist_type = (argv[2][0] == 'e') ? EUCL_DIST : MAHA_DIST; cepdir = argv[3]; calibfile = argv[4]; if (sscanf (argv[5], "%d", &ncalib) != 1) { E_FATAL("Usage: %s feattype disttype(e/m) cepdir calibctlfile ncalib mfcsmooth [allpfile]\n", argv[0]); } if (sscanf (argv[6], "%lf", &mfc_smooth) != 1) { E_FATAL("Usage: %s feattype disttype(e/m) cepdir calibctlfile ncalib mfcsmooth [allpfile]\n", argv[0]); } allpfile = (argc > 7) ? argv[7] : NULL; logsc = 0; feat_init ("s3_1x39"); cepsize = feat_cepsize (); n_feat = feat_featsize (&fl); assert ((n_feat == 1) && (fl[0] == 39)); if (strcmp (feattype, "cep") == 0) { featlen = 13; } else if (strcmp (feattype, "cep_c0") == 0) { featlen = 12; } else if (strcmp (feattype, "d1") == 0) { featlen = 26; } else if (strcmp (feattype, "d2") == 0) { featlen = 26; } else if (strcmp (feattype, "d1_c0") == 0) { featlen = 24; } else if (strcmp (feattype, "d1d2avg") == 0) { featlen = 26; } else if (strcmp (feattype, "d1d2") == 0) { featlen = 39; } else if (strcmp (feattype, "d_dd") == 0) { featlen = 39; } else if (strcmp (feattype, "s3") == 0) { featlen = fl[0]; } else E_FATAL("Unknown feattype: %s\n", feattype); feat = (float32 **) ckd_calloc_2d (S3_MAX_FRAMES, featlen, sizeof(float32)); if (allpfile) { if ((allpfp = fopen(allpfile, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", allpfile); pseg = (pseg_t *) ckd_calloc (S3_MAX_FRAMES, sizeof(pseg_t)); } else { allpfp = NULL; pseg = NULL; } calib (calibfile, ncalib); process_ctlfile (stdin); exit(0); } <file_sep>/misc_scripts/by_speaker.sh #!/bin/bash # run decoding over each speaker individually # this is a wrapper for decodecep2.pl and takes the same arguments # [20091009] (air) if [ $# -ne 2 ] ; then echo "usage: by_speaker <cfg> <id_stub>"; exit; fi # the speakers in the traveler dev_test... spkr="f2caa01 f2uaa01 f3uba01 m2faa01 m2nba01 m3dca01" for s in $spkr ; do # remove pointers from base file grep -v "ctlfile" $1 > tmp.$$ grep -v "reffile" tmp.$$ > tempcfg.$$ rm tmp.$$ # put in the speaker-specific ones echo "ctlfile = \$ctldir/byspeaker/$s.fileid" >>tempcfg.$$ echo "reffile = \$ctldir/byspeaker/$s.ref" >>tempcfg.$$ expid=$2_$s scripts/decodecep2.pl -config tempcfg.$$ -expid $expid #remember this... mv tempcfg.$$ logdir/$expid/$expid.cfg # save the config file # quick look at result echo "--- $expid --------------------------------------------------" tail logdir/$expid/$expid.align echo "" done # <file_sep>/archive_s3/s3.0/pgm/hypext/hypext.c /* * hypext.c -- Extract hypotheses from multiple recognition hypotheses in reverse * chronological order. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 22-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> static corpus_t **inhyp; static int32 n_inhyp; static FILE *outfp; static char **infilename; /* Validation function for loading a hypseg corpus */ static int32 validate (char *str) { char tmp[65535], *wdp[4096]; int32 nwd; strcpy (tmp, str); if ((nwd = str2words (tmp, wdp, 4095)) < 0) E_FATAL("str2words failed\n"); if ((nwd > 0) && (strcmp (wdp[nwd-1], "(null)") == 0)) return 0; /* Exclude (null) hypotheses */ return 1; } /* Duplicate resolution */ static int32 dup_resolve (char *s1, char *s2) { if (strcmp (s1, s2) != 0) return -1; else return 0; } static void process_utt (char *uttfile, int32 sf, int32 ef, char *uttid) { int32 i, f, nwd; char *str; char tmp[65535], *wdp[4096]; for (i = 0; i < n_inhyp; i++) { if ((str = corpus_lookup (inhyp[i], uttid)) != NULL) break; } if (i >= n_inhyp) E_ERROR("%s: Missing\n", uttid); else { strcpy (tmp, str); if ((nwd = str2words (tmp, wdp, 4095)) < 0) E_FATAL("str2words failed\n"); if ((nwd == 0) || (sscanf (wdp[nwd-1], "%d", &f) != 1) || (f != (ef-sf+1))) E_ERROR("%s: Bad hyp in %s: %s\n", uttid, infilename[i], str); else { fprintf (outfp, "%s %s\n", uttid, str); fflush (outfp); E_INFO("%s: Extracted from %s\n", uttid, infilename[i]); } } } main (int32 argc, char *argv[]) { int32 i; if (argc < 3) { E_INFO("Usage: %s outhypfile inhypfile1 inhypfile2 ... < ctlfile\n", argv[0]); exit(0); } n_inhyp = argc - 2; inhyp = (corpus_t **) ckd_calloc (n_inhyp, sizeof(corpus_t *)); for (i = 2; i < argc; i++) inhyp[i-2] = corpus_load_headid (argv[i], validate, dup_resolve); E_INFO("Extracting\n"); if ((outfp = fopen(argv[1], "w")) == NULL) E_FATAL_SYSTEM("fopen(%s,w) failed\n", argv[1]); infilename = &(argv[2]); ctl_process (NULL, 0, 1000000000, process_utt); fclose (outfp); E_INFO("Done\n"); exit(0); } <file_sep>/web/script/sfbackup.sh #!/bin/bash loopUntilSuccess () { cmd=$@ # start loop to download code count=0; while ! $cmd; do count=`expr $count + 1` if [ $count -gt 50 ]; then # not successful, and we attempted it too many times. Clean up and l eave. return $count fi done } # Check that we have all executables if ! SSH=`command -v ssh 2>&1`; then exit 1; fi if ! SCP=`command -v scp 2>&1`; then exit 1; fi if ! RSYNC=`command -v rsync 2>&1`; then exit 1; fi if ! TAR=`command -v gtar 2>&1`; then if ! TAR=`command -v tar 2>&1`; then exit 1; fi fi # cd to directory where files are kept cd ${HOME}/project/SourceForge/backup # create the web space backup file ${SSH} www.speech.cs.cmu.edu ${TAR} czf cmusphinxWeb.tgz -C project cmusphinx # copy it locally ${SCP} -B -q www.speech.cs.cmu.edu:cmusphinxWeb.tgz cmusphinxWeb.tgz.new # remove the backup from sourceforge ${SSH} www.speech.cs.cmu.edu rm cmusphinxWeb.tgz if test -e cmusphinxWeb.tgz.new; then # Copy the twiki/web from www.speech.cs # shift the backup files, so that "-6" is the oldest rm cmusphinxWeb-6.tgz mv cmusphinxWeb-5.tgz cmusphinxWeb-6.tgz mv cmusphinxWeb-4.tgz cmusphinxWeb-5.tgz mv cmusphinxWeb-3.tgz cmusphinxWeb-4.tgz mv cmusphinxWeb-2.tgz cmusphinxWeb-3.tgz mv cmusphinxWeb-1.tgz cmusphinxWeb-2.tgz mv cmusphinxWeb.tgz cmusphinxWeb-1.tgz mv cmusphinxWeb.tgz.new cmusphinxWeb.tgz fi # backup the repository # First, rsync the cvs repository, since we still use it for regression test ${RSYNC} -a rsync://cmusphinx.cvs.sourceforge.net/cvsroot/cmusphinx/'*' cvs || echo "CVS rsync failed" # Then rsync the svn repository ${RSYNC} -a cmusphinx.svn.sourceforge.net::svn/cmusphinx/'*' svn || echo "SVN rsync failed" # copy the web space locally loopUntilSuccess $RSYNC -auvz --delete `whoami`,<EMAIL>:/home/groups/c/cm/cmusphinx . && ${TAR} czf sfWeb.tgz.new cmusphinx if test -e sfWeb.tgz.new; then # shift the backup files, so that "-6" is the oldest rm sfWeb-6.tgz mv sfWeb-5.tgz sfWeb-6.tgz mv sfWeb-4.tgz sfWeb-5.tgz mv sfWeb-3.tgz sfWeb-4.tgz mv sfWeb-2.tgz sfWeb-3.tgz mv sfWeb-1.tgz sfWeb-2.tgz mv sfWeb.tgz sfWeb-1.tgz mv sfWeb.tgz.new sfWeb.tgz fi # list the current local directory /bin/ls -l <file_sep>/SphinxTrain/src/programs/make_quests/make_tree.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * $Log$ * Revision 1.6 2005/07/09 03:13:03 arthchan2003 * Fix keyword expansion probelm * * Revision 1.5 2005/07/09 02:31:47 arthchan2003 * 1, When user forgot to specify -type, make_quest.c failed to check whether type is valid, when passed as an argument to strcpy, strcpy will cause seg core. Resolved it by explicitly adding a checking and prompting user to specify it correctly. 2, Also added keyword for all .c files. * */ #include <math.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define MINVAR 1e-08 int32 findclosestpair(float32***,float32***,float32**,int32,int32, int32,int32*,int32*); float32 likelhddec(float32*,float32*,float32*,float32*,float32,float32,int32); int make_tree(float32 **mixw, // Mixture weights for [phone][state] float32 ***means, // Means for [phone][state][dim] float32 ***vars, // Variances for [phone][state][dim] int32 nphones, // Total no. of phones char **phones, // Identities of the phones int32 nstates, // No. of states per phone int32 stt, // State we are building tree for int32 ndim // Dimensionality of feature set ) { float32 ***oldmeans, ***oldvars, ***newmeans, ***newvars; float32 **oldmixw, **newmixw, ***tmp3d, **tmp2d; char **phoneid, **newphoneid, **tmpstr; int32 i,j,l,a,b,set,nsets; oldmixw = (float32 **) ckd_calloc_2d(nphones,nstates,sizeof(float32)); oldmeans = (float32***) ckd_calloc_3d(nphones,nstates,ndim,sizeof(float32)); oldvars = (float32 ***) ckd_calloc_3d(nphones,nstates,ndim,sizeof(float32)); phoneid = (char **)ckd_calloc_2d(nphones,2048,sizeof(char)); newmixw = (float32 **) ckd_calloc_2d(nphones,nstates,sizeof(float32)); newmeans = (float32***) ckd_calloc_3d(nphones,nstates,ndim,sizeof(float32)); newvars = (float32 ***) ckd_calloc_3d(nphones,nstates,ndim,sizeof(float32)); newphoneid = (char **)ckd_calloc_2d(nphones,2048,sizeof(char)); for (i=0;i<nphones;i++){ sprintf(phoneid[i],"%s",phones[i]); //Phone ids for (j=0;j<nstates;j++){ oldmixw[i][j] = mixw[i][j]; for (l=0;l<ndim;l++){ oldmeans[i][j][l] = means[i][j][l]; oldvars[i][j][l] = vars[i][j][l]; } } } for (nsets = nphones; nsets > 2; nsets--) { // Find the closest distributions findclosestpair(oldmeans,oldvars,oldmixw,nsets,stt,ndim,&a,&b); printf("Merging %s %s\n",phoneid[a],phoneid[b]); fflush(stdout); // Copy and Merge distributions... // Copy unmerged distributions first for (i=0,set=0;i<nsets;i++){ if (i != a && i != b){ sprintf(newphoneid[set],"%s",phoneid[i]); //Phone ids newmixw[set][stt] = oldmixw[i][stt]; for (l=0;l<ndim;l++){ newmeans[set][stt][l] = oldmeans[i][stt][l]; newvars[set][stt][l] = oldvars[i][stt][l]; } set++; } } // Merge a and b sprintf(newphoneid[set],"%s_%s",phoneid[a],phoneid[b]); { float32 *nm = newmeans[set][stt]; float32 *nv = newvars[set][stt]; float32 *oma = oldmeans[a][stt]; float32 *ova = oldvars[a][stt]; float32 *omb = oldmeans[b][stt]; float32 *ovb = oldvars[b][stt]; float32 cnta, cntb; cnta = oldmixw[a][stt]; cntb = oldmixw[b][stt]; newmixw[set][stt] = cnta + cntb; for (l=0;l<ndim;l++){ nm[l] = (cnta*oma[l] + cntb*omb[l]) / (cnta + cntb); nv[l] = cnta*(ova[l]+oma[l]*oma[l])+cntb*(ovb[l]+omb[l]*omb[l]); nv[l] = nv[l]/(cnta+cntb) - nm[l]*nm[l]; if (nv[l] < MINVAR) nv[l] = MINVAR; } } // Switch old and new variables tmp3d = oldmeans; oldmeans = newmeans; newmeans = tmp3d; tmp3d = oldvars; oldvars = newvars; newvars = tmp3d; tmp2d = oldmixw; oldmixw = newmixw; newmixw = tmp2d; tmpstr = phoneid; phoneid = newphoneid; newphoneid = tmpstr; } ckd_free_3d((void ***)oldmeans); ckd_free_3d((void ***)oldvars); ckd_free_3d((void ***)newmeans); ckd_free_3d((void ***)newvars); ckd_free_2d((void **)oldmixw); ckd_free_2d((void **)newmixw); ckd_free_2d((void **)newphoneid); ckd_free_2d((void **)phoneid); return 0; } /* Find the two closest distributions. We assume 1 gaussian/state */ int32 findclosestpair(float32 ***pmeans, float32 ***pvars, float32 **pmixw, int32 nsets, int32 stt, int32 dim, int *a, int32 *b) { float32 reduction, minreduction; int32 i, j, la=0, lb=0; minreduction = 1.0e+32; for (i=0; i<nsets; i++){ for (j=i+1;j<nsets;j++){ if (i != j){ reduction = likelhddec(pmeans[i][stt],pvars[i][stt], pmeans[j][stt],pvars[j][stt], pmixw[i][stt],pmixw[j][stt], dim); if (reduction < minreduction){ minreduction = reduction; la = i; lb = j; } } } } *a = la; *b = lb; return 0; } float32 likelhddec(float32 *meana, float32 *vara, float32 *meanb, float32 *varb, float32 cnta, float32 cntb, int32 dim) { int32 i; float32 cntc, la, lb, lc, nm, nv, lkdec; cntc = cnta + cntb; for (i=0, lc=0, lb=0, la=0;i<dim;i++){ nm = (cnta*meana[i] + cntb*meanb[i])/(cnta+cntb); nv = cnta*(vara[i]+meana[i]*meana[i])+cntb*(varb[i]+meanb[i]*meanb[i]); nv = nv/(cnta+cntb) - nm*nm; if (nv < MINVAR) nv = MINVAR; lc += (float32)log(nv); lb += (float32)log(varb[i]); la += (float32)log(vara[i]); } lkdec = 0.5*(cntc*lc - cntb*lb - cnta*la); return(lkdec); } <file_sep>/CLP/include/Prons.h //------------------------------------------------------------------------------------------- // Read the words, their most likely pronunciations and the number of prons they have //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _Prons_h #define _Prons_h #include "common.h" #include "common_lattice.h" #include <ext/hash_map> using namespace __gnu_cxx; struct eqstr { bool operator()(const string s1, const string s2) const { return s1 == s2; } }; namespace __gnu_cxx { template<> struct hash<string> { size_t operator() (string s) const { return __stl_hash_string(s.c_str()); } }; } typedef hash_map<string, int, hash<string>, eqstr> WordIntHMap; typedef WordIntHMap::iterator WordIntHMapIt; class Prons { protected: WordIntHMap word2int; // index words WordVector int2word; // the inverse mapping IntVector word_no_prons; // the number of pronunciations for words WordVector word_pron; // the most likely pronunciation for a word int size; void add_word(const string&); public: Prons(int s = 0); Prons(const string& filename); int get_idx(const string& w); const string& get_pron(const int idx) const {return word_pron[idx];} int get_no_prons(const int idx) const {return word_no_prons[idx];} Word get_word(const int idx) const {return int2word[idx];} int Size() const {return size;} friend ostream& operator << (ostream& os, const Prons& pron); }; #endif <file_sep>/sphinx2/src/libsphinx2fe/Makefile.am # libsphinx2fe: Feature Extraction interface for Sphinx-II lib_LTLIBRARIES = libsphinx2fe.la libsphinx2fe_la_LDFLAGS = -version-info 0:6:0 libsphinx2fe_la_SOURCES = \ fe_interface.c \ fe_sigproc.c \ fe_warp.c \ fe_warp_affine.c \ fe_warp_inverse_linear.c \ fe_warp_piecewise_linear.c noinst_HEADERS = fe_internal.h \ fe_warp.h \ fe_warp_affine.h \ fe_warp_inverse_linear.h \ fe_warp_piecewise_linear.h INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include <file_sep>/archive_s3/s3.0/src/libmain/kbcore.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * kbcore.c -- Routines for initializing the main models. * * * HISTORY * * 28-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libfeat/libfeat.h> #include "kbcore.h" kbcore_t *kbcore_init (float64 logbase, char *feattype, char *mdeffile, char *dictfile, char *fdictfile, char *compsep, char *lmfile, char *fillpenfile, float64 silprob, float64 fillprob, float64 lw, float64 wip, char *meanfile, char *varfile, float64 varfloor, char *sen2mgau, char *mixwfile, float64 mixwfloor, char *tmatfile, float64 tmatfloor) { kbcore_t *kb; int32 i; E_INFO("Initializing core models:\n"); kb = (kbcore_t *) ckd_calloc (1, sizeof(kbcore_t)); kb->fcb = NULL; kb->mdef = NULL; kb->dict = NULL; kb->lm = NULL; kb->fillpen = NULL; kb->tmat = NULL; kb->dict2lmwid = NULL; kb->gau = NULL; kb->sen = NULL; logs3_init (logbase); if (feattype) { if ((kb->fcb = feat_init (feattype)) == NULL) E_FATAL("feat_init(%s) failed\n", feattype); } if (mdeffile) { if ((kb->mdef = mdef_init (mdeffile)) == NULL) E_FATAL("mdef_init(%s) failed\n", mdeffile); } if (dictfile) { if (! compsep) compsep = ""; else if ((compsep[0] != '\0') && (compsep[1] != '\0')) { E_FATAL("Compound word separator(%s) must be empty or single character string\n", compsep); } if ((kb->dict = dict_init (kb->mdef, dictfile, fdictfile, compsep[0])) == NULL) E_FATAL("dict_init(%s,%s,%s) failed\n", dictfile, fdictfile ? fdictfile : "", compsep); } if (lmfile) { if ((kb->lm = lm_read (lmfile, lw, wip)) == NULL) E_FATAL("lm_read(%s) failed\n", lmfile); } if (fillpenfile || (lmfile && kb->dict)) { if (! kb->dict) /* Sic */ E_FATAL("No dictionary specified for associating filler penalty file(%s)\n", fillpenfile); if ((kb->fillpen = fillpen_init (kb->dict, fillpenfile, silprob, fillprob, lw, wip)) == NULL) E_FATAL("fillpen_init(%s) failed\n", fillpenfile); } if (meanfile) { if (! varfile) E_FATAL("Varfile not specified along with meanfile(%s)\n", meanfile); if ((kb->gau = gauden_init (meanfile, varfile, varfloor, TRUE)) == NULL) E_FATAL("gauden_init(%s, %s, %e) failed\n", meanfile, varfile, varfloor); } if (mixwfile) { if (! sen2mgau) E_FATAL("sen2mgau argument not specified for mixwfile(%s)\n", mixwfile); if ((kb->sen = senone_init (mixwfile, sen2mgau, mixwfloor)) == NULL) E_FATAL("senone_init (%s, %s, %e) failed\n", mixwfile, sen2mgau, mixwfloor); } if (tmatfile) { if ((kb->tmat = tmat_init (tmatfile, tmatfloor)) == NULL) E_FATAL("tmat_init (%s, %e) failed\n", tmatfile, tmatfloor); } if (kb->dict && kb->lm) { /* Initialize dict2lmwid */ if ((kb->dict2lmwid = wid_dict_lm_map (kb->dict, kb->lm)) == NULL) E_FATAL("Dict/LM word-id mapping failed\n"); } /* ***************** Verifications ***************** */ E_INFO("Verifying models consistency:\n"); if (kb->fcb && kb->gau) { /* Verify feature streams against gauden codebooks */ if (feat_n_stream(kb->fcb) != gauden_n_stream(kb->gau)) E_FATAL("#Feature streams mismatch: feat(%d), gauden(%d)\n", feat_n_stream(kb->fcb), gauden_n_stream(kb->gau)); for (i = 0; i < feat_n_stream(kb->fcb); i++) { if (feat_stream_len(kb->fcb, i) != gauden_stream_len(kb->gau, i)) E_FATAL("Feature streamlen[%d] mismatch: feat(%d), gauden(%d)\n", i, feat_stream_len(kb->fcb, i), gauden_stream_len(kb->gau, i)); } } if (kb->fcb && kb->sen) { /* Verify senone parameters against gauden parameters */ if (senone_n_stream(kb->sen) != feat_n_stream(kb->fcb)) E_FATAL("#Feature mismatch: feat(%d), senone(%d)\n", feat_n_stream(kb->fcb), senone_n_stream(kb->sen)); } if (kb->sen && kb->gau) { if (senone_n_mgau(kb->sen) != gauden_n_mgau(kb->gau)) E_FATAL("#Mixture gaussians mismatch: senone(%d), gauden(%d)\n", senone_n_mgau(kb->sen), gauden_n_mgau(kb->gau)); } if (kb->mdef && kb->sen) { /* Verify senone parameters against model definition parameters */ if (kb->mdef->n_sen != senone_n_sen(kb->sen)) E_FATAL("#Senones mismatch: Model definition(%d) senone(%d)\n", kb->mdef->n_sen, senone_n_sen(kb->sen)); } if (kb->mdef && kb->tmat) { /* Verify transition matrices parameters against model definition parameters */ if (kb->mdef->n_tmat != kb->tmat->n_tmat) E_FATAL("Model definition has %d tmat; but #tmat= %d\n", kb->mdef->n_tmat, kb->tmat->n_tmat); if (kb->mdef->n_emit_state != kb->tmat->n_state) E_FATAL("#Emitting states in model definition = %d, #states in tmat = %d\n", kb->mdef->n_emit_state, kb->tmat->n_state); } return kb; } #if (_KBCORE_TEST_) static arg_t arglist[] = { { "-logbase", ARG_FLOAT32, "1.0001", "Base in which all log values calculated" }, { "-feat", ARG_STRING, NULL, "Feature type: s3_1x39 / s2_4x / cep_dcep[,%d] / cep[,%d] / %d,%d,...,%d" }, { "-mdef", ARG_STRING, NULL, "Model definition input file" }, { "-dict", ARG_STRING, NULL, "Pronunciation dictionary input file" }, { "-fdict", ARG_STRING, NULL, "Filler word pronunciation dictionary input file" }, { "-compsep", ARG_STRING, "", /* Default: No compound word (NULL separator char) */ "Separator character between components of a compound word (NULL if none)" }, { "-lm", ARG_STRING, NULL, "Word trigram language model input file" }, { "-fillpen", ARG_STRING, NULL, "Filler word probabilities input file" }, { "-silprob", ARG_FLOAT32, "0.1", "Default silence word probability" }, { "-fillprob", ARG_FLOAT32, "0.02", "Default non-silence filler word probability" }, { "-lw", ARG_FLOAT32, "9.5", "Language weight" }, { "-wip", ARG_FLOAT32, "0.2", "Word insertion penalty" }, { "-mean", ARG_STRING, NULL, "Mixture gaussian means input file" }, { "-var", ARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to -var file)" }, { "-senmgau", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, { "-mixw", ARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to -mixw file)" }, { "-mgaubeam", ARG_FLOAT32, "1e-3", "Beam selecting best components within each mixture Gaussian [0(widest)..1(narrowest)]" }, { "-tmat", ARG_STRING, NULL, "HMM state transition matrix input file" }, { "-tmatfloor", ARG_FLOAT32, "0.0001", "HMM state transition probability floor (applied to -tmat file)" }, { NULL, ARG_INT32, NULL, NULL } }; main (int32 argc, char *argv[]) { cmd_ln_parse (arglist, argc, argv); kbcore_init (cmd_ln_float32("-logbase"), cmd_ln_str("-feat"), cmd_ln_str("-mdef"), cmd_ln_str("-dict"), cmd_ln_str("-fdict"), cmd_ln_str("-compsep"), cmd_ln_str("-lm"), cmd_ln_str("-fillpen"), cmd_ln_float32("-silprob"), cmd_ln_float32("-fillprob"), cmd_ln_float32("-lw"), cmd_ln_float32("-wip"), cmd_ln_str("-mean"), cmd_ln_str("-var"), cmd_ln_float32("-varfloor"), cmd_ln_str("-senmgau"), cmd_ln_str("-mixw"), cmd_ln_float32("-mixwfloor"), cmd_ln_str("-tmat"), cmd_ln_float32("-tmatfloor")); } #endif <file_sep>/archive_s3/s3.3/src/tests/isolatedDigits-ti46.sh #!/bin/sh # # Usage: ./isolatedDigits-ti46.sh > res.out # # where 'res.out' is the file you want to redirect the results to # # arguments to the batchmetrics program: # # ti46.ctl : a file of all the audio files to decode # /lab/speech/... : where the audio files are # ARGS : the Sphinx 3 arguments/options file # ../../bin.sparc-sun-solaris2.8/batchmetrics ./ti46-quick.ctl /lab/speech/sphinx4/data/ti46/ti20/test/test/raw ARGS <file_sep>/cmuclmtk/src/programs/text2wngram.c /* ==================================================================== * Copyright (c) 1999-2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* [20080222] (air) temporary filenames now generated using tempnam() */ #define DEFAULT_MAX_FILES 20 #define TEMP_FILE_ROOT "text2wngram.tmp." #include <sys/types.h> /* #include <sys/utsname.h> */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "../liblmest/toolkit.h" #include "../libs/pc_general.h" #include "../libs/general.h" #include "../libs/win32compat.h" int cmp_strings(const void *string1,const void *string2) { char *s1; char *s2; s1 = *((char **) string1); s2 = *((char **) string2); return (strcmp(s1,s2)); } void merge_tempfiles (int start_file, int end_file, char *temp_file_root, char *temp_file_ext, int max_files, FILE *outfile, int n, int verbosity) { FILE *new_temp_file; char *new_temp_filename; FILE **temp_file; char **temp_filename; char **current_ngram; char smallest_ngram[1000]; int *current_ngram_count; flag *finished; flag all_finished; int temp_count; char temp_word[500]; int i,j; pc_message(verbosity,2,"Merging temp files %d through %d...\n", start_file, end_file); /* * If we try to do more than max_files, then merge into groups, * then merge groups recursively. */ if (end_file-start_file+1 > max_files) { int new_start_file, new_end_file; int n_file_groups = 1 + (end_file-start_file)/max_files; fprintf(stderr, "%d files to do, in %d groups\n", end_file-start_file, n_file_groups); new_temp_filename = (char *) rr_malloc(300*sizeof(char)); /* * These n_file_groups sets of files will be done in groups of * max_files batches each, as temp files numbered * end_file+1 ... end_file+n_file_groups, * and then these will be merged into the final result. */ for (i = 0; i < n_file_groups; i++) { /* do files i*max_files through min((i+1)*max_files-1,end_file); */ new_start_file = start_file + (i*max_files); new_end_file = start_file + ((i+1)*max_files) - 1; if (new_end_file > end_file) new_end_file = end_file; sprintf(new_temp_filename, "%s%hu%s", temp_file_root, end_file+i+1, temp_file_ext); new_temp_file = rr_oopen(new_temp_filename); merge_tempfiles(new_start_file, new_end_file, temp_file_root, temp_file_ext, max_files, new_temp_file, n, verbosity); rr_iclose(new_temp_file); } merge_tempfiles(end_file+1, end_file+n_file_groups, temp_file_root, temp_file_ext, max_files, outfile, n, verbosity); return; } /* * We know we are now doing <= max_files. */ temp_file = (FILE **) rr_malloc((end_file+1)*sizeof(FILE *)); temp_filename = (char **) rr_malloc((end_file+1)*sizeof(char *)); for (i=start_file;i<=end_file;i++) { temp_filename[i] = (char *) rr_malloc(300*sizeof(char)); } current_ngram = (char **) rr_malloc((end_file+1)*sizeof(char *)); for (i=start_file;i<=end_file;i++) { current_ngram[i] = (char *) rr_malloc(1000*sizeof(char)); } current_ngram_count = (int *) rr_malloc((end_file+1)*sizeof(int)); finished = (flag *) rr_malloc(sizeof(flag)*(end_file+1)); /* Open all the temp files for reading */ for (i=start_file;i<=end_file;i++) { sprintf(temp_filename[i],"%s%hu%s", temp_file_root,i,temp_file_ext); temp_file[i] = rr_iopen(temp_filename[i]); } /* Now go through the files simultaneously, and write out the appropriate ngram counts to the output file. */ for (i=start_file;i<=end_file;i++) { finished[i] = 0; if (!rr_feof(temp_file[i])) { for (j=0;j<=n-1;j++) { if (fscanf(temp_file[i],"%s",temp_word) != 1) { if (!rr_feof(temp_file[i])) quit(-1,"Error reading temp file %s\n",temp_filename[i]); }else { if (j==0) strcpy(current_ngram[i],temp_word); else { strcat(current_ngram[i]," "); strcat(current_ngram[i],temp_word); } } } if (fscanf(temp_file[i],"%d",&current_ngram_count[i]) != 1) { if (!rr_feof(temp_file[i])) quit(-1,"Error reading temp file %s\n",temp_filename[i]); } } } all_finished = 0; while (!all_finished) { /* Find the smallest current ngram */ strcpy(smallest_ngram,""); for (i=start_file;i<=end_file;i++) { if (!finished[i]) { if (strcmp(smallest_ngram,current_ngram[i]) > 0 || (smallest_ngram[0] == '\0')) strcpy(smallest_ngram,current_ngram[i]); } } /* For each of the files that are currently holding this ngram, add its count to the temporary count, and read in a new ngram from the files. */ temp_count = 0; for (i=start_file;i<=end_file;i++) { if (!finished[i]) { if (!strcmp(smallest_ngram,current_ngram[i])) { temp_count += current_ngram_count[i]; if (!rr_feof(temp_file[i])) { for (j=0;j<=n-1;j++) { if (fscanf(temp_file[i],"%s",temp_word) != 1) { if (!rr_feof(temp_file[i])) { quit(-1,"Error reading temp file %s\n",temp_filename[i]); } }else { if (j==0) strcpy(current_ngram[i],temp_word); else { strcat(current_ngram[i]," "); strcat(current_ngram[i],temp_word); } } } if (fscanf(temp_file[i],"%d",&current_ngram_count[i]) != 1) { if (!rr_feof(temp_file[i])) { quit(-1,"Error reading temp file count %s\n", temp_filename[i]); } } } /* * PWP: Note that the fscanf may have changed the state of * temp_file[i], so we re-ask the question rather than just * doing an "else". */ if (rr_feof(temp_file[i])) { finished[i] = 1; all_finished = 1; for (j=start_file;j<=end_file;j++) { if (!finished[j]) { all_finished = 0; } } } } } } /* * PWP: We cannot conditionalize this on (!all_finished) because * if we do we may have lost the very last count. (Consider the * case when several files have ran out of data, but the last * couple have the last count in them.) */ if (fprintf(outfile,"%s %d\n",smallest_ngram,temp_count) < 0) { quit(-1,"Write error encountered while attempting to merge temporary files.\nAborting, but keeping temporary files.\n"); } } for (i=start_file;i<=end_file;i++) { rr_iclose(temp_file[i]); remove(temp_filename[i]); } free(temp_file); for (i=start_file;i<=end_file;i++) { free(temp_filename[i]); } free(temp_filename); for (i=start_file;i<=end_file;i++) { free(current_ngram[i]); } free(current_ngram); free(current_ngram_count); free(finished); } void help_message() { fprintf(stderr,"text2wngram - Convert a text stream to a word n-gram stream.\n"); fprintf(stderr,"Usage : text2wngram [ -n 3 ]\n"); fprintf(stderr," [ -temp %s ]\n",DEFAULT_TEMP); fprintf(stderr," [ -chars %d ]\n",STD_MEM*7000000/11); fprintf(stderr," [ -words %d ]\n",STD_MEM*1000000/11); fprintf(stderr," [ -gzip | -compress ]\n"); fprintf(stderr," [ -verbosity 2 ]\n"); fprintf(stderr," < .text > .wngram\n"); } int main (int argc, char **argv) { int n; int verbosity; int max_files; int max_words; int max_chars; char temp_directory[1000]; int current_word; int current_char; int start_char; /* start boundary (possibly > than 0) */ int no_of_spaces; int pos_in_string; int i; char *current_string; char current_temp_filename[500]; int current_file_number; FILE *temp_file; flag text_buffer_full; char *text_buffer; char **pointers; char current_ngram[500]; int current_count; int counter; char *temp_file_root; char *temp_file_ext; flag words_set; flag chars_set; /* Process command line */ verbosity = pc_intarg(&argc, argv,"-verbosity",DEFAULT_VERBOSITY); pc_message(verbosity,2,"text2wngram\n"); report_version(&argc,argv); if (pc_flagarg( &argc, argv,"-help")) { help_message(); exit(1); } n = pc_intarg(&argc, argv,"-n",DEFAULT_N); /* max_words = pc_intarg(&argc, argv,"-words",STD_MEM*1000000/11); max_chars = pc_intarg(&argc, argv,"-chars",STD_MEM*7000000/11); */ max_words = pc_intarg(&argc, argv,"-words",-1); max_chars = pc_intarg(&argc, argv,"-chars",-1); if (max_words == -1) { words_set = 0; max_words = STD_MEM*1000000/11; }else words_set = 1; if (max_chars == -1) { chars_set = 0; max_chars = STD_MEM*7000000/11; }else chars_set = 1; max_files = pc_intarg(&argc, argv,"-files",DEFAULT_MAX_FILES); strcpy(temp_directory,pc_stringarg( &argc, argv, "-temp", DEFAULT_TEMP)); if (pc_flagarg(&argc,argv,"-compress")) temp_file_ext = salloc(".Z"); else { if (pc_flagarg(&argc,argv,"-gzip")) temp_file_ext = salloc(".gz"); else temp_file_ext = salloc(""); } temp_file_root = tempnam(temp_directory, TEMP_FILE_ROOT); pc_report_unk_args(&argc,argv,verbosity); if (words_set && !chars_set) max_chars = max_words * 7; if (!words_set && chars_set) max_words = max_chars / 7; /* If the last charactor in the directory name isn't a / then add one. */ if (temp_directory[strlen(temp_directory)-1] != '/') { strcat(temp_directory,"/"); } pc_message(verbosity,2,"n = %d\n",n); pc_message(verbosity,2,"Number of words in buffer = %d\n",max_words); pc_message(verbosity,2,"Number of chars in buffer = %d\n",max_chars); pc_message(verbosity,2,"Max number of files open at once = %d\n",max_files); pc_message(verbosity,2,"Temporary directory = %s\n",temp_directory); /* Allocate memory for the buffers */ text_buffer = (char *) rr_malloc(sizeof(char)*max_chars); pc_message(verbosity,2,"Allocated %d bytes to text buffer.\n", sizeof(char)*max_chars); pointers = (char **) rr_malloc(sizeof(char *)*max_words); pc_message(verbosity,2,"Allocated %d bytes to pointer array.\n", sizeof(char *)*max_words); current_file_number = 0; current_word = 1; start_char = 0; current_char = 0; counter = 0; pointers[0] = text_buffer; while (!feof(stdin)) { current_file_number++; /* Read text into buffer */ pc_message(verbosity,2,"Reading text into buffer...\n"); pc_message(verbosity,2,"Reading text into the n-gram buffer...\n"); pc_message(verbosity,2,"20,000 words processed for each \".\", 1,000,000 for each line.\n"); pointers[0] = text_buffer; while ((!rr_feof(stdin)) && (current_word < max_words) && (current_char < max_chars)) { text_buffer[current_char] = getchar(); if (text_buffer[current_char] == '\n' || text_buffer[current_char] == '\t' ) { text_buffer[current_char] = ' '; } if (text_buffer[current_char] == ' ') { if (current_char > start_char) { if (text_buffer[current_char-1] == ' ') { current_word--; current_char--; } pointers[current_word] = &(text_buffer[current_char+1]); current_word++; counter++; if (counter % 20000 == 0) { if (counter % 1000000 == 0) pc_message(verbosity,2,"\n"); else pc_message(verbosity,2,"."); } } } if (text_buffer[current_char] != ' ' || current_char > start_char) current_char++; } text_buffer[current_char]='\0'; if (current_word == max_words || rr_feof(stdin)) { for (i=current_char+1;i<=max_chars-1;i++) text_buffer[i] = ' '; text_buffer_full = 0; }else text_buffer_full = 1; /* Sort buffer */ pc_message(verbosity,2,"\nSorting pointer array...\n"); qsort((void *) pointers,(size_t) current_word-n,sizeof(char *),cmp_strings); /* Write out temporary file */ sprintf(current_temp_filename,"%s%hu%s",temp_file_root,current_file_number,temp_file_ext); pc_message(verbosity,2,"Writing out temporary file %s...\n",current_temp_filename); temp_file = rr_oopen(current_temp_filename); text_buffer[current_char] = ' '; current_count = 0; strcpy(current_ngram,""); for (i = 0; i <= current_word-n; i++) { current_string = pointers[i]; /* Find the nth space */ no_of_spaces = 0; pos_in_string = 0; while (no_of_spaces < n) { if (current_string[pos_in_string] == ' ') no_of_spaces++; pos_in_string++; } if (!strncmp(current_string,current_ngram,pos_in_string)) current_count++; else { if (strcmp(current_ngram,"")) if (fprintf(temp_file,"%s %d\n",current_ngram,current_count) < 0) quit(-1,"Error writing to temporary file %s\n",current_temp_filename); current_count = 1; strncpy(current_ngram,current_string,pos_in_string); current_ngram[pos_in_string] = '\0'; } } rr_oclose(temp_file); /* Move the last n-1 words to the beginning of the buffer, and set correct current_word and current_char things */ strcpy(text_buffer,pointers[current_word-n]); pointers[0]=text_buffer; /* Find the (n-1)th space */ no_of_spaces=0; pos_in_string=0; if (!text_buffer_full){ while (no_of_spaces<(n-1)) { if (pointers[0][pos_in_string]==' ') { no_of_spaces++; pointers[no_of_spaces] = &pointers[0][pos_in_string+1]; } pos_in_string++; } }else { while (no_of_spaces<n) { if (pointers[0][pos_in_string]==' ') { no_of_spaces++; pointers[no_of_spaces] = &pointers[0][pos_in_string+1]; } pos_in_string++; } pos_in_string--; } current_char = pos_in_string; current_word = n; /* mark boundary beyond which counting pass cannot backup */ start_char = current_char; } /* Merge temporary files */ pc_message(verbosity,2,"Merging temporary files...\n"); merge_tempfiles(1, current_file_number, temp_file_root, temp_file_ext, max_files, stdout, n, verbosity); pc_message(verbosity,0,"text2wngram : Done.\n"); exit(0); } <file_sep>/SphinxTrain/src/libs/libcommon/cvt2triphone.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cvt2triphone.c * * Description: * This file contains routines to convert a sequence of context * independent phones into a sequence of triphones. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/cvt2triphone.h> #include <s3/acmod_set.h> #include <s3/s3.h> #include <stdio.h> #include <assert.h> /********************************************************************* * * Function: btw_posn * * Description: * This function takes a between word marker and a current * word position state and generates the next word position * state (see the description for cvt2triphone() for a * discussion of between word markers). * * Function Inputs: * char btw_mark - * The value of the current between word marker. * * word_posn_t posn - * The current word position state (i.e. * word begin, word end, word internal, single * phone word). * * Global Inputs: * None * * Return Values: * The following table gives the return values for all * possible values of the word_posn and btw_mark inputs. * * word_posn * * BEGIN INT SINGLE END * ------------------------------ * btw_mark: T END END SINGLE SINGLE * : F INT INT BEGIN BEGIN * * * Global Outputs: * None * * Errors: * *********************************************************************/ word_posn_t btw_posn(char btw_mark, word_posn_t posn) { if (btw_mark) { if ((posn == WORD_POSN_INTERNAL) || (posn == WORD_POSN_BEGIN)) { posn = WORD_POSN_END; } else if (posn == WORD_POSN_END) { posn = WORD_POSN_SINGLE; } else if (posn == WORD_POSN_SINGLE) ; /* Don't change in this case */ else { E_FATAL("Unhandled word position\n"); } } else { if (posn == WORD_POSN_BEGIN) { posn = WORD_POSN_INTERNAL; } else if ((posn == WORD_POSN_END) || (posn == WORD_POSN_SINGLE)) { posn = WORD_POSN_BEGIN; } else if (posn == WORD_POSN_INTERNAL) ; /* Don't change posn's value in this case */ else { E_FATAL("Unhandled word position\n"); } } return posn; } /********************************************************************* * * Function: cvt2triphone * * Description: * This routine takes a context indepent phone sequence and * converts it into a triphone sequence. The between word * marker sequence, given as input, is used to determine the * word position of the triphone (i.e. begin, end, internal or single * phone). * * For each context independent phone in the input sequence * there is a between word marker. It is a boolean value * which is true when there is a word boundary after the * associated phone. For instance, if the word BAT is * used in the original word string the corresponding * phone string and associated between word marker * sequence are: * * phone: ... B AA T ... * marker: ... FALSE FALSE TRUE ... * * Function Inputs: * acmod_set_t *acmod_set - * This is the data structure which allows the acmod_set * module to return triphone id's * * acmod_id_t *phone - * This is the sequence of context independent acoustic * models corresponding to some word string. * * char *btw_mark - * The between word markers for this CI model sequence. * * uint32 n_phone - * The number of CI models in the sequence. * * Global Inputs: * None * * Return Values: * None (this probably needs to be changed) * * Global Outputs: * None * *********************************************************************/ int cvt2triphone(acmod_set_t *acmod_set, acmod_id_t *phone, char *btw_mark, uint32 n_phone) { uint32 i; ci_acmod_id_t b = (ci_acmod_id_t)NO_ACMOD; ci_acmod_id_t l = (ci_acmod_id_t)NO_ACMOD; ci_acmod_id_t r = (ci_acmod_id_t)NO_ACMOD; acmod_id_t tri_id; word_posn_t posn; static int spoke_my_peace = FALSE; acmod_id_t sil = acmod_set_name2id(acmod_set, "SIL"); char *word_posn_map = WORD_POSN_CHAR_MAP; if (acmod_set_n_multi(acmod_set) == 0) { /* nothing to do */ if (!spoke_my_peace) { fflush(stdout); E_INFO("no multiphones defined, no conversion done\n"); spoke_my_peace = TRUE; fflush(stderr); } return S3_SUCCESS; } for (i = 0, l = r = sil, posn = WORD_POSN_END; i < n_phone-1; i++) { /* get new right context */ r = phone[i+1]; if (acmod_set_has_attrib(acmod_set, r, "filler")) r = sil; b = phone[i]; /* determine between word position {begin|start|single} */ posn = btw_posn(btw_mark[i], posn); if (!acmod_set_has_attrib(acmod_set, b, "filler")) { tri_id = acmod_set_tri2id(acmod_set, b, l, r, posn); if (tri_id != NO_ACMOD) { /* got good triphone, so replace CI w/ tri */ phone[i] = tri_id; } else { /* Try to back off to other word positions */ int j; for (j = 0; j < N_WORD_POSN; ++j) { tri_id = acmod_set_tri2id(acmod_set, b, l, r, j); if (tri_id != NO_ACMOD) { phone[i] = tri_id; break; } } if (j == N_WORD_POSN) { #if 0 E_WARN("Missing triphone, (%s %s %s %c), left as CI phone\n", acmod_set_id2name(acmod_set, b), acmod_set_id2name(acmod_set, l), acmod_set_id2name(acmod_set, r), word_posn_map[(int)posn]); #endif } } } else { /* phone[i] is a filler phone, so just leave it as is */ /* Change b to SIL for triphone context purposes */ b = sil; } /* Set next left context is the current base phone (where filler phones * are mapped to SIL) */ l = b; } b = phone[i]; r = sil; /* At this point, b is the right context of * the next to last phone. Typically, this * is sil or some other filler phone. */ if (!acmod_set_has_attrib(acmod_set, b, "filler")) { if (i > 0) { E_WARN("utt does not end with filler phone\n"); r = sil; } assert( btw_mark[i] ); posn = btw_posn(btw_mark[i], posn); tri_id = acmod_set_tri2id(acmod_set, b, l, r, posn); if (tri_id != NO_ACMOD) phone[i] = tri_id; else { E_WARN("Missing triphone, (%s %s %s %c), left as CI phone", acmod_set_id2name(acmod_set, b), acmod_set_id2name(acmod_set, l), acmod_set_id2name(acmod_set, r), word_posn_map[(int)posn]); } } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.5 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.5 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.4 96/06/17 14:33:57 eht * Added typecasts * * Revision 1.3 1996/03/25 15:30:39 eht * Removed unreferenced local var *  * * Revision 1.2 1995/12/01 20:47:04 eht * Include function prototypes for this .c file * * Revision 1.1 1995/12/01 20:41:47 eht * Initial revision * */ <file_sep>/tools/riddler/java/edu/cmu/sphinx/tools/riddler/persist/Corpus.java /** * Copyright 1999-2007 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * <p/> * User: <NAME> * Date: Jan 13, 2007 * Time: 8:23:37 PM */ package edu.cmu.sphinx.tools.riddler.persist; import javax.persistence.*; import java.util.*; /** * A Corpus' unique identifier. A Corpus consists of Items and has an associated Dictionary * mapping Words to pronunciations. * @see Item * @see Pronunciation * @author <NAME> */ @Entity @NamedQuery(name = "findCorporaByMetadatum", query = "SELECT c FROM Corpus c, " + "IN (c.metadata) m " + "WHERE m.theKey = :key AND m.theValue = :value") public class Corpus implements StringIdentified { @Id @GeneratedValue(strategy = GenerationType.TABLE) private String id; @OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER, mappedBy = "corpus") private List<Item> items = new ArrayList<Item>(); @OneToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) private Dictionary dictionary; @Temporal(value = TemporalType.DATE) private Date collectDate; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Metadatum> metadata = new ArrayList<Metadatum>(); public Corpus(List<Item> items, Dictionary dictionary, Date collectDate, List<Metadatum> metadata) { this.items = items; this.dictionary = dictionary; this.collectDate = collectDate; this.metadata = metadata; } public Corpus() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public Dictionary getDictionary() { return dictionary; } public void setDictionary(Dictionary dictionary) { this.dictionary = dictionary; } public Date getCollectDate() { return collectDate; } public void setCollectDate(Date collectDate) { this.collectDate = collectDate; } public List<Metadatum> getMetadata() { return metadata; } public void setMetadata(List<Metadatum> metadata) { this.metadata = metadata; } }<file_sep>/SphinxTrain/src/programs/bw/next_utt_states.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: next_utt_states.c * * Description: * Get the word transcript for the next utterance and convert it * into a sequence of states ready for forward/backward. * * Author: * <NAME>, <EMAIL> *********************************************************************/ #include <s3/lexicon.h> #include <s3/model_inventory.h> #include <s3/mk_wordlist.h> #include <s3/ckd_alloc.h> #include <s3/mk_phone_list.h> #include <s3/cvt2triphone.h> #include <s3/state_seq.h> #include "next_utt_states.h" state_t *next_utt_states(uint32 *n_state, lexicon_t *lex, model_inventory_t *inv, model_def_t *mdef, char *trans, int32 sil_del, char* silence_str ) { char **word; uint32 n_word; uint32 n_phone; char *btw_mark; acmod_set_t *acmod_set; acmod_id_t *phone; acmod_id_t optSil; state_t *state_seq; word = mk_wordlist(trans, &n_word); phone = mk_phone_list(&btw_mark, &n_phone, word, n_word, lex); if (phone == NULL) { E_WARN("Unable to produce CI phones for utt\n"); ckd_free(word); return NULL; } acmod_set = inv->acmod_set; #ifdef NEXT_UTT_STATES_VERBOSE print_phone_list(phone, n_phone, btw_mark, acmod_set); #endif cvt2triphone(acmod_set, phone, btw_mark, n_phone); #ifdef NEXT_UTT_STATES_VERBOSE print_phone_list(phone, n_phone, btw_mark, acmod_set); #endif optSil= acmod_set_name2id(acmod_set, silence_str); /* * Debug? * E_INFO("Silence id %d\n",optSil); */ state_seq = state_seq_make(n_state, phone, n_phone, inv, mdef,sil_del,(acmod_id_t)optSil); #ifdef NEXT_UTT_STATES_VERBOSE state_seq_print(state_seq, *n_state, mdef); #endif ckd_free(phone); ckd_free(btw_mark); ckd_free(word); return state_seq; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.9 2005/03/30 16:43:47 egouvea * Commented E_INFO calls that seemed to be there for debug/trace purpose only, not for a user * * Revision 1.8 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.7 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.4 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.13 1996/07/29 16:18:29 eht * Moved state_seq module into libcommon * * Revision 1.12 1995/12/01 20:52:07 eht * cvt2triphone() and mk_phone_list() now in libcommon since other commands * need them now. * * Revision 1.11 1995/11/02 16:18:40 eht * Fix so that if a phone seq is not able to be produced, * the utterance is just skipped * * Revision 1.10 1995/10/12 18:30:22 eht * Made state.h a "local" header file * * Revision 1.9 1995/10/10 12:43:50 eht * Changed to use <s3/prim_type.h> * * Revision 1.8 1995/10/09 15:37:18 eht * added missing include of <s3/ckd_alloc.h> * * Revision 1.7 1995/10/09 15:32:34 eht * forgot semi-colon * * Revision 1.6 1995/10/09 14:55:33 eht * Change interface to new ckd_alloc routines * * Revision 1.5 1995/09/14 14:22:39 eht * Changed call to state_seq_print() to conform to new interface * * Revision 1.4 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.3 1995/06/28 14:33:34 eht * Made changes to allow tying to be determined by model_def_t * data structure rather than the tying DAG * * Revision 1.2 1995/06/27 19:25:25 eht * Fixed bug in transition matrix mapping found by <NAME> * * Revision 1.1 1995/06/02 20:41:22 eht * Initial revision * * */ <file_sep>/sphinx4/src/apps/edu/cmu/sphinx/demo/jsapi/icecream/IceCreamDemo.java package edu.cmu.sphinx.demo.jsapi.icecream; import javax.speech.AudioException; import javax.speech.Central; import javax.speech.EngineException; import javax.speech.EngineStateError; import javax.speech.recognition.FinalRuleResult; import javax.speech.recognition.Recognizer; import javax.speech.recognition.RecognizerModeDesc; import javax.speech.recognition.Result; import javax.speech.recognition.ResultEvent; import javax.speech.recognition.ResultListener; import javax.speech.recognition.ResultToken; import edu.cmu.sphinx.jsapi.SphinxEngineCentral; import edu.cmu.sphinx.jsapi.SphinxRecognizerModeDesc; /** * A MIDlet demonstrating the use of speech synthesis and recognition together. */ public class IceCreamDemo implements ResultListener { private Object lock = new Object(); public void run() throws EngineException, AudioException, EngineStateError { Central.registerEngineCentral( SphinxEngineCentral.class.getCanonicalName()); RecognizerModeDesc mode = new SphinxRecognizerModeDesc( "/edu/cmu/sphinx/demo/jsapi/icecream/sphinx4.config.xml"); Recognizer recognizer = (Recognizer) Central.createRecognizer(mode); // Start up the recognizer. System.out.println("Allocating recognizer..."); recognizer.allocate(); // Create the grammar. It is enabled by default. // Add a listener for recognition results. recognizer.addResultListener(this); // Request focus and start listening. recognizer.requestFocus(); recognizer.resume(); System.out.println("What is your favorite icecream?"); } public void waitForResult() throws InterruptedException { synchronized (lock) { lock.wait(); } } /** * Called when the MIDlet is started or resumed. * <p> * Note that <code>startApp()</code> can be called several times if * <code>pauseApp()</code> has been called in between. */ public static void main(String[] args) { try { IceCreamDemo demo = new IceCreamDemo(); demo.run(); demo.waitForResult(); } catch (Exception e) { e.printStackTrace(); } } /** * Displays a finalized result. * * @param result * A result which was accepted by {@link #resultUpdate}. * @returns the spoken text */ private String displayResult(Result result) { StringBuffer spoken = new StringBuffer(); // Get the array of tokens that the recognizer thinks // the user most likely spoke. ResultToken[] best = result.getBestTokens(); // Concatenate all of the result's tokens. for (int i = 0; i < best.length; i++) { if (i > 0) spoken.append(' '); spoken.append(best[i].getSpokenText()); } // Append the spoken tokens to the user interface. return spoken.toString(); } @Override public void audioReleased(ResultEvent event) { System.out.println(event); } @Override public void grammarFinalized(ResultEvent event) { System.out.println(event); } @Override public void resultAccepted(ResultEvent event) { System.out.println(event); synchronized (lock) { lock.notifyAll(); } final Result result = (Result) event.getSource(); displayResult(result); } @Override public void resultCreated(ResultEvent event) { System.out.println(event); } @Override public void resultRejected(ResultEvent event) { System.out.println(event); synchronized (lock) { lock.notifyAll(); } } @Override public void resultUpdated(ResultEvent event) { switch (event.getId()) { case ResultEvent.RESULT_ACCEPTED: FinalRuleResult result = (FinalRuleResult) event.getSource(); // Display the result. String spoken = this.displayResult(result); // Speak whatever the user said. System.out.println(spoken); break; } } @Override public void trainingInfoReleased(ResultEvent event) { System.out.println(event); } } <file_sep>/SphinxTrain/src/programs/map_adapt/main.c /* -*- c-file-style: "bsd"; c-basic-offset: 4 -*- */ /********************************************************************* * * $Header$ * * Carnegie Mellon ARPA Speech Group * * Copyright (c) 1996-2005 Carnegie Mellon University. * All rights reserved. ********************************************************************* * * File: src/programs/map_adapt/main.c * * Description: * Do one pass of MAP re-estimation (adaptation). * * See "Speaker Adaptation Based on MAP Estimation of HMM * Parameters", <NAME> and <NAME>, Proceedings * of ICASSP 1993, p. II-558 for the details of prior density * estimation and forward-backward MAP. * * Author: * <NAME> <<EMAIL>> * *********************************************************************/ /* The SPHINX-III common library */ #include <stdio.h> #include <s3/common.h> #include <sys_compat/file.h> #include <s3/model_inventory.h> #include <s3/model_def_io.h> #include <s3/s3gau_io.h> #include <s3/s3mixw_io.h> #include <s3/s3tmat_io.h> #include <s3/s3acc_io.h> #include <s3/matrix.h> /* Some SPHINX-II compatibility definitions */ #include <s3/s2_param.h> #include <s3/s3.h> #include <s3/err.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <string.h> #include "parse_cmd_ln.h" static void check_consistency(const char *filename, uint32 n_mgau, uint32 n_mgau_rd, uint32 n_stream, uint32 n_stream_rd, uint32 n_density, uint32 n_density_rd, const uint32 *veclen, const uint32 *veclen_rd) { uint32 s; if (n_mgau != n_mgau_rd) E_FATAL("Number of codebooks is mismatched in %s\n",filename); if (n_stream != n_stream_rd) E_FATAL("Number of streams is mismatched in %s\n",filename); if (n_density != n_density_rd) E_FATAL("Number of gaussians is mismatched in %s\n",filename); for (s = 0; s < n_stream; ++s) if (veclen[s] != veclen_rd[s]) E_FATAL("Vector length of stream %u mismatched in %s\n", s, filename); } static float32 *** estimate_tau(vector_t ***si_mean, vector_t ***si_var, float32 ***si_mixw, uint32 n_cb, uint32 n_stream, uint32 n_density, uint32 n_mixw, const uint32 *veclen, vector_t ***wt_mean, float32 ***wt_mixw, float32 ***wt_dcount) { float32 ***map_tau; uint32 i, j, k, m; E_INFO("Estimating tau hyperparameter from variances and observations\n"); map_tau = (float32 ***)ckd_calloc_3d(n_mixw, n_stream, n_density, sizeof(float32)); for (i = 0; i < n_mixw; ++i) { for (j = 0; j < n_stream; ++j) { for (k = 0; k < n_density; ++k) { float32 tau_nom, tau_dnom; tau_nom = veclen[j] * wt_mixw[i][j][k]; tau_dnom = 0.0f; for (m = 0; m < veclen[j]; ++m) { float32 ydiff, wvar, dnom, ml_mu, si_mu, si_sigma; if (n_mixw != n_cb && n_cb == 1) {/* Semi-continuous. */ dnom = wt_dcount[0][j][k]; si_mu = si_mean[0][j][k][m]; si_sigma = si_var[0][j][k][m]; ml_mu = dnom ? wt_mean[0][j][k][m] / dnom : si_mu; } else { /* Continuous. */ dnom = wt_dcount[i][j][k]; si_mu = si_mean[i][j][k][m]; si_sigma = si_var[i][j][k][m]; ml_mu = dnom ? wt_mean[i][j][k][m] / dnom : si_mu; } ydiff = ml_mu - si_mu; /* Gauvain/Lee's estimation of this makes no * sense as I read it, it seems to simply * equal the precision matrix. We want to use * the variance anyway, because higher * variance in the SI models should lead to * stronger adaptation. */ /* And this is still less than ideal, because * it way overestimates tau for SCHMM due to * the large number of mixtures. So for * semi-continuous models you probably want to * use -fixedtau. */ wvar = si_mixw[i][j][k] * si_sigma; tau_dnom += dnom * ydiff * wvar * ydiff; } if (tau_dnom > 1e-5 && tau_nom > 1e-5) map_tau[i][j][k] = tau_nom / tau_dnom; else map_tau[i][j][k] = 1000.0f; /* FIXME: Something big, I guess. */ #if 0 E_INFO("map_tau[%d][%d][%d] = %f / %f = %f\n", i, j, k, tau_nom, tau_dnom, map_tau[i][j][k]); #endif } } } return map_tau; } static int map_mixw_reest(float32 ***map_tau, float32 fixed_tau, float32 ***si_mixw, float32 ***wt_mixw, float32 ***map_mixw, float32 mwfloor, uint32 n_mixw, uint32 n_stream, uint32 n_density) { uint32 i, j, k; E_INFO("Re-estimating mixture weights using MAP\n"); for (i = 0; i < n_mixw; ++i) { for (j = 0; j < n_stream; ++j) { float32 sum_tau, sum_nu, sum_wt_mixw; sum_tau = sum_nu = sum_wt_mixw = 0.0f; for (k = 0; k < n_density; ++k) sum_tau += (map_tau != NULL) ? map_tau[i][j][k] : fixed_tau; for (k = 0; k < n_density; ++k) { float32 nu; /* NOTE: We estimate nu such that the SI mixture * weight is the mode of the posterior distribution, * hence the + 1. This allows the MAP estimate to * converge to the SI one in the case of no adaptation * data (clearly, this is desirable!) */ nu = si_mixw[i][j][k] * sum_tau + 1; sum_nu += nu; sum_wt_mixw += wt_mixw[i][j][k]; } for (k = 0; k < n_density; ++k) { float32 tau, nu; tau = (map_tau != NULL) ? map_tau[i][j][k] : fixed_tau; nu = si_mixw[i][j][k] * sum_tau + 1; map_mixw[i][j][k] = (nu - 1 + wt_mixw[i][j][k]) / (sum_nu - n_density + sum_wt_mixw); /* Floor mixture weights - otherwise they will be negative in cases where si_mixw is very small. FIXME: This might be an error in my implementation? */ if (map_mixw[i][j][k] < mwfloor) map_mixw[i][j][k] = mwfloor; #if 0 printf("%d %d %d tau %f map_mixw %f =\n" " nu %f - 1 + wt_mixw %f\n" "/ sum_nu %f - %d + sum_wt_mixw %f\n", i, j, k, tau, map_mixw[i][j][k], nu, wt_mixw[i][j][k], sum_nu, n_density, sum_wt_mixw); #endif } } } return S3_SUCCESS; } static int map_tmat_reest(float32 ***si_tmat, float32 ***wt_tmat, float32 ***map_tmat, float32 tpfloor, uint32 n_tmat, uint32 n_state) { uint32 t, i, j; E_INFO("Re-estimating transition probabilities using MAP\n"); for (t = 0; t < n_tmat; ++t) { for (i = 0; i < n_state-1; ++i) { float32 sum_si_tmat = 0.0f, sum_wt_tmat = 0.0f; for (j = 0; j < n_state; ++j) { sum_si_tmat += si_tmat[t][i][j]; sum_wt_tmat += si_tmat[t][i][j]; } for (j = 0; j < n_state; ++j) { if (si_tmat[t][i][j] + wt_tmat[t][i][j] < 0) continue; map_tmat[t][i][j] = (si_tmat[t][i][j] + wt_tmat[t][i][j]) / (sum_si_tmat + sum_wt_tmat); if (map_tmat[t][i][j] < 0.0f) { E_WARN("map_tmat[%d][%d][%d] < 0 (%f)\n", t, i, j, map_tmat[t][i][j]); map_tmat[t][i][j] = 0.0f; } } } } return S3_SUCCESS; } static int32 bayes_mean_reest(vector_t ***si_mean, vector_t ***si_var, vector_t ***wt_mean, vector_t ***wt_var, float32 ***wt_dcount, int32 pass2var, vector_t ***map_mean, float32 varfloor, uint32 i, uint32 j, uint32 k, const uint32 *veclen) { uint32 m; /* Textbook MAP estimator for single Gaussian. This works better if tau is unknown. */ for (m = 0; m < veclen[j]; ++m) { if (wt_dcount[i][j][k]) { float32 mlmean, mlvar; mlmean = wt_mean[i][j][k][m] / wt_dcount[i][j][k]; if (pass2var) mlvar = wt_var[i][j][k][m] / wt_dcount[i][j][k]; else mlvar = (wt_var[i][j][k][m] / wt_dcount[i][j][k] - mlmean * mlmean); /* Perfectly normal if -2passvar isn't specified. */ if (mlvar < 0.0f) { if (pass2var) E_WARN("mlvar[%d][%d][%d][%d] < 0 (%f)\n", i,j,k,m,mlvar); mlvar = varfloor; } map_mean[i][j][k][m] = (wt_dcount[i][j][k] * si_var[i][j][k][m] * mlmean + mlvar * si_mean[i][j][k][m]) / (wt_dcount[i][j][k] * si_var[i][j][k][m] + mlvar); } else map_mean[i][j][k][m] = si_mean[i][j][k][m]; } return S3_SUCCESS; } static int map_mean_reest(float32 tau, vector_t ***si_mean, vector_t ***wt_mean, float32 ***wt_dcount, vector_t ***map_mean, uint32 i, uint32 j, uint32 k, const uint32 *veclen) { uint32 m; /* CH Lee mean update equation. Use this if you want to experiment with values of tau. */ for (m = 0; m < veclen[j]; ++m) { if (wt_dcount[i][j][k]) map_mean[i][j][k][m] = (tau * si_mean[i][j][k][m] + wt_mean[i][j][k][m]) / (tau + wt_dcount[i][j][k]); else map_mean[i][j][k][m] = si_mean[i][j][k][m]; } return S3_SUCCESS; } static int map_var_reest(float32 tau, vector_t ***si_mean, vector_t ***si_var, vector_t ***wt_mean, vector_t ***wt_var, float32 ***wt_dcount, vector_t ***map_mean, vector_t ***map_var, float32 varfloor, uint32 i, uint32 j, uint32 k, const uint32 *veclen) { uint32 m; for (m = 0; m < veclen[j]; ++m) { float32 alpha, beta, mdiff; /* Somewhat different estimates of alpha and beta from the * ones given in Gauvain & Lee. These actually converge to * the SI variance with no observations, and also seem to * perform better in at least one case. */ alpha = tau + 1; beta = tau * si_var[i][j][k][m]; mdiff = si_mean[i][j][k][m] - map_mean[i][j][k][m]; /* This should be the correct update equation for diagonal * covariance matrices. */ map_var[i][j][k][m] = (beta + wt_var[i][j][k][m] + tau * mdiff * mdiff) / (alpha - 1 + wt_dcount[i][j][k]); if (map_var[i][j][k][m] < 0.0f) { /* This is bad and shouldn't happen! */ E_WARN("mapvar[%d][%d][%d][%d] < 0 (%f)\n", i,j,k,m, map_var[i][j][k][m]); map_var[i][j][k][m] = varfloor; } if (map_var[i][j][k][m] < varfloor) map_var[i][j][k][m] = varfloor; } return S3_SUCCESS; } static int map_update(void) { float32 ***si_mixw = NULL; float32 ***si_tmat = NULL; vector_t ***si_mean = NULL; vector_t ***si_var = NULL; vector_t ***wt_mean = NULL; vector_t ***wt_var = NULL; float32 ***wt_mixw = NULL; float32 ***wt_tmat = NULL; float32 ***wt_dcount = NULL; int32 pass2var; float32 ***map_mixw = NULL; float32 ***map_tmat = NULL; vector_t ***map_mean = NULL; vector_t ***map_var = NULL; float32 ***map_tau = NULL; float32 fixed_tau = 10.0f; float32 mwfloor = 1e-5f; float32 varfloor = 1e-5f; float32 tpfloor = 1e-4f; uint32 n_mixw, n_mixw_rd; uint32 n_tmat, n_tmat_rd, n_state, n_state_rd; uint32 n_cb, n_cb_rd; uint32 n_stream, n_stream_rd; uint32 n_density, n_density_rd; const uint32 *veclen = NULL; const uint32 *veclen_rd = NULL; const char **accum_dir; const char *si_mixw_fn; const char *map_mixw_fn; const char *si_tmat_fn; const char *map_tmat_fn; const char *si_mean_fn; const char *map_mean_fn; const char *si_var_fn; const char *map_var_fn; uint32 i, j, k; accum_dir = (const char **)cmd_ln_access("-accumdir"); si_mean_fn = (const char *)cmd_ln_access("-meanfn"); si_var_fn = (const char *)cmd_ln_access("-varfn"); si_tmat_fn = (const char *)cmd_ln_access("-tmatfn"); si_mixw_fn = (const char *)cmd_ln_access("-mixwfn"); map_mean_fn = (const char *)cmd_ln_access("-mapmeanfn"); map_var_fn = (const char *)cmd_ln_access("-mapvarfn"); map_tmat_fn = (const char *)cmd_ln_access("-maptmatfn"); map_mixw_fn = (const char *)cmd_ln_access("-mapmixwfn"); /* Must be at least one accum dir. */ if (accum_dir == NULL) E_FATAL("Must specify at least one -accumdir\n"); /* Must have means and variances. */ if (si_mean_fn == NULL || si_var_fn == NULL || si_mixw_fn == NULL) E_FATAL("Must specify baseline means, variances, and mixture weights\n"); /* Must specify output means. */ if (map_mean_fn == NULL) E_FATAL("Must at least specify output MAP means\n"); /* Read SI model parameters. */ if (s3gau_read(si_mean_fn, &si_mean, &n_cb, &n_stream, &n_density, &veclen) != S3_SUCCESS) E_FATAL("Couldn't read %s\n", si_mean_fn); if (s3gau_read(si_var_fn, &si_var, &n_cb_rd, &n_stream_rd, &n_density_rd, &veclen_rd) != S3_SUCCESS) E_FATAL("Couldn't read %s\n", si_var_fn); check_consistency(si_var_fn, n_cb, n_cb_rd, n_stream, n_stream_rd, n_density, n_density_rd, veclen, veclen_rd); /* Don't free veclen_rd, as rdacc_den needs it. */ /* Read and normalize SI mixture weights. */ if (si_mixw_fn) { mwfloor = cmd_ln_float32("-mwfloor"); if (s3mixw_read(si_mixw_fn, &si_mixw, &n_mixw, &n_stream_rd, &n_density_rd) != S3_SUCCESS) E_FATAL("Couldn't read %s\n", si_mixw_fn); for (i = 0; i < n_mixw; ++i) { for (j = 0; j < n_stream; ++j) { float32 sum_si_mixw = 0.0f; for (k = 0; k < n_density; ++k) { if (si_mixw[i][j][k] < mwfloor) si_mixw[i][j][k] = mwfloor; sum_si_mixw += si_mixw[i][j][k]; } for (k = 0; k < n_density; ++k) si_mixw[i][j][k] /= sum_si_mixw; } } } /* Read SI transition matrices. */ /* FIXME: We may want to normalize these if we do more interesting * estimation of the eta hyperparameters (i.e. using tau) */ if (si_tmat_fn) { tpfloor = cmd_ln_float32("-tpfloor"); if (s3tmat_read(si_tmat_fn, &si_tmat, &n_tmat, &n_state) != S3_SUCCESS) E_FATAL("Couldn't read %s\n", si_tmat_fn); } /* Read observation counts. */ for (i = 0; accum_dir[i]; ++i) { E_INFO("Reading and accumulating observation counts from %s\n", accum_dir[i]); if (rdacc_den(accum_dir[i], &wt_mean, &wt_var, &pass2var, &wt_dcount, &n_cb_rd, &n_stream_rd, &n_density_rd, &veclen_rd) != S3_SUCCESS) E_FATAL("Error in reading densities from %s\n", accum_dir[i]); check_consistency(accum_dir[i], n_cb, n_cb_rd, n_stream, n_stream_rd, n_density, n_density_rd, veclen, veclen_rd); if (pass2var && map_var_fn) E_FATAL("Variance re-estimation requested, but -2passvar was specified in bw."); if (map_mixw_fn || !cmd_ln_int32("-fixedtau")) { if (rdacc_mixw(accum_dir[i], &wt_mixw, &n_mixw_rd, &n_stream_rd, &n_density_rd) != S3_SUCCESS) E_FATAL("Error in reading mixture weights from %s\n", accum_dir[i]); check_consistency(accum_dir[i], n_mixw, n_mixw_rd, n_stream, n_stream_rd, n_density, n_density_rd, veclen, veclen_rd); } if (map_tmat_fn) { if (rdacc_tmat(accum_dir[i], &wt_tmat, &n_tmat_rd, &n_state_rd) != S3_SUCCESS) E_FATAL("Error in reading transition matrices from %s\n", accum_dir[i]); if (n_tmat_rd != n_tmat || n_state_rd != n_state) E_FATAL("Mimsatch in tranition matrices from %s\n", accum_dir[i]); } } ckd_free((void *)veclen_rd); /* Allocate MAP parameters */ map_mean = gauden_alloc_param(n_cb, n_stream, n_density, veclen); if (map_var_fn) map_var = gauden_alloc_param(n_cb, n_stream, n_density, veclen); if (map_mixw_fn) map_mixw = (float32 ***)ckd_calloc_3d(n_mixw, n_stream, n_density, sizeof(float32)); if (map_tmat_fn) map_tmat = (float32 ***)ckd_calloc_3d(n_tmat, n_state-1, n_state, sizeof(float32)); /* Optionally estimate prior tau hyperparameter for each HMM * (all other prior parameters can be derived from it). */ if (cmd_ln_int32("-fixedtau")) { fixed_tau = cmd_ln_float32("-tau"); E_INFO("tau hyperparameter fixed at %f\n", fixed_tau); } else map_tau = estimate_tau(si_mean, si_var, si_mixw, n_cb, n_stream, n_density, n_mixw, veclen, wt_mean, wt_mixw, wt_dcount); /* Re-estimate mixture weights. */ if (map_mixw) { map_mixw_reest(map_tau, fixed_tau, si_mixw, wt_mixw, map_mixw, mwfloor, n_mixw, n_stream, n_density); } /* Re-estimate transition matrices. */ if (map_tmat) map_tmat_reest(si_tmat, wt_tmat, map_tmat, tpfloor, n_tmat, n_state); /* Re-estimate means and variances */ if (cmd_ln_int32("-bayesmean")) E_INFO("Re-estimating means using Bayesian interpolation\n"); else E_INFO("Re-estimating means using MAP\n"); if (n_mixw != n_cb && n_cb == 1) E_INFO("Interpolating tau hyperparameter for semi-continuous models\n"); if (map_var) E_INFO("Re-estimating variances using MAP\n"); for (i = 0; i < n_cb; ++i) { for (j = 0; j < n_stream; ++j) { for (k = 0; k < n_density; ++k) { float32 tau; if (map_tau == NULL) tau = fixed_tau; else { /* Interpolate tau for semi-continuous models. */ if (n_mixw != n_cb && n_cb == 1) { int m; tau = 0.0f; for (m = 0; m < n_mixw; ++m) tau += map_tau[m][j][k]; tau /= n_mixw; #if 0 printf("SC tau[%d][%d] = %f\n", j, k, tau); #endif } else /* Continuous. */ tau = map_tau[i][j][k]; } /* Means re-estimation. */ if (cmd_ln_int32("-bayesmean")) bayes_mean_reest(si_mean, si_var, wt_mean, wt_var, wt_dcount, pass2var, map_mean, varfloor, i, j, k, veclen); else map_mean_reest(tau, si_mean, wt_mean, wt_dcount, map_mean, i, j, k, veclen); /* Variance re-estimation. Doesn't work with * -2passvar, and in many cases this can actually * degrade accuracy, so use it with caution. */ if (map_var) map_var_reest(tau, si_mean, si_var, wt_mean, wt_var, wt_dcount, map_mean, map_var, varfloor, i, j, k, veclen); } } } if (map_mean_fn) if (s3gau_write(map_mean_fn, (const vector_t ***)map_mean, n_cb, n_stream, n_density, veclen) != S3_SUCCESS) E_FATAL("Unable to write MAP mean to %s\n",map_mean_fn); if (map_var && map_var_fn) if (s3gau_write(map_var_fn, (const vector_t ***)map_var, n_cb, n_stream, n_density, veclen) != S3_SUCCESS) E_FATAL("Unable to write MAP variance to %s\n",map_var_fn); if (map_mixw && map_mixw_fn) if (s3mixw_write(map_mixw_fn, map_mixw, n_mixw, n_stream, n_density)!= S3_SUCCESS) E_FATAL("Unable to write MAP mixture weights to %s\n",map_mixw_fn); if (map_tmat && map_tmat_fn) if (s3tmat_write(map_tmat_fn, map_tmat, n_tmat, n_state)!= S3_SUCCESS) E_FATAL("Unable to write MAP transition matrices to %s\n",map_tmat_fn); ckd_free((void *)veclen); gauden_free_param(si_mean); gauden_free_param(si_var); if (si_mixw) ckd_free_3d((void *)si_mixw); if (si_tmat) ckd_free_3d((void *)si_tmat); gauden_free_param(wt_mean); gauden_free_param(wt_var); ckd_free_3d((void *)wt_dcount); if (map_mean) gauden_free_param(map_mean); if (map_var) gauden_free_param(map_var); if (map_tau) ckd_free_3d((void *)map_tau); if (map_mixw) ckd_free_3d((void *)map_mixw); if (map_tmat) ckd_free_3d((void *)map_tmat); return S3_SUCCESS; } int main(int argc, char *argv[]) { /* define, parse and (partially) validate the command line */ parse_cmd_ln(argc, argv); if (map_update() != S3_SUCCESS) { exit(1); } exit(0); } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/ConfigSceneUtils.java package edu.cmu.sphinx.tools.confdesigner; import org.openide.util.Utilities; import java.awt.*; import java.awt.image.BufferedImage; /** * DOCUMENT ME! * * @author <NAME> */ public class ConfigSceneUtils { public static void initGrids(ConfigScene scene){ Image sourceImage = Utilities.loadImage("test/resources/paper_grid17.png"); // NOI18N int width = sourceImage.getWidth(null); int height = sourceImage.getHeight(null); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.drawImage(sourceImage, 0, 0, null); graphics.dispose(); TexturePaint PAINT_BACKGROUND = new TexturePaint(image, new Rectangle(0, 0, width, height)); scene.setBackground(PAINT_BACKGROUND); scene.repaint(); scene.revalidate(false); scene.validate(); } } <file_sep>/SphinxTrain/src/libs/libcep_feat/norm.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: norm.c * * Description: * This file implements batch CMN for an utterance. * * norm_mean() - compute the mean of the input vectors * and then subtract the mean from the * input vectors. Leave coefficient 0 * untouched. * * Author: * eht (?), faa (?) dunno *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include <s3/norm.h> #include <s3/ckd_alloc.h> #include <s3/prim_type.h> #include <s3/cmd_ln.h> #include <stdio.h> #include <string.h> #include <math.h> void norm_mean (float32 *vec, /* the data */ uint32 nvec, /* number of vectors (frames) */ uint32 veclen) /* number of components per vector */ { static double *mean = 0, *var = 0; double temp; float32 *data; uint32 i, f; const char *normvar = cmd_ln_access("-varnorm"); if (mean == 0) mean = (double *) ckd_calloc (veclen, sizeof (double)); if (var == 0) var = (double *) ckd_calloc (veclen, sizeof (double)); for (i = 0; i < veclen; i++) mean[i] = var[i] = 0.0; /* * Compute the sum */ for (data = vec, f = 0; f < nvec; f++, data += veclen) { for (i = 0; i < veclen; i++) mean[i] += (double)data[i]; } /* * Compute the mean */ for (i = 0; i < veclen; i++) { mean[i] /= (double)nvec; } if (strcmp(normvar,"yes") == 0){ for (data = vec, f = 0; f < nvec; f++, data += veclen) { for (i = 0; i < veclen; i++) var[i] += ((double)data[i]-mean[i])*((double)data[i]-mean[i]); } for (i = 0; i < veclen; i++) { temp = var[i] / (double)nvec; var[i] = sqrt(temp); } } /* * Normalize the data */ for (data = vec, f = 0; f < nvec; f++, data += veclen) { for (i = 0; i < veclen; i++) data[i] -= (float)mean[i]; } if (strcmp(normvar,"yes") == 0){ for (data = vec, f = 0; f < nvec; f++, data += veclen) { for (i = 0; i < veclen; i++) data[i] /= (float)var[i]; } } } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1995/10/17 13:05:04 eht * Cleaned up code a bit so that it is more ANSI compliant * * Revision 1.2 1995/10/10 12:36:12 eht * Changed to use <s3/prim_type.h> * * Revision 1.1 1995/06/02 20:57:22 eht * Initial revision * * */ <file_sep>/CLP/include/LatticeInfo.h // ------------------------------------------------------------------------------------------------------------- // LatticeInfo.h // Stores the general information found in the lattice header for SLF lattices or whatever it can get from FSMs // ------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Copyright (c) nov 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _LatticeInfo_h #define _LatticeInfo_h #include "Prob.h" #include "common_lattice.h" #include <string> class LatticeInfo { friend class Lattice; public: LatticeInfo(const string& infile, const string& graph_type); double Wdpenalty() const {return wdpenalty;} double LMscale() const {return lmscale;} double PRscale() const {return prscale;} LnProb No_links() const {return no_links;} LnProb No_nodes() const {return no_nodes;} const string& Utt() const {return utterance;} const string& Filename() const {return file_name;} friend ostream& operator<<(ostream& os, const LatticeInfo& info); private: string file_name; /* lattice file name */ string type; /* "FSM" or "SLF" depending on the input file */ string utterance; /* the utterance label */ unsigned no_nodes; /* no of nodes in the lattice */ unsigned no_links; /* no of links in the lattice */ double lmscale; /* the language model scale */ double prscale; /* the pronunciation model scale */ double wdpenalty; /* word insertion penalty */ void fill_info_fields(const string& idf, const string& entry); }; #endif <file_sep>/archive_s3/s3.3/src/tests/hub4/Makefile # ==================================================================== # Copyright (c) 2000 <NAME> University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Sphinx III # # ==================================================================== TOP=../../.. DIRNAME=src/tests/hub4 BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) MAINSRCS = dump_frontend.c batch_metrics.c LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile $(SRCS) $(H) LIBNAME= tests LOCAL_INCLUDES = -I$(TOP)/src -I$(TOP)/src/libs3decoder -I$(TOP)/src/libs3audio ALL = $(BINDIR)/dumpfrontend $(BINDIR)/batchmetrics include $(TOP)/config/common_make_rules HUB4_MODEL_DIR=/lab/speech/sphinx4/data/hub4_model HUB4_DIR=/lab/speech/sphinx4/data/hub4/eval99/supervised ifeq ($(CONDITION),) CONDITION = all endif CTL_FILE=$(HUB4_DIR)/$(CONDITION)_hub4.batch $(BINDIR)/dumpfrontend: dump_frontend.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ dump_frontend.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) $(BINDIR)/batchmetrics: batch_metrics.o $(LIVEDECOBJS) $(CC) $(CFLAGS) -o $@ batch_metrics.o $(LIVEDECOBJS) $(LDFLAGS) $(LIBS) hub4_flatunigram: rm -f gmake-hub4_flatunigram.results /bin/cp ARGS.hub4_base ARGS.hub4_flatunigram echo "-lm ${HUB4_MODEL_DIR}/hub4.flat_unigram.lm.DMP" >> ARGS.hub4_flatunigram $(BINDIR)/batchmetrics $(CTL_FILE) / ./ARGS.hub4_flatunigram > gmake-hub4_flatunigram.results hub4_trigram: rm -f gmake-hub4_trigram.results /bin/cp ARGS.hub4_base ARGS.hub4_trigram echo "-lm ${HUB4_MODEL_DIR}/language_model.arpaformat.DMP" >> ARGS.hub4_trigram $(BINDIR)/batchmetrics $(CTL_FILE) / ./ARGS.hub4_trigram > gmake-hub4_trigram.results <file_sep>/SphinxTrain/src/libs/libio/corpus.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: corpus.c * * Description: * This file contains the routines which manage the access of the * data related to each utterance of a speech data corpus. Such * data currently includes MFCC and word transcript data. * One could imagine many more data types however. * * A speech corpus is defined by a control file. It is just a * list of relative paths, one-per-line, for all the utterances * in a speech corpus. Each data type (e.g. MFCC, SENT) must * reside under a single root directory. If a speech corpus * is not unified under a single root directory, it is * assumed that it is easy to construct such a directory * heirarchy using, for example, symbolic links. * * These routines allow partitions of a speech corpus to * be defined for the purpose of distributing the work over * multiple processors. Selection of a set in a partition * may be specified in two ways; either a by a skip count * and a run length or by identifying a set out of N (roughly) * equal sized sets (i.e. part 1 of 10). * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/corpus.h> #include <s3/ckd_alloc.h> #include <s3/read_line.h> #include <s3/prefetch.h> #include <s3/mllr_io.h> #include <sys_compat/file.h> #include <sys_compat/misc.h> #include <s3/acmod_set.h> #include <s3/s2io.h> #include <s3/s3.h> /* System level includes */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <assert.h> /* * Private functions to corpus */ static int strcmp_ci(const char *a, const char *b); static char * fgets_wo_nl(char *str, size_t max, FILE *fp); static int read_sildel(uint32 **del_sf, uint32 **del_ef, uint32 *n_del); static char * mk_filename(uint32 type, char *rel_path); static FILE * open_file_for_reading(uint32 type); static int corpus_read_next_sent_file(char **trans); static int corpus_read_next_lsn_line(char **trans); #define DATA_TYPE_SENT 0 #define DATA_TYPE_MFCC 1 #define DATA_TYPE_SEG 2 #define DATA_TYPE_CCODE 3 #define DATA_TYPE_DCODE 4 #define DATA_TYPE_PCODE 5 #define DATA_TYPE_DDCODE 6 #define DATA_TYPE_MLLR 7 #define DATA_TYPE_PHSEG 8 #define N_DATA_TYPE 9 #define MAX_LSN_LINE 8192 /* The root directory for the speech corpus. Each line of the control * file is appended to this directory */ static const char *data_dir[N_DATA_TYPE]; /* The file name extensions for each data type */ static const char *extension[N_DATA_TYPE]; /* Whether the directory is flat or uses the subdirs in the control * file. */ static int is_flat[N_DATA_TYPE]; /* The name of an LSN file containing all transcripts for the corpus */ static const char *lsn_filename = NULL; /* Standard I/O file pointer for the LSN file */ static FILE *lsn_fp = NULL; /* The current LSN transcript */ static char lsn_line[MAX_LSN_LINE]; /* The current mllr tranform */ static char mllr_line[MAXPATHLEN]; /* Standard I/O file pointer for the silence deletion file */ static FILE *sil_fp = NULL; /* next line of the sildence file file */ static char sil_line[MAXPATHLEN]; static uint32 *del_sf = NULL; static uint32 *del_ef = NULL; static uint32 n_del = 0; /* Standard I/O file pointer for the control file */ static FILE *ctl_fp = NULL; /* Control file lines may be of the following form: * * <path w/o extension> [<start_frame> <end_frame> [<utt_id>]] * */ static char ctl_line_a[8192] = ""; static char ctl_line_b[8192] = ""; #define NO_FRAME 0xffffffff /* The current line from a control file */ static char *cur_ctl_line = ctl_line_a; /* The current path from a control file */ static char *cur_ctl_path = NULL; /* The current start frame ( < 0 indicates NONE) from a control file */ static uint32 cur_ctl_sf = NO_FRAME; /* The current end frame ( < 0 indicates NONE) from a control file */ static uint32 cur_ctl_ef = NO_FRAME; /* The current utt id (NULL indicates NONE) from a control file */ static char *cur_ctl_utt_id = NULL; static char *next_ctl_line = ctl_line_b; static char *next_ctl_path = NULL; /* Flag to indicate whether the application requires MFCC data */ static int32 requires_mfcc = FALSE; /* Flag to indicate whether the application requires sentence * transcripts */ static int32 requires_sent = FALSE; /* Flag to indicate whether the application requires state * segmentations */ static int32 requires_seg = FALSE; /* Flag to indicate whether the application requires phone * segmentations */ static int32 requires_phseg = FALSE; static int32 requires_ccode = FALSE; static int32 requires_dcode = FALSE; static int32 requires_pcode = FALSE; static int32 requires_ddcode = FALSE; #define UNTIL_EOF 0xffffffff static uint32 sv_n_skip = 0; static uint32 sv_run_len = UNTIL_EOF; static uint32 n_run = UNTIL_EOF; static uint32 n_proc = 0; static uint32 begin; static int strcmp_ci(const char *a, const char *b) { char a_lc[1024]; char b_lc[1024]; int i; strcpy(a_lc, a); strcpy(b_lc, b); for (i = 0; i < strlen(a_lc); i++) a_lc[i] = tolower((int)a_lc[i]); for (i = 0; i < strlen(b_lc); i++) b_lc[i] = tolower((int)b_lc[i]); return strcmp(a_lc, b_lc); } static char * fgets_wo_nl(char *str, size_t max, FILE *fp) { char *out; uint32 len; out = fgets(str, max, fp); if (out == NULL) return NULL; len = strlen(out); if (out[len-1] == '\n') out[len-1] = '\0'; else { E_FATAL("input string too long. Truncated.\n"); return NULL; } return out; } int32 corpus_provides_mfcc() { return requires_mfcc; } int32 corpus_provides_sent() { return requires_sent; } int32 corpus_provides_seg() { return requires_seg; } int32 corpus_provides_phseg() { return requires_phseg; } int32 corpus_provides_ccode() { return requires_ccode; } int32 corpus_provides_dcode() { return requires_dcode; } int32 corpus_provides_pcode() { return requires_pcode; } int32 corpus_provides_ddcode() { return requires_ddcode; } static void parse_ctl_line(char *line, char **path, uint32 *sf, uint32 *ef, char **id) { char *sp; char sv_line[4192]; strcpy(sv_line, line); sp = strchr(sv_line, ' '); if (sp == NULL) { /* 'old' style control file */ if (path) *path = strdup(sv_line); if (sf) *sf = NO_FRAME; if (ef) *ef = NO_FRAME; if (id) *id = NULL; } else { *sp = '\0'; if (path) *path = strdup(sv_line); /* at least one space, so try to parse rest of line */ if (sf != NULL) *sf = atoi(sp+1); /* set the start frame */ sp = strchr(sp+1, ' '); if (sp == NULL) { E_FATAL("Control file line must be '<path> [<sf> <ef> [<id>]]', instead saw '%s'\n", line); } if (ef != NULL) *ef = atoi(sp+1); /* set the end frame */ sp = strchr(sp+1, ' '); if (id != NULL) { if (sp == NULL) { /* assume that the optional ID has been omitted */ *id = NULL; } else { *id = strdup(sp+1); /* set the utterance ID */ } } } } /********************************************************************* * * Function: corpus_set_ctl_filename * * Description: * This routine sets the control file used to define the corpus. * It has a side-effect of opening the control file. * * Function Inputs: * const char *ctl_filename - * This is the file name of the control file. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - * Indicates the control file could be opened for reading. * * S3_ERROR - * Indicates some error occured while opening the control file. * * Global Outputs: * None * * Pre-Conditions: * ctl_filename argument must be a pointer to a C string. * * Post-Conditions: * *********************************************************************/ int corpus_set_ctl_filename(const char *ctl_filename) { ctl_fp = fopen(ctl_filename, "r"); if (ctl_fp == NULL) { E_WARN_SYSTEM("Unable to open %s for reading\n", ctl_filename); return S3_ERROR; } if (fgets_wo_nl(next_ctl_line, MAXPATHLEN, ctl_fp) == NULL) { E_ERROR("Must be at least one line in the control file\n"); return S3_ERROR; } parse_ctl_line(next_ctl_line, &next_ctl_path, NULL, NULL, NULL); return S3_SUCCESS; } /********************************************************************* * * Function: corpus_get_begin * * Description: * This function returns the offset of the first utterance to be * processed. This allows the * * Function Inputs: * None * * Global Inputs: * None * * Return Values: * The current skip count to the starting utterance. * * Global Outputs: * None * * Errors: * None * *********************************************************************/ uint32 corpus_get_begin() { return begin; } /********************************************************************* * * Function: corpus_set_interval * * Description: * Defines the interval in the control file over which to run. * The interval is specified by a count of the utterances to skip * followed by a number of utterances to run over. * * Function Inputs: * uint32 n_skip - * The number of utterances in the control file to skip over * * uint32 run_len - * The number of utterances to run over after skipping over * N_SKIP utterances. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, the only possible return value * * Global Outputs: * None * *********************************************************************/ int corpus_set_interval(uint32 n_skip, uint32 run_len) { sv_n_skip = n_skip; sv_run_len = run_len; if (n_skip) { E_INFO("skipping %d utts.\n", n_skip); for (begin = 0; (n_skip > 0) && corpus_next_utt(); --n_skip, begin++); E_INFO("Last utt skipped: %s\n", corpus_utt()); } if (run_len != UNTIL_EOF) n_run = run_len; n_proc = 0; return S3_SUCCESS; } int corpus_reset() { n_run = UNTIL_EOF; assert(ctl_fp); rewind(ctl_fp); if (lsn_fp) rewind(lsn_fp); if (sil_fp) rewind(sil_fp); cur_ctl_line[0] = '\0'; if (fgets_wo_nl(next_ctl_line, MAXPATHLEN, ctl_fp) == NULL) { E_ERROR("Must be at least one line in the control file\n"); return S3_ERROR; } parse_ctl_line(next_ctl_line, &next_ctl_path, NULL, NULL, NULL); /* Position the control file to the * saved values */ corpus_set_interval(sv_n_skip, sv_run_len); return S3_SUCCESS; } /* * This must be done after the processing of the utterance */ int corpus_ckpt(const char *fn) { FILE *fp; char tmp[256]; fp = fopen(fn, "w"); if (fp == NULL) { E_ERROR_SYSTEM("Unable to open chkpt file %s\n", fn); return S3_ERROR; } sprintf(tmp,"%u %u\n", begin + n_proc, n_run); printf("|%s|\n", tmp); if (fprintf(fp, "%u %u\n", begin + n_proc, n_run) != strlen(tmp)) { E_ERROR_SYSTEM("Unable to write %s successfully\n", fn); } fclose(fp); return S3_SUCCESS; } int corpus_ckpt_set_interval(const char *fn) { FILE *fp; uint32 o, rl; fp = fopen(fn, "r"); if (fp == NULL) { E_ERROR_SYSTEM("Can't open ckpt file %s", fn); return S3_ERROR; } if (fscanf(fp, "%u %u", &o, &rl) != 2) { E_ERROR("Problems reading ckpt file %s\n", fn); fclose(fp); return S3_ERROR; } fclose(fp); return corpus_set_interval(o, rl); } /********************************************************************* * * Function: corpus_set_partition * * Description: * This function allows one to specify a set R of a partition of * the corpus into S (roughly) equal sized partitions. * * Function Inputs: * uint32 r - * This argument selects the Rth OF_S sets (R runs from 1..OF_S) * * uint32 of_s - * The number of total (roughly equal sized) sets in the partition. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Operation completed successfully * S3_ERROR - Operation did not complete successfully * * Global Outputs: * None * *********************************************************************/ int corpus_set_partition(uint32 r, uint32 of_s) { uint32 lineno; char ignore[MAXPATHLEN+1]; uint32 run_len; uint32 n_skip; if (ctl_fp == NULL) { E_ERROR("Control file has not been set\n"); return S3_ERROR; } for (lineno = 0; fgets(ignore, MAXPATHLEN+1, ctl_fp); lineno++); rewind(ctl_fp); fgets_wo_nl(next_ctl_line, MAXPATHLEN, ctl_fp); run_len = lineno / of_s; n_skip = (r-1) * run_len; if (r == of_s) run_len = UNTIL_EOF; return corpus_set_interval(n_skip, run_len); } /********************************************************************* * * Function: corpus_set_mfcc_dir * * Description: * Set the root directory for the MFCC data. * * Function Inputs: * const char *dir - * This is the root directory for the MFCC data. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently the only return value. * * Global Outputs: * None * *********************************************************************/ int corpus_set_mfcc_dir(const char *dir) { requires_mfcc = TRUE; data_dir[DATA_TYPE_MFCC] = dir; is_flat[DATA_TYPE_MFCC] = FALSE; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_mllr_dir * * Description: * Set the root directory for the MLLR data. * * Function Inputs: * const char *dir - * This is the root directory for the MLLR data. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently the only return value. * * Global Outputs: * None * *********************************************************************/ int corpus_set_mllr_dir(const char *dir) { data_dir[DATA_TYPE_MLLR] = dir; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_mfcc_ext * * Description: * Set the file name extension for MFCC data files * * Function Inputs: * const char *ext - * This is the file name extension for MFCC file names. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, the only return value * * Global Outputs: * None * *********************************************************************/ int corpus_set_mfcc_ext(const char *ext) { extension[DATA_TYPE_MFCC] = ext; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_seg_dir * * Description: * Set the root directory for the state segmentation data. * * Function Inputs: * const char *dir - * This is the root directory for the state segmentation data. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently the only return value. * * Global Outputs: * None * *********************************************************************/ int corpus_set_seg_dir(const char *dir) { char *tt; requires_seg = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_SEG] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_SEG] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in seg dir is part of a pathname\n"); is_flat[DATA_TYPE_SEG] = FALSE; } } else { is_flat[DATA_TYPE_SEG] = FALSE; } data_dir[DATA_TYPE_SEG] = dir; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_seg_ext * * Description: * Set the file name extension for the state segmentation files * * Function Inputs: * const char *ext - * This is the file name extension for the state segmentation file names. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, the only return value * * Global Outputs: * None * *********************************************************************/ int corpus_set_seg_ext(const char *ext) { extension[DATA_TYPE_SEG] = ext; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_phseg_dir * * Description: * Set the root directory for the phone segmentation data. * * Function Inputs: * const char *dir - * This is the root directory for the phone segmentation data. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently the only return value. * * Global Outputs: * None * *********************************************************************/ int corpus_set_phseg_dir(const char *dir) { char *tt; requires_phseg = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_PHSEG] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_PHSEG] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in phseg dir is part of a pathname\n"); is_flat[DATA_TYPE_PHSEG] = FALSE; } } else { is_flat[DATA_TYPE_PHSEG] = FALSE; } data_dir[DATA_TYPE_PHSEG] = dir; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_phseg_ext * * Description: * Set the file name extension for the phone segmentation files * * Function Inputs: * const char *ext - * This is the file name extension for the phone segmentation file names. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, the only return value * * Global Outputs: * None * *********************************************************************/ int corpus_set_phseg_ext(const char *ext) { extension[DATA_TYPE_PHSEG] = ext; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_sent_dir * * Description: * Set the root directory for word transcripts. This is only * used if corpus_set_lsn_filename() has not been called. * * Function Inputs: * const char *dir - * This is the root directory for the word transcripts. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently the only return value. * * Global Outputs: * None * *********************************************************************/ int corpus_set_sent_dir(const char *dir) { char *tt; assert(lsn_filename == NULL); requires_sent = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_SENT] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_SENT] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in sent dir is part of a pathname\n"); is_flat[DATA_TYPE_SENT] = FALSE; } } else { is_flat[DATA_TYPE_SENT] = FALSE; } data_dir[DATA_TYPE_SENT] = dir; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_sent_ext * * Description: * Set the file name extension for word transcripts. * * Function Inputs: * const char *ext - * This is the file name extension for word transcripts. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, the only return value * * Global Outputs: * None * *********************************************************************/ int corpus_set_sent_ext(const char *ext) { extension[DATA_TYPE_SENT] = ext; return S3_SUCCESS; } int corpus_set_ccode_dir(const char *dir) { char *tt; requires_ccode = TRUE; data_dir[DATA_TYPE_CCODE] = dir; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_CCODE] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_CCODE] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in ccode dir is part of a pathname\n"); is_flat[DATA_TYPE_CCODE] = FALSE; } } else { is_flat[DATA_TYPE_CCODE] = FALSE; } return S3_SUCCESS; } int corpus_set_ccode_ext(const char *ext) { extension[DATA_TYPE_CCODE] = ext; return S3_SUCCESS; } int corpus_set_dcode_dir(const char *dir) { char *tt; requires_dcode = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_DCODE] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_DCODE] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in dcode dir is part of a pathname\n"); is_flat[DATA_TYPE_DCODE] = FALSE; } } else { is_flat[DATA_TYPE_DCODE] = FALSE; } data_dir[DATA_TYPE_DCODE] = dir; return S3_SUCCESS; } int corpus_set_dcode_ext(const char *ext) { extension[DATA_TYPE_DCODE] = ext; return S3_SUCCESS; } int corpus_set_pcode_dir(const char *dir) { char *tt; requires_pcode = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_PCODE] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_PCODE] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in pcode dir is part of a pathname\n"); is_flat[DATA_TYPE_PCODE] = FALSE; } } else { is_flat[DATA_TYPE_PCODE] = FALSE; } data_dir[DATA_TYPE_PCODE] = dir; return S3_SUCCESS; } int corpus_set_pcode_ext(const char *ext) { extension[DATA_TYPE_PCODE] = ext; return S3_SUCCESS; } int corpus_set_ddcode_dir(const char *dir) { char *tt; requires_ddcode = TRUE; tt = strrchr(dir, ','); if (tt != NULL) { if (strcmp(tt+1, "FLAT") == 0) { is_flat[DATA_TYPE_PCODE] = TRUE; *tt = '\0'; } else if (strcmp(tt+1, "CTL") == 0) { is_flat[DATA_TYPE_PCODE] = FALSE; *tt = '\0'; } else { E_INFO("Assuming ',' in pcode dir is part of a pathname\n"); is_flat[DATA_TYPE_PCODE] = FALSE; } } else { is_flat[DATA_TYPE_PCODE] = FALSE; } data_dir[DATA_TYPE_DDCODE] = dir; return S3_SUCCESS; } int corpus_set_ddcode_ext(const char *ext) { extension[DATA_TYPE_DDCODE] = ext; return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_lsn_filename * * Description: * This routine sets and opens a LSN file which must contain all * the word transcripts for corpus. The order of this file must * be the same as the control file. The LSN file is expected to * use the NIST defined LSN format. * * Function Inputs: * const char *fn - * This is the LSN file name. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, this is the only return value. All * errors currently are fatal. * * Global Outputs: * None * *********************************************************************/ int corpus_set_lsn_filename(const char *fn) { assert(data_dir[DATA_TYPE_SENT] == NULL); lsn_filename = fn; requires_sent = TRUE; lsn_fp = fopen(lsn_filename, "r"); if (lsn_fp == NULL) { E_FATAL_SYSTEM("Cannot open LSN filename %s", lsn_filename); } return S3_SUCCESS; } /********************************************************************* * * Function: corpus_set_mllr_filename * * Description: * This routine sets and opens a MLLR file which must contain all * the MLLR transforms for the corpus. The order of this file must * be the same as the control file. * * Function Inputs: * const char *fn - * This is the MLLR file name. * * Global Inputs: * None * * Return Values: * S3_SUCCESS - Currently, this is the only return value. All * errors currently are fatal. * * Global Outputs: * None * *********************************************************************/ int corpus_set_mllr_filename(const char *fn) { const char *mllr_filename = NULL; FILE *mllr_fp = NULL; assert(data_dir[DATA_TYPE_SENT] == NULL); mllr_filename = fn; mllr_fp = fopen(mllr_filename, "r"); if (mllr_fp == NULL) { E_FATAL_SYSTEM("Cannot open MLLR filename %s", mllr_filename); } return S3_SUCCESS; } /********************************************************************* * * Function: corpus_init * * Description: * This routine takes the configuration parameters given by * the corpus_set_*() functions defined above and does any * remaining setup. * * Function Inputs: * None * * Global Inputs: * None * * Return Values: * S3_SUCCESS - No error was found during initialization * S3_ERROR - Some error occurred so that further use of the * corpus module would result in errors. * * Global Outputs: * None * *********************************************************************/ int corpus_init() { /* Currently, just do some sanity checking */ if (ctl_fp == NULL) { E_ERROR("Control file not given before corpus_init() called\n"); return S3_ERROR; } if (requires_sent && (lsn_fp == NULL) && (extension[DATA_TYPE_SENT] == NULL)) { E_ERROR("No lexical entry transcripts given\n"); return S3_ERROR; } if (requires_mfcc && extension[DATA_TYPE_MFCC] == NULL) { E_ERROR("No MFCC extension given\n"); return S3_ERROR; } if (requires_seg && extension[DATA_TYPE_SEG] == NULL) { E_ERROR("No seg extension given\n"); return S3_ERROR; } if (requires_phseg && extension[DATA_TYPE_PHSEG] == NULL) { E_ERROR("No phseg extension given\n"); return S3_ERROR; } if (requires_ccode && extension[DATA_TYPE_CCODE] == NULL) { E_ERROR("No ccode extension given\n"); return S3_ERROR; } if (requires_dcode && extension[DATA_TYPE_DCODE] == NULL) { E_ERROR("No dcode extension given\n"); return S3_ERROR; } if (requires_pcode && extension[DATA_TYPE_PCODE] == NULL) { E_ERROR("No pcode extension given\n"); return S3_ERROR; } if (requires_ddcode && extension[DATA_TYPE_DDCODE] == NULL) { E_ERROR("No ddcode extension given\n"); return S3_ERROR; } if (n_run == UNTIL_EOF) { E_INFO("Will process all remaining utts starting at %d\n", begin); } else { E_INFO("Will process %d utts starting at %d\n", n_run, begin); } return S3_SUCCESS; } int corpus_next_utt() { char *tt; tt = cur_ctl_line; cur_ctl_line = next_ctl_line; next_ctl_line = tt; if (cur_ctl_path) { free(cur_ctl_path); cur_ctl_path = NULL; } if (cur_ctl_utt_id) { free(cur_ctl_utt_id); cur_ctl_utt_id = NULL; } parse_ctl_line(cur_ctl_line, &cur_ctl_path, &cur_ctl_sf, &cur_ctl_ef, &cur_ctl_utt_id); if (next_ctl_path) { free(next_ctl_path); next_ctl_path = NULL; } parse_ctl_line(next_ctl_line, &next_ctl_path, NULL, NULL, NULL); if (n_run != UNTIL_EOF) { if (n_run == 0) return FALSE; --n_run; } ++n_proc; if (strlen(cur_ctl_line) == 0) /* this means that the prior call reached the ctl file EOF */ return FALSE; /* if a big LSN file exists, position it to the correct line */ /* NOTE: corpus_set_ctl_filename() reads the first line of * the control file, so that lsn_fp is one line * behind ctl_fp. */ if (lsn_fp) { if (fgets_wo_nl(lsn_line, MAX_LSN_LINE, lsn_fp) == NULL) { /* ahem! */ E_FATAL("File length mismatch at line %d in %s\n", n_proc, lsn_filename); } } if (sil_fp) { if (del_sf) ckd_free(del_sf); if (del_ef) ckd_free(del_ef); if (fgets_wo_nl(sil_line, MAXPATHLEN, sil_fp) == NULL) sil_line[0] = '\0'; read_sildel(&del_sf, &del_ef, &n_del); } if (fgets_wo_nl(next_ctl_line, MAXPATHLEN, ctl_fp) == NULL) next_ctl_line[0] = '\0'; return TRUE; } char *corpus_utt() { int need_slash = 1; int i; if (cur_ctl_utt_id) return cur_ctl_utt_id; else { if (cur_ctl_path && strlen(cur_ctl_path) > 0) { i = strlen(cur_ctl_path); do { if (cur_ctl_path[--i] == '/') --need_slash; } while ((i > 0) && need_slash); if (i == 0) return cur_ctl_path; else return &cur_ctl_path[i+1]; } else { return "N/A"; } } } char *corpus_utt_brief_name() { int need_slash = 2; int i; if (cur_ctl_path && strlen(cur_ctl_path) > 0) { i = strlen(cur_ctl_path); do { if (cur_ctl_path[--i] == '/') --need_slash; } while ((i > 0) && need_slash); if (i == 0) return cur_ctl_path; else return &cur_ctl_path[i+1]; } else return "N/A"; } char *corpus_utt_full_name() { if (cur_ctl_path && strlen(cur_ctl_path) > 0) { return cur_ctl_path; } else { return "N/A"; } } static char * mk_filename(uint32 type, char *rel_path) { static char fn[MAXPATHLEN]; const char *r; const char *e; char *tt; r = data_dir[type]; e = extension[type]; if (r && e) { if (is_flat[type] == FALSE) { sprintf(fn, "%s/%s.%s", r, rel_path, e); } else { tt = strrchr(rel_path, '/'); if (tt) { ++tt; } else { tt = rel_path; } sprintf(fn, "%s/%s.%s", r, tt, e); } } else if (r) { if (is_flat[type] == FALSE) { sprintf(fn, "%s/%s", r, rel_path); } else { tt = strrchr(rel_path, '/'); if (tt) { ++tt; } else { tt = rel_path; } sprintf(fn, "%s/%s", r, tt); } } else if (e) { sprintf(fn, "%s.%s", rel_path, e); } else { strcpy(fn, rel_path); } return fn; } static FILE * open_file_for_reading(uint32 type) { char *fn; FILE *out; fn = mk_filename(type, cur_ctl_path); out = fopen(fn, "r"); if (out == NULL) { E_WARN_SYSTEM("Unable to open %s for reading\n", fn); } return out; } static int corpus_read_next_sent_file(char **trans) { FILE *fp; char big_str[8192]; /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_SENT, next_ctl_path)); /* open the current file */ fp = open_file_for_reading(DATA_TYPE_SENT); if (fgets_wo_nl(big_str, 8192, fp) == NULL) { E_ERROR("Unable to read data in sent file %s\n", mk_filename(DATA_TYPE_SENT, cur_ctl_path)); return S3_ERROR; } fclose(fp); *trans = strdup(big_str); return S3_SUCCESS; } #include <s3/s2_param.h> /* provides dfn of S2_CEP_VECLEN */ int corpus_get_mfcc(vector_t **mfc, uint32 *n_frame, uint32 *veclen) { vector_t *out; float32 *coeff, **cptr; uint32 n_f; uint32 n_c; uint32 i, j; uint32 ret = S3_ERROR; uint32 no_retries=0; if (!requires_mfcc) { /* asked for mfc data, but not set up to send it */ return S3_ERROR; } if(cur_ctl_sf > cur_ctl_ef){ E_ERROR("Start frame is later than end frame for utt %s \n", corpus_utt()); return S3_ERROR; } if (mfc) cptr = &coeff; else { /* If mfc == NULL, just get the number of frames. */ coeff = NULL; cptr = NULL; } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_MFCC, next_ctl_path)); do { if ((cur_ctl_sf == NO_FRAME) && (cur_ctl_ef == NO_FRAME)) { ret = areadfloat(mk_filename(DATA_TYPE_MFCC, cur_ctl_path), cptr, (int *)&n_c); } else if ((cur_ctl_sf != NO_FRAME) && (cur_ctl_ef != NO_FRAME)) { ret = areadfloat_part(mk_filename(DATA_TYPE_MFCC, cur_ctl_path), cur_ctl_sf * S2_CEP_VECLEN, (cur_ctl_ef + 1) * S2_CEP_VECLEN - 1, cptr, (int *)&n_c); } else { E_FATAL("Both start and end frame must be set in the ctl file\n"); } /* ARCHAN: Unless there is any special reason, new programmer should just do less retries rather than more. The network is always fast enough to handle situation in nowadays. I gave 5 minutes as the possible waiting period. This is more than we should have. */ if (ret == S3_ERROR) { E_ERROR("MFCC read of %s failed. Retrying after sleep...\n", corpus_utt()); sleep(3); no_retries++; if(no_retries>100){ E_FATAL("Failed to get the files after 100 retries of getting MFCC(about 300 seconds)\n "); } } } while (ret == S3_ERROR); if ((ret == 0) && (cur_ctl_sf != NO_FRAME) && (cur_ctl_ef != NO_FRAME)) { E_ERROR("Region [%d %d] for %s extends beyond end of file\n", cur_ctl_sf, cur_ctl_ef, corpus_utt()); } if ((n_c % S2_CEP_VECLEN) != 0) { E_FATAL("Expected mfcc vector len of %d in %s\n", S2_CEP_VECLEN, corpus_utt()); } n_f = n_c / S2_CEP_VECLEN; if (n_f == 0) { if (mfc) *mfc = NULL; if (n_frame) *n_frame = 0; } if (mfc && coeff) { out = (vector_t *)ckd_calloc(n_f, sizeof(vector_t)); for (i = 0, j = 0; i < n_f; i++, j += S2_CEP_VECLEN) { out[i] = &coeff[j]; } *mfc = out; } if (n_frame) *n_frame = n_f; if (veclen) *veclen = S2_CEP_VECLEN; return S3_SUCCESS; } /* ARCHAN: This part of the code need be merged with the corpus_get_generic_featvec. */ /* ADDED BY BHIKSHA TO READ FEATURES OF GENERIC LENGTH. TO ALLOW VECLEN TO BE VALUES OTHER THAN 13. 7 JAN 98 */ int corpus_get_generic_featurevec(vector_t **mfc, uint32 *n_frame, uint32 veclen) { vector_t *out; float32 *coeff, **cptr; uint32 n_f; uint32 n_c; uint32 i, j; uint32 ret=S3_ERROR; uint32 no_retries=0; if (!requires_mfcc) { /* asked for mfc data, but not set up to send it */ return S3_ERROR; } if (mfc) cptr = &coeff; else { /* If mfc == NULL, just get the number of frames. */ coeff = NULL; cptr = NULL; } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_MFCC, next_ctl_path)); do { if ((cur_ctl_sf == NO_FRAME) && (cur_ctl_ef == NO_FRAME)) { ret = areadfloat(mk_filename(DATA_TYPE_MFCC, cur_ctl_path), cptr, (int *)&n_c); } else if ((cur_ctl_sf != NO_FRAME) && (cur_ctl_ef != NO_FRAME)) { ret = areadfloat_part(mk_filename(DATA_TYPE_MFCC, cur_ctl_path), cur_ctl_sf * veclen, (cur_ctl_ef + 1) * veclen - 1, cptr, (int *)&n_c); } else { E_FATAL("Both start and end frame must be set in the ctl file\n"); } if (ret == S3_ERROR) { E_ERROR("MFCC read of %s failed. Retrying after sleep...\n", mk_filename(DATA_TYPE_MFCC, cur_ctl_path)); no_retries++; sleep(3); if(no_retries>100){ E_FATAL("Failed to get the files after 100 retries (about 300 seconds)\n "); } } } while (ret == S3_ERROR); if ((ret == 0) && (cur_ctl_sf != NO_FRAME) && (cur_ctl_ef != NO_FRAME)) { E_ERROR("Region [%d %d] for %s extends beyond end of file\n", cur_ctl_sf, cur_ctl_ef, corpus_utt()); } if ((n_c % veclen) != 0) { E_FATAL("Expected mfcc vector len of %d, got %d (%d)\n", veclen, n_c % veclen, n_c); } n_f = n_c / veclen; if (n_f == 0) { if (mfc) *mfc = NULL; if (n_frame) *n_frame = 0; } if (mfc && coeff) { out = (vector_t *)ckd_calloc(n_f, sizeof(vector_t)); for (i = 0, j = 0; i < n_f; i++, j += veclen) { out[i] = &coeff[j]; } *mfc = out; } if (n_frame) *n_frame = n_f; return S3_SUCCESS; } /* END OF CHANGES BY BHIKSHA */ int corpus_get_ccode(unsigned char **ccode, uint32 *n_frame) { if (!requires_ccode) { /* asked for ccode data, but not set up to send it */ return S3_ERROR; } if ((cur_ctl_sf != NO_FRAME) || (cur_ctl_ef != NO_FRAME)) { E_WARN("Start and end frames not yet implemented for ccode data\n"); } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_CCODE, next_ctl_path)); if (areadchar(mk_filename(DATA_TYPE_CCODE, cur_ctl_path), (char **)ccode, (int32 *)n_frame) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_dcode(unsigned char **dcode, uint32 *n_frame) { if (!requires_dcode) { /* asked for dcode data, but not set up to send it */ return S3_ERROR; } if ((cur_ctl_sf != NO_FRAME) || (cur_ctl_ef != NO_FRAME)) { E_WARN("Start and end frames not yet implemented for dcode data\n"); } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_DCODE, next_ctl_path)); if (areadchar(mk_filename(DATA_TYPE_DCODE, cur_ctl_path), (char **)dcode, (int32 *)n_frame) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_pcode(unsigned char **pcode, uint32 *n_frame) { if (!requires_pcode) { /* asked for pcode data, but not set up to send it */ return S3_ERROR; } if ((cur_ctl_sf != NO_FRAME) || (cur_ctl_ef != NO_FRAME)) { E_WARN("Start and end frames not yet implemented for pcode data\n"); } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_PCODE, next_ctl_path)); if (areadchar(mk_filename(DATA_TYPE_PCODE, cur_ctl_path), (char **)pcode, (int32 *)n_frame) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_ddcode(unsigned char **ddcode, uint32 *n_frame) { if (!requires_ddcode) { /* asked for ddcode data, but not set up to send it */ return S3_ERROR; } if ((cur_ctl_sf != NO_FRAME) || (cur_ctl_ef != NO_FRAME)) { E_WARN("Start and end frames not yet implemented for dcode data\n"); } /* start prefetching the next file, if one. */ if (strlen(next_ctl_path) > 0) (void) prefetch_hint(mk_filename(DATA_TYPE_DDCODE, next_ctl_path)); if (areadchar(mk_filename(DATA_TYPE_DDCODE, cur_ctl_path), (char **)ddcode, (int32 *)n_frame) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_seg(uint16 **seg, uint32 *n_seg) { char *rel_path; if (!requires_seg) { /* asked for seg data, but not set up to send it */ return S3_ERROR; } #if 0 if ((cur_ctl_sf != NO_FRAME) || (cur_ctl_ef != NO_FRAME)) { E_WARN("Start and end frames not yet implemented for seg data\n"); } #endif /* If control file specifies an utt ID, use it. O/W use the path */ if (cur_ctl_utt_id != NULL) rel_path = cur_ctl_utt_id; else rel_path = cur_ctl_path; if (areadshort(mk_filename(DATA_TYPE_SEG, rel_path), (int16 **)seg, (int32 *)n_seg) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_phseg(acmod_set_t *acmod_set, s3phseg_t **out_phseg) { char *rel_path; if (!requires_phseg) { /* asked for seg data, but not set up to send it */ return S3_ERROR; } /* If control file specifies an utt ID, use it. O/W use the path */ if (cur_ctl_utt_id != NULL) rel_path = cur_ctl_utt_id; else rel_path = cur_ctl_path; if (s3phseg_read(mk_filename(DATA_TYPE_PHSEG, rel_path), acmod_set, out_phseg) < 0) return S3_ERROR; return S3_SUCCESS; } int corpus_get_sildel(uint32 **sf, uint32 **ef, uint32 *n_seg) { *sf = del_sf; *ef = del_ef; *n_seg = n_del; return S3_SUCCESS; } static uint32 fullsuffixmatch = 0; void corpus_set_full_suffix_match(uint32 state) { fullsuffixmatch = state; } static int corpus_read_next_lsn_line(char **trans) { char utt_id[512]; char *s; /* look for a close paren in the line */ s = strrchr(lsn_line, ')'); if (s != NULL) { int nspace; /* found a close paren */ nspace = strspn(s + 1, " \t\r\n"); if (s[nspace + 1] == '\0') { /* it is at the end of the line */ *s = '\0'; /* terminate the string at the paren */ /* search for a matching open paren */ for (s--; (s >= lsn_line) && (*s != '('); s--); if (*s == '(') { /* found a matching open paren */ assert(strlen(s+1) < 512); strcpy(utt_id, s+1); /* check LSN utt id (if any) against ctl file utt id */ if (!fullsuffixmatch) { if (strcmp_ci(utt_id, corpus_utt()) != 0) { E_WARN("LSN utt id, %s, does not match ctl utt id, %s.\n", utt_id, corpus_utt()); } } else { char * uttfullname = corpus_utt_full_name(); int suffpos = strlen(uttfullname) - strlen(utt_id); if (suffpos >= 0 && strlen(utt_id) > 0 && strcmp_ci(&uttfullname[suffpos], utt_id) != 0) { E_WARN("LSN utt id, %s, is not a suffix of control file sub-path %s.\n", utt_id, uttfullname); } } /* look for the first non-whitespace character before the open paren */ for (--s; (s >= lsn_line) && isspace((int)*s); s--); if (s < lsn_line) { E_FATAL("Utterance transcription is empty: %s\n", lsn_line); } ++s; *s = '\0'; /* terminate the string at the first whitespace character following the first non-whitespace character found above */ } else { E_ERROR("Expected open paren after ending close paren in line:\n%s", lsn_line); return S3_ERROR; } } else { /* close paren not at end of line so assume it is not the close paren associated with the utt id */ } } else { /* No close paren, so no utt id */ /* This is fine, but the user gets no explicit sanity check for the ordering of the LSN file */ } *trans = strdup(lsn_line); return S3_SUCCESS; } int corpus_get_sent(char **trans) { if (lsn_fp == NULL) return corpus_read_next_sent_file(trans); else return corpus_read_next_lsn_line(trans); } int corpus_has_xfrm() { /* return mllr_fp != NULL; */ return 0; } int corpus_get_xfrm(float32 *****out_a, float32 ****out_b, const uint32 **out_veclen, uint32 *out_n_mllrcls, uint32 *out_n_stream) { char mllrfn[MAXPATHLEN]; if (data_dir[DATA_TYPE_MLLR]) sprintf(mllrfn, "%s/%s", data_dir[DATA_TYPE_MLLR], mllr_line); else { strcpy(mllrfn, mllr_line); } if (read_reg_mat(mllrfn, out_veclen, out_n_mllrcls, out_n_stream, out_a, out_b) != S3_SUCCESS) E_FATAL("Unable to read %s\n",mllrfn); return S3_SUCCESS; } static uint32 sil_lineno; int corpus_set_sildel_filename(const char *file_name) { E_INFO("Silence deletions in %s\n", file_name); sil_fp = fopen(file_name, "r"); if (sil_fp == NULL) { E_FATAL_SYSTEM("Unable to open silence deletion file %s", file_name); } sil_lineno = 0; return 0; } #define OFF 10 static int read_sildel(uint32 **out_sf, uint32 **out_ef, uint32 *out_n_seg) { char *sf_str, *ef_str; char sv[1024]; char *tok; uint32 n_f, n_seg; uint32 sdf; uint32 edf; uint32 *sf; uint32 *ef; strcpy(sv, sil_line); tok = strtok(sil_line, " \t"); if (strcmp_ci(tok, corpus_utt()) != 0) { E_FATAL("ctl file utt == %s, but sildel file utt == %s\n", corpus_utt(), tok); } for (n_f = 0; strtok(NULL, " \t"); n_f++); if (n_f % 2) { E_FATAL("expected even # of fields in sildel file lineno %u\n", sil_lineno); } n_seg = n_f / 2; if (n_seg == 0) { *out_sf = NULL; *out_ef = NULL; *out_n_seg = 0; return S3_SUCCESS; } sf = ckd_calloc(n_seg, sizeof(uint32)); ef = ckd_calloc(n_seg, sizeof(uint32)); strcpy(sil_line, sv); tok = strtok(sil_line, " \t"); n_seg = 0; while ((sf_str = strtok(NULL, " \t")) && (ef_str = strtok(NULL, " \t"))) { sdf = atoi(sf_str) + OFF; edf = atoi(ef_str) - OFF; if ((int)edf - (int)sdf + 1 > 0) { sf[n_seg] = sdf; ef[n_seg] = edf; ++n_seg; } } if (n_seg == 0) { ckd_free(sf); ckd_free(ef); *out_sf = NULL; *out_ef = NULL; *out_n_seg = 0; } else { *out_sf = sf; *out_ef = ef; *out_n_seg = n_seg; } return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.15 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.14 2006/02/23 22:21:26 eht * add -outputfullpath and -fullsuffixmatch arguments to bw. * * Default behavior is to keep the existing system behavior when the * corpus module tries to match the transcript utterance id with the * partial path contained in the control file. * * Using -fullsuffixmatch yes will do the following: * The corpus module will check whether the string contained * inside parentheses in the transcript for the utterances * matches the final part of the control file partial path * for the utterance. For instance, if the control file * partial path is: * tidigits/train/man/ae/243za * the following strings will be considered to match: * 243za * ae/243za * man/ae/243za * . * . * . * In any event, the utterance will be used by bw for training. * This switch just modifies when the warning message for * mismatching control file and transcripts is generated. * * Using -outputfullpath yes will output the entire subpath from the * control file in the log output of bw rather than just the final path * component. This allows for simpler automatic processing of the output * of bw. * * Revision 1.13 2005/11/17 16:28:07 dhdfu * corpus_reset() not working as advertised * * Revision 1.12 2005/11/17 16:15:36 dhdfu * extend the get-length-only thing to corpus_get_mfcc() and friends * * Revision 1.11 2005/09/27 02:01:15 arthchan2003 * Return S3_ERROR when starting frame is larger than ending frame. * * Revision 1.10 2004/11/17 01:46:57 arthchan2003 * Change the sleeping time to be at most 30 seconds. No one will know whether the code dies or not if keep the code loop infinitely. * * Revision 1.8 2004/07/21 18:05:40 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.7 2004/03/01 15:38:00 egouvea * Fixed number of data types, bug report 660181 * * Revision 1.6 2003/11/18 21:07:25 egouvea * Got rid of warning casting the argument to "isspace". * * Revision 1.5 2002/11/13 21:42:52 egouvea * Code breaks if transcription is empty. * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/03/01 00:47:44 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.3 1997/07/18 14:04:51 eht * Added corpus_reset() call * * Revision 1.2 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.1 97/03/17 15:01:49 eht * Initial revision * * Revision 1.19 1996/06/17 14:43:22 eht * Made status output a bit less cryptic * * Revision 1.18 1996/03/26 15:16:26 eht * Fixed defn of local functions * * Revision 1.17 1996/03/25 15:28:02 eht * Added ability to get VQ code files. * * Revision 1.16 1996/03/04 15:52:57 eht * Added capability to use VQ codeword files * * Revision 1.15 1996/02/06 18:45:26 eht * Added corpus_utt_full_name() call to functions that want to get the path * information out. * * Revision 1.14 1996/01/23 18:23:33 eht * Got rid of: * Unused variables * incompatible type error messages for malloced pointers * * Used: * E_ERROR() calls in stead of ad hoc solutions * * Revision 1.13 1995/12/01 19:53:24 eht * - Changed a float to a float32 in the corpus_get_mfcc() prototype * - Changed int6 to uint16 for seg output since bitwise AND operations are * done on seg numbers. * * Revision 1.12 1995/12/01 18:02:17 eht * - Add ability to get state segmentation data per utterance * - Add ability to ignore any data type (e.g. decoder may only be * interested in MFCC data alone). * - Add corpus_utt() function to return just the utterance id. * * Revision 1.11 1995/10/17 14:02:55 eht * Changed so that it would port to Windows NT * * Revision 1.10 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.9 1995/10/09 15:07:37 eht * Moved most of prefetching calls into corpus.c * * Revision 1.8 1995/09/07 19:03:29 eht * Added ability to specify training partitions as part N of R * total equal sized partitions of the control file. * * Revision 1.7 1995/08/29 12:20:29 eht * Changed all configuration calls to be prefixed with * "corpus_set" * * Revision 1.6 1995/08/29 12:11:17 eht * Updated corpus interface so that not so much is * bundled up in the corpus_init() call. I'd rather * that call not change, but be able to do various * kinds of initialization * * Revision 1.5 1995/08/29 11:47:37 eht * Fixed erroneous "LSN file is shorter than ctl file" message * * Revision 1.4 1995/08/24 20:04:58 eht * Added PWP's prefetching changed * * Revision 1.3 1995/08/24 19:30:07 eht * Added global LSN file capability * * Revision 1.2 1995/06/02 20:28:32 eht * Use PWP's error reporting package * * Revision 1.1 1995/06/02 14:52:54 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/src/libmain/hmm.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * hmm.h -- HMM search structure. * * * HISTORY * * 24-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added hmm_vit_trans_comp(). * * 16-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBMAIN_HMM_H_ #define _LIBMAIN_HMM_H_ #include "s3types.h" #include "mdef.h" #include "tmat.h" #include "vithist.h" /* * An individual HMM among the HMM search space. An HMM with N emitting states consists * of N+2 internal states including the non-emitting entry (in) and exit (out) states. * For compatibility with Sphinx-II, we assume that the initial or entry state can only * transition to state 0, and the transition matrix is n_emit_state x (n_emit_state+1), * where the extra destination dimension correponds to the final or exit state. */ typedef struct { /* A single state in the HMM */ int32 score; /* State score (path log-likelihood) */ int32 data; /* Any auxiliary data */ vithist_t *hist; /* Viterbi search history */ } hmm_state_t; typedef struct { /* The HMM */ hmm_state_t *state; /* Per-state data for emitting states */ hmm_state_t in; /* Non-emitting entry state */ hmm_state_t out; /* Non-emitting exit state */ s3pid_t pid; /* Triphone ID */ int32 bestscore; /* Best [emitting] state score in current frame (for pruning) */ s3frmid_t active; /* Frame in which HMM was most recently active */ } hmm_t; /* * Reset the states of the HMM to the invalid or inactive condition; i.e., scores to * LOGPROB_ZERO and hist to NULL. h->*.data values are left undefined. */ void hmm_clear (mdef_t *m, hmm_t *h); /* * Viterbi evaluation of the given HMM through one frame. Emitting states are updated. * NOTE: The dummy, non-emitting exit state is updated separately. In the Viterbi DP * diagram, transitions to the exit state occur from the current time (are vertical). * Hence they should be made only after the history has been logged for the emitting * states. * Return value: The best state score after the update. */ int32 hmm_vit_eval (mdef_t *m, /* In: HMM model definition */ tmat_t *tmat, /* In: HMM topology transition matrices */ hmm_t *h, /* In/Out: HMM to be evaluated; states updated */ int32 *senscore); /* In: Senone scores */ /* * Update the score for the (non-emitting) exit state in the given HMM. */ void hmm_vit_eval_exit (mdef_t *m, /* In: HMM model definition */ tmat_t *tmat, /* In: HMM topology transition matrices */ hmm_t *h); /* In/Out: HMM to be evaluated; states updated */ /* * Enter into the non-emitting initial state of the HMM with the given parameters, * and activate the HMM with the given frame number. */ void hmm_enter (hmm_t *h, /* In/Out: HMM to be updated */ int32 score, /* In: New score entering into the HMM */ int32 data, /* In: New user-defined data */ vithist_t *hist, /* In: New Viterbi history */ s3frmid_t f); /* In: Active in this frame */ /* * Like hmm_enter, but transitions from the dummy exit state of src to the dummy entry * state of dst, iff dst->in.score < src->out.score. The active status of the target * is updated to the given frame if the transition is taken. * Return value: TRUE iff transition taken and the active status actually changed (i.e., * if the status was already == frm, return value would be 0). */ int32 hmm_vit_trans (hmm_t *src, /* In: Source HMM for the transition */ hmm_t *dst, /* In/Out: Destination HMM */ int32 frm); /* In: Frame for which dst is being activated */ /* * Like hmm_vit_comp, but incoming hmm components provided individually, rather than in an * hmm_t structure. */ int32 hmm_vit_trans_comp (int32 score, /* In: Incoming score */ vithist_t *hist, /* In: Incoming Viterbi history */ int32 data, /* In: Incoming auxiliary data */ hmm_t *dst, /* In/Out: Destination HMM */ int32 frm); /* In: Frame for which dst is being activated */ /* For debugging */ void hmm_dump (FILE *fp, mdef_t *m, hmm_t *h); #endif <file_sep>/SphinxTrain/src/libs/libcep_feat/lda.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * lda.c -- Read and apply LDA matrices to features. * * Author: <NAME> <<EMAIL>> */ #include "s3/feat.h" #include "s3/ckd_alloc.h" #include "s3/s3io.h" #include "s3/err.h" #include <assert.h> #include <string.h> #define MATRIX_FILE_VERSION "0.1" float32 *** lda_read(const char *ldafile, uint32 *out_n_lda, uint32 *out_m, uint32 *out_n) { FILE *fh; uint32 byteswap; uint32 chksum, n_lda, m, n; const char *do_chk, *ver; float32 ***lda; if ((fh = s3open(ldafile, "rb", &byteswap)) == NULL) { E_ERROR_SYSTEM("s3open(%s, rb) failed", ldafile); return NULL; } /* check version id */ ver = s3get_gvn_fattr("version"); if (ver) { if (strcmp(ver, MATRIX_FILE_VERSION) != 0) { E_FATAL("Version mismatch for %s, file ver: %s != reader ver: %s\n", ldafile, ver, MATRIX_FILE_VERSION); } } else { E_FATAL("No version attribute for %s\n", ldafile); } /* if do_chk is non-NULL, there is a checksum after the data in the file */ do_chk = s3get_gvn_fattr("chksum0"); if (do_chk && !strcmp(do_chk, "no")) { do_chk = NULL; } chksum = 0; if (s3read_3d((void ****)&lda, sizeof(float32), &n_lda, &m, &n, fh, byteswap, &chksum) < 0) { E_ERROR_SYSTEM("%s: bio_fread_3d(lda) failed\n", ldafile); fclose(fh); return NULL; } if (out_n_lda) *out_n_lda = n_lda; if (out_m) *out_m = m; if (out_n) *out_n = n; return lda; } void lda_transform(float32 ***inout_feat, uint32 nfr, float32 ***lda, uint32 veclen, uint32 dim) { float32 *tmp; uint32 i, j, k; tmp = ckd_calloc(veclen, sizeof(float32)); for (i = 0; i < nfr; ++i) { /* Do the matrix multiplication inline here since fcb->lda * is transposed (eigenvectors in rows not columns). */ /* FIXME: In the future we ought to use the BLAS. */ memset(tmp, 0, sizeof(float32)*veclen); for (j = 0; j < dim; ++j) { for (k = 0; k < veclen; ++k) { tmp[j] += inout_feat[i][0][k] * lda[0][j][k]; } } memcpy(inout_feat[i][0], tmp, veclen * sizeof(float32)); } ckd_free(tmp); } <file_sep>/SphinxTrain/src/libs/libs2io/s2_write_seno.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_read_seno.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_write_seno.h> #include <s3/s2_param.h> #include <s3/ckd_alloc.h> #include <s3/s2io.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/model_inventory.h> #include <s3/common.h> #include <s2/log.h> #include <sys_compat/file.h> static int write_seno_cluster(int32 **seno_cluster, const char *seno_dir, const char *base_name, const char **ext, uint32 n_weights) { unsigned int f; int n_written; char seno_filename[MAXPATHLEN]; E_INFO("writing %d mixture weights for %s\n", n_weights, base_name); for (f = 0; f < S2_N_FEATURE; f++) { sprintf(seno_filename, "%s/%s.%s", seno_dir, base_name, ext[f]); n_written = awriteint(seno_filename, seno_cluster[f], n_weights); if (n_written != n_weights) { fflush(stdout); fprintf(stderr, "%s(%d): had %d weights in %s but only wrote %d\n", __FILE__, __LINE__, n_weights, seno_filename, n_written); fflush(stderr); /* can't reasonably proceed after this kind of wreckage */ exit(1); } } return S3_SUCCESS; } static void norm_log_mixw(float32 ***new_mixw, /* the mixture weight matrix for all shared states */ int32 **old_seno, /* mixture weights for states in a given CI phone */ uint32 ci_id, /* the CI phone associated with the input weights */ uint32 *cluster_offset, /* mixture weight array offsets */ uint32 *state_of) /* the model state associated with each senone. Used only * for CI initialization of CD weights. */ { int32 cd_n_seno; /* # of context dependent senones */ uint32 s_new_mixw_org; /* the first weight id under this CI_ID in the output matrix */ uint32 s_new_mixw_next; /* the first weight id of the next ci in the output matrix */ uint32 s_new_mixw_ci_begin; /* the first CI weight of this CI_ID in the output matrix */ uint32 s_new_mixw_ci_next; /* the next CI weight after the last CI weight for this CI_ID */ uint32 s_in_ci_org; /* the first weight id of the ci weights in the input matrix */ uint32 f; /* a feature stream id */ uint32 s_old_seno; /* a weight id in the input matrix */ uint32 s_new_mixw; /* a weight id in the output matrix */ uint32 cw; /* a codeword index */ s_new_mixw_org = cluster_offset[ci_id]; s_new_mixw_next = cluster_offset[ci_id+1]; cd_n_seno = s_new_mixw_next - s_new_mixw_org; E_INFO("ci_id == %d, cd_n_seno == %d\n", ci_id, cd_n_seno); E_INFO("cluster_offset[%d] == %d\n", ci_id, cluster_offset[ci_id]); E_INFO("cluster_offset[%d] == %d\n", ci_id+1, cluster_offset[ci_id+1]); if (cd_n_seno < 0) { /* can't reasonably proceed after this kind of wreckage */ E_ERROR("Fewer than zero CD senones?!? cd_n_seno == %d = %d - %d\n", cd_n_seno, s_new_mixw_next, s_new_mixw_org); } s_in_ci_org = cd_n_seno; s_new_mixw_ci_begin = ci_id * (S2_N_STATE-1); s_new_mixw_ci_next = s_new_mixw_ci_begin + (S2_N_STATE-1); E_INFO("converting weights to log(weights)\n"); E_INFO("%d CD senones, plus %d CI senones == %d\n", s_in_ci_org, (s_new_mixw_ci_next - s_new_mixw_ci_begin), (s_in_ci_org + (s_new_mixw_ci_next - s_new_mixw_ci_begin))); for (f = 0; f < S2_N_FEATURE; f++) { for (s_new_mixw = s_new_mixw_org, s_old_seno = 0; s_old_seno < s_in_ci_org; s_old_seno++, s_new_mixw++) { vector_normalize(new_mixw[s_new_mixw][f], S2_N_CODEWORD); for (cw = 0; cw < S2_N_CODEWORD; cw++) { old_seno[f][s_old_seno * S2_N_CODEWORD + cw] = LOG(new_mixw[s_new_mixw][f][cw]); } } for (s_new_mixw = s_new_mixw_ci_begin, s_old_seno = s_in_ci_org; s_new_mixw < s_new_mixw_ci_next; s_new_mixw++, s_old_seno++) { vector_normalize(new_mixw[s_new_mixw][f], S2_N_CODEWORD); for (cw = 0; cw < S2_N_CODEWORD; cw++) { old_seno[f][s_old_seno * S2_N_CODEWORD + cw] = LOG(new_mixw[s_new_mixw][f][cw]); } } } } float32 *** s2_write_seno_3(float ***new_mixw, /* the sphinx-3 mixture weights we are saving */ acmod_set_t *acmod_set, /* the phone set of the model inventory */ uint32 *cluster_offset, /* number of senones before each base phone cluster */ const char *seno_dir, /* the directory containing the .ccode, .d2code, etc. files */ uint32 **in_smap, /* An initial global state sharing map */ uint32 *state_of) /* the model state id's for each shared state */ { uint32 i, f; uint32 n_ci; int32 **old_seno; uint32 n_states; uint32 n_base_states; uint32 n_base_weights; const char **seno_filename_ext; seno_filename_ext = ckd_calloc(S2_N_FEATURE, sizeof(char *)); seno_filename_ext[0] = cmd_ln_access("-cepsenoext"); seno_filename_ext[1] = cmd_ln_access("-dcepsenoext"); seno_filename_ext[2] = cmd_ln_access("-powsenoext"); seno_filename_ext[3] = cmd_ln_access("-2dcepsenoext"); n_ci = acmod_set_n_ci(acmod_set); n_states = cluster_offset[n_ci]; #if 0 new_mixw = ckd_calloc_3d(n_states, S2_N_FEATURE, S2_N_CODEWORD, sizeof(float)); #endif E_INFO("%dK in mixture weights\n", n_states * S2_N_CODEWORD * S2_N_FEATURE / 1024); E_INFO("%dK in array overhead\n", ((n_states * S2_N_FEATURE * sizeof(float *)) + (S2_N_FEATURE * sizeof(float **))) / 1024); n_base_weights = (S2_N_STATE-1) * S2_N_CODEWORD; old_seno = (int **) ckd_calloc(S2_N_FEATURE, sizeof(int32 *)); for (i = 0; i < n_ci; i++) { n_base_states = cluster_offset[i+1] - cluster_offset[i]; /* diff of cluster offsets just accounts for shared triphone states, not ci phone states. Add ci state count */ n_base_states += S2_N_STATE-1; n_base_weights = n_base_states * S2_N_CODEWORD; for (f = 0; f < S2_N_FEATURE; f++) { old_seno[f] = (int *) ckd_calloc(n_base_weights, sizeof(int32)); } /* turn new weights into old weights */ norm_log_mixw(new_mixw, old_seno, i, cluster_offset, state_of); write_seno_cluster(old_seno, seno_dir, acmod_set_id2name(acmod_set, i), seno_filename_ext, n_base_weights); for (f = 0; f < S2_N_FEATURE; f++) { ckd_free(old_seno[f]); } } ckd_free(old_seno); return new_mixw; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/02/11 14:52:14 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.6 1995/10/17 14:03:23 eht * Changed to port to Windows NT * * Revision 1.5 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.4 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.3 1995/10/09 15:08:24 eht * changed ckd_alloc interface to remove need for __FILE__, __LINE__ * arguments * * Revision 1.2 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.1 1995/09/07 19:26:41 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/programs/dict2tri/main.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/lexicon.h> #include <s3/model_def_io.h> #include <s3/ckd_alloc.h> #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { const char *basephnfn; FILE *base_fp; const char *dictfn; lexicon_t *lex; acmod_set_t *tri; acmod_id_t p, f, *lctxt, *rctxt, l, b, r, new; word_posn_t posn; uint32 n_lctxt, n_rctxt; uint32 i, l_i, r_i; uint32 n_ci; lex_entry_t *e; const char *no_attrib[2] = { "n/a", NULL }; const char *filler_attrib[2] = { "filler", NULL }; char o_f = '\n'; char b_name[128]; parse_cmd_ln(argc, argv); lex = NULL; basephnfn = (const char *)cmd_ln_access("-basephnfn"); base_fp = fopen(basephnfn, "r"); if (base_fp == NULL) { E_FATAL_SYSTEM("Unable to open %s for reading\n", basephnfn); } /* create a new acoustic model set mapping structure */ tri = acmod_set_new(); for (n_ci = 0; fgets(b_name, 128, base_fp) != NULL; n_ci++); rewind(base_fp); acmod_set_set_n_ci_hint(tri, n_ci); for (p = 0; fgets(b_name, 128, base_fp) != NULL; p++) { b_name[strlen(b_name)-1] = '\0'; if ((strcmp(b_name, "SIL") == 0) || (strcmp(b_name, "SILb") == 0) || (strcmp(b_name, "SILe") == 0) || ((b_name[0] == '+') && (b_name[strlen(b_name)-1] == '+'))) { acmod_set_add_ci(tri, b_name, filler_attrib); } else { acmod_set_add_ci(tri, b_name, no_attrib); } } dictfn = (const char *)cmd_ln_access("-dictfn"); E_INFO("Reading: %s\n", dictfn); lex = lexicon_read(lex, dictfn, tri); if (lex == NULL) { E_FATAL_SYSTEM("Unable to read lexicon file %s", dictfn); } E_INFO("Determining full triphone list\n"); /* set the # of CI phones in the new set */ n_ci = acmod_set_n_ci(tri); rctxt = ckd_calloc(n_ci, sizeof(acmod_id_t)); lctxt = ckd_calloc(n_ci, sizeof(acmod_id_t)); /* set an upper bound on the # of triphones */ acmod_set_set_n_tri_hint(tri, 200000); /* Allow possibility of sil to the left or right of any word */ lctxt[0] = acmod_set_name2id(tri, "SIL"); rctxt[0] = acmod_set_name2id(tri, "SIL"); n_lctxt = n_rctxt = 1; if (*(uint32 *)cmd_ln_access("-btwtri")) { for (e = lex->head; e; e = e->next) { f = e->ci_acmod_id[0]; l = e->ci_acmod_id[e->phone_cnt-1]; if (!acmod_set_has_attrib(tri, f, "filler")) { for (i = 0; i < n_rctxt; i++) if (f == rctxt[i]) break; if (i == n_rctxt) { rctxt[i] = f; ++n_rctxt; } } if (!acmod_set_has_attrib(tri, l, "filler")) { for (i = 0; i < n_lctxt; i++) if (l == lctxt[i]) break; if (i == n_lctxt) { lctxt[i] = l; ++n_lctxt; } } } } E_INFO("%u word begin left context:", n_lctxt); for (i = 0; i < n_lctxt; i++) { E_INFOCONT(" %s", acmod_set_id2name(tri, lctxt[i])); } E_INFOCONT("\n"); E_INFO("%u word end right context:", n_rctxt); for (i = 0; i < n_rctxt; i++) { E_INFOCONT(" %s", acmod_set_id2name(tri, rctxt[i])); } E_INFOCONT("\n"); for (e = lex->head; e; e = e->next) { if (o_f != e->ortho[0]) { o_f = e->ortho[0]; E_INFO("Doing %c\n", o_f); } if (e->phone_cnt == 1) { /* single phone words */ b = e->ci_acmod_id[0]; if (!acmod_set_has_attrib(tri, b, "filler")) { posn = WORD_POSN_SINGLE; for (l_i = 0; l_i < n_lctxt; l_i++) { for (r_i = 0; r_i < n_rctxt; r_i++) { l = lctxt[l_i]; r = rctxt[r_i]; if (acmod_set_tri2id(tri, b, l, r, posn) == NO_ACMOD) { new = acmod_set_add_tri(tri, b, l, r, posn, no_attrib); printf("%s\n", acmod_set_id2name(tri, new)); } } } } } else { b = e->ci_acmod_id[0]; if (!acmod_set_has_attrib(tri, b, "filler")) { r = e->ci_acmod_id[1]; posn = WORD_POSN_BEGIN; for (l_i = 0; l_i < n_lctxt; l_i++) { l = lctxt[l_i]; if (acmod_set_tri2id(tri, b, l, r, posn) == NO_ACMOD) { new = acmod_set_add_tri(tri, b, l, r, posn, no_attrib); printf("%s\n", acmod_set_id2name(tri, new)); } } } posn = WORD_POSN_INTERNAL; for (i = 1; i < e->phone_cnt-1; i++) { b = e->ci_acmod_id[i]; if (!acmod_set_has_attrib(tri, b, "filler")) { r = e->ci_acmod_id[i+1]; l = e->ci_acmod_id[i-1]; if (acmod_set_tri2id(tri, b, l, r, posn) == NO_ACMOD) { new = acmod_set_add_tri(tri, b, l, r, posn, no_attrib); printf("%s\n", acmod_set_id2name(tri, new)); } } } b = e->ci_acmod_id[e->phone_cnt-1]; if (!acmod_set_has_attrib(tri, b, "filler")) { l = e->ci_acmod_id[e->phone_cnt-2]; posn = WORD_POSN_END; for (r_i = 0; r_i < n_rctxt; r_i++) { r = rctxt[r_i]; if (acmod_set_tri2id(tri, b, l, r, posn) == NO_ACMOD) { new = acmod_set_add_tri(tri, b, l, r, posn, no_attrib); printf("%s\n", acmod_set_id2name(tri, new)); } } } } } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:22 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libfbs/cmn.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * cmn.c -- Various forms of cepstral mean normalization * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 19-Jun-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Changed to compute CMN over ALL dimensions of cep instead of 1..12. * * 04-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Created. */ #include <assert.h> #include <libutil/libutil.h> #include "cmn.h" #include <math.h> #include <string.h> /* * Normalize all cepstral vectors (except C0) by subtracting the mean for the * entire utterance. */ void norm_mean (float32 **mfc, int32 n_frame, int32 veclen) { static float32 *mean = 0, *var = 0; float *mfcp; int32 i, f, normvar; char *varnorm; varnorm = (char *) cmd_ln_access ("-varnorm"); if (strcmp(varnorm,"yes")==0) normvar = 1; else normvar = 0; if (normvar) E_INFO("Normalizing utterance variance\n"); assert ((n_frame > 0) && (veclen > 0)); if (mean == 0) mean = (float32 *) ckd_calloc (veclen, sizeof (float32)); if (var == 0) var = (float32 *) ckd_calloc (veclen, sizeof (float32)); for (i = 0; i < veclen; i++) mean[i] = var[i] = 0.0; for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mean[i] += mfcp[i]; } for (i = 0; i < veclen; i++) mean[i] /= n_frame; if (normvar) { for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) var[i] += (mfcp[i]-mean[i])*(mfcp[i]-mean[i]); } for (i = 0; i < veclen; i++) var[i] = (float)sqrt((double)var[i]/(double)n_frame); /* std dev */ } for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mfcp[i] -= mean[i]; } if (normvar) { for (f = 0; f < n_frame; f++) { mfcp = mfc[f]; for (i = 0; i < veclen; i++) mfcp[i] /= var[i]; } } } <file_sep>/SphinxTrain/src/programs/agg_seg/cnt_st_seg.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cnt_st_seg.c * * Description: * * Author: * *********************************************************************/ #include "cnt_st_seg.h" #include <s3/lexicon.h> #include <s3/corpus.h> #include <s3/segdmp.h> #include <s3/feat.h> #include <s3/ck_seg.h> #include <s3/mk_sseq.h> #include <s3/mk_phone_seq.h> #include <s3/ckd_alloc.h> static uint32 * get_next_sseq(model_def_t *mdef, lexicon_t *lex, uint32 *out_n_frame) { char *trans; uint16 *seg; uint32 n_frame; acmod_id_t *phone; uint32 n_phone; uint32 *sseq; corpus_get_sent(&trans); corpus_get_seg(&seg, &n_frame); mk_phone_seq(&phone, &n_phone, trans, mdef->acmod_set, lex); ck_seg(mdef->acmod_set, phone, n_phone, seg, n_frame, corpus_utt()); sseq = mk_sseq(seg, n_frame, phone, n_phone, mdef); ckd_free(phone); ckd_free(seg); ckd_free(trans); *out_n_frame = n_frame; return sseq; } uint32 * cnt_st_seg(model_def_t *mdef, lexicon_t *lex) { uint32 seq_no; uint32 n_frame; uint32 *sseq; uint32 *n_frame_per; uint32 i; E_INFO("Counting # occ. for %u tied states\n", mdef->n_tied_state); n_frame_per = ckd_calloc(mdef->n_tied_state, sizeof(uint32)); for (seq_no = corpus_get_begin(); corpus_next_utt(); seq_no++) { if (!(seq_no % 250)) { fprintf(stderr, " cnt[%u]", seq_no); fflush(stderr); } /* Read transcript and convert it into a senone sequence */ sseq = get_next_sseq(mdef, lex, &n_frame); if (sseq == NULL) { E_WARN("senone sequence not produced; skipping.\n"); continue; } for (i = 0; i < n_frame; i++) { n_frame_per[sseq[i]]++; } ckd_free(sseq); } for (i = 0; i < mdef->n_tied_state; i++) { E_INFO("ts= %u cnt= %u\n", i, n_frame_per[i]); } return n_frame_per; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/share/lm3g2dmp/lm3g2dmp.c /* $Header$ * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1995 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * lm_3g.c -- Darpa Trigram LM module. * * HISTORY * * 12-Feb-2000 <NAME> (rkm@cs) at Carnegie Mellon University * Adapted from original version, for standalone compilation and running. * * 03-Apr-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Added lm3g_raw_score() and lm_t.invlw. * Changed a number of function names from lm_... to lm3g_... * * 09-Jan-97 <NAME> (r<EMAIL>) at Carnegie Mellon University * BUGFIX: Added check for lmp->unigrams[i].wid in lm_set_current(). * * 06-Dec-95 <NAME> (rkm@cs) at Carnegie Mellon University * Changed function name lmname_to_lm() to lm_name2lm(). * * 06-Dec-95 <NAME> (rkm@cs) at Carnegie Mellon University * Changed function name get_current_lm to lm_get_current. * Changed check for already existing word in lm_add_word, and added * condition to updating dictwid_map. * * 01-Jul-95 <NAME> (r<EMAIL>) at Carnegie Mellon University * Removed LM cache and replaced with find_bg and find_tg within the main * bigrams and trigram structures. No loss of speed and uses less memory. * * 24-Jun-95 <NAME> (r<EMAIL>) at Carnegie Mellon University * Fixed a number of memory leaks while deleting an LM. Added the global * dictwid_map, and allocated it once and never freed. Made sure lm_cache * is created only once. * * 14-Jun-95 <NAME> (<EMAIL>) at Carnegie Mellon University * Modified lm_read to return 0 on success, and to delete any existing LM * with the new LM name (instead of reporting error and exiting). * Added backslash option in building filenames (for PC compatibility). * * $Log$ * Revision 1.2 2005/07/21 19:42:47 egouvea * Cleaned up code so it compiles with MS Visual C++. Added MS VC++ * support files (.dsp and .dsw). * * Revision 1.1 2002/11/11 17:42:40 egouvea * Initial import of lm3g2dmp from Ravi's files. * * Revision 1.1.1.1 2000/02/28 18:34:43 rkm * Imported Sources * * Revision 8.9 94/10/11 12:36:28 rkm * Changed lm_tg_score to call lm_bg_score if no trigrams present or * the first word is invalid. * * Revision 8.8 94/07/29 11:54:23 rkm * Renamed lmSetParameters to lm_set_param and moved it into lm_add(). * Added functions lm_init_oov() to create initial list of OOVs, * and lm_add_word() to add new OOV at run time. * * Revision 8.7 94/05/19 14:19:59 rkm * Rewrote LM cache code for greater efficiency. * * Revision 8.6 94/05/10 10:47:58 rkm * Added lm_add() and lm_set_param() functions, for dynamically adding a new * in-memory LM to the set of available LMs. * * Revision 8.5 94/04/22 13:53:27 rkm * Added query_lm_cache_lines() to allow run-time spec of #cache lines. * * Revision 8.4 94/04/14 15:08:46 rkm * Added function lm_delete() to delete a named LM and reclaim space. * * Revision 8.3 94/04/14 14:40:27 rkm * Minor changes. * * Revision 8.1 94/02/15 15:09:22 rkm * Derived from v7. Includes multiple LMs for grammar switching. * * Revision 6.13 94/02/11 13:14:45 rkm * Added bigram and trigram multi-line caches, and functions, for v7. * Replaced sequential search in wstr2wid() with hash_lookup(). * * Revision 6.12 94/01/07 10:56:16 rkm * Corrected bug relating to input file format. * * Revision 6.11 93/12/17 13:14:52 rkm * *** empty log message *** * * Revision 6.10 93/12/03 17:09:59 rkm * Added ability to handle bigram-only dump files. * Added <s> </s> bigram -> MIN_PROB. * Added timestamp to dump files. * * Revision 6.9 93/12/01 12:29:55 rkm * Added ability to handle LM files containing only bigrams. * Excluded start_sym from interpolation of unigram prob with uniform prob. * * * 93/10/21 <EMAIL> * Added <c.h> * * Revision 6.6 93/10/19 18:58:10 rkm * Added code to change bigram-prob(<s>,<s>) to very low value. The * Darpa LM file contains a spurious value to be ignored. * Fixed bug that dumps one trigram entry too many. * * Revision 6.5 93/10/15 15:00:14 rkm * * Revision 6.4 93/10/13 16:56:04 rkm * Added LM cache line stats. * Added bg_only option for lm_read parameter list * (but not yet implemented). * Changed proc name ilm_LOG_prob_of to lm3g_prob, to avoid conflict * with Roni's ILM function of the same name. * * Revision 6.3 93/10/09 17:01:55 rkm * <NAME> (<EMAIL>) at Carnegie Mellon * Cleaned up handling precompiled binary 3g LM file, * Added SWAP option for HP platforms. * * Revision 6.2 93/10/06 11:08:15 rkm * <NAME> (<EMAIL>) at Carnegie Mellon University * Darpa Trigram LM module. Created. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <assert.h> #include "primtype.h" #include "hash.h" #include "lm_3g.h" #include "CM_macros.h" #include "err.h" #define NO_WORD -1 static char *dumpdir; static char *start_sym = "<s>"; static char *end_sym = "</s>"; static char *darpa_hdr = "Darpa Trigram LM"; /* The currently active LM */ static lm_t *lmp; /* Run-time determined versions of compile-time constants BG_SEG_SZ and LOG_BG_SEG_SZ */ static int32 bg_seg_sz; static int32 log_bg_seg_sz; /* HACK!! Re-define these macros from lm_3g.h to make them run-time constants */ #undef TSEG_BASE #undef FIRST_TG #undef LAST_TG #define TSEG_BASE(m,b) ((m)->tseg_base[(b)>>log_bg_seg_sz]) #define FIRST_TG(m,b) (TSEG_BASE((m),(b))+((m)->bigrams[b].trigrams)) #define LAST_TG(m,b) (FIRST_TG((m),(b)+1)-1) /* Single dictionary->LM wid map for the currently active LM */ static int32 *dictwid_map = NULL; static int32 lm3g_dump (); extern char *salloc(); extern char *listelem_alloc (); extern void listelem_free (); /* Words in LM; used only for building internal LM from LM file */ static char **word_str; #define MIN_PROB_F -99.0 #define MAX_SORTED_ENTRIES 65534 /* * Bigram probs and bo-wts, and trigram probs are kept in separate tables * rather than within the bigram_t and trigram_t structures. These tables * hold unique prob and bo-wt values, and can be < 64K long (see lm_3g.h). * The following tree structure is used to construct these tables of unique * values. Whenever a new value is read from the LM file, the sorted tree * structure is searched to see if the value already exists, and inserted * if not found. */ typedef struct sorted_entry_s { log_t val; /* value being kept in this node */ u_int16 lower; /* index of another entry. All descendants down this path have their val < this node's val. 0 => no son exists (0 is root index) */ u_int16 higher; /* index of another entry. All descendants down this path have their val > this node's val 0 => no son exists (0 is root index) */ } sorted_entry_t; /* * The sorted list. list is a (64K long) array. The first entry is the * root of the tree and is created during initialization. */ typedef struct { sorted_entry_t *list; int32 free; /* first free element in list */ } sorted_list_t; /* Arrays of unique bigram probs and bo-wts, and trigram probs */ static sorted_list_t sorted_prob2; static sorted_list_t sorted_bo_wt2; static sorted_list_t sorted_prob3; /* * Initialize sorted list with the 0-th entry = MIN_PROB_F, which may be needed * to replace spurious values in the Darpa LM file. */ static void init_sorted_list (l) sorted_list_t *l; { l->list = (sorted_entry_t *) CM_calloc (MAX_SORTED_ENTRIES, sizeof (sorted_entry_t)); l->list[0].val.f = MIN_PROB_F; l->list[0].lower = 0; l->list[0].higher = 0; l->free = 1; } static void free_sorted_list (l) sorted_list_t *l; { free (l->list); } static log_t *vals_in_sorted_list (l) sorted_list_t *l; { log_t *vals; int32 i; vals = (log_t *) CM_calloc (l->free, sizeof (log_t)); for (i = 0; i < l->free; i++) vals[i].f = l->list[i].val.f; return (vals); } static int32 sorted_id (l, val) sorted_list_t *l; float *val; { int32 i = 0; for (;;) { if (*val == l->list[i].val.f) return (i); if (*val < l->list[i].val.f) { if (l->list[i].lower == 0) { if (l->free >= MAX_SORTED_ENTRIES) E_FATAL("sorted list overflow\n"); l->list[i].lower = l->free; (l->free)++; i = l->list[i].lower; l->list[i].val.f = *val; return (i); } else i = l->list[i].lower; } else { if (l->list[i].higher == 0) { if (l->free >= MAX_SORTED_ENTRIES) E_FATAL("sorted list overflow\n"); l->list[i].higher = l->free; (l->free)++; i = l->list[i].higher; l->list[i].val.f = *val; return (i); } else i = l->list[i].higher; } } } /* * allocate, initialize and return pointer to an array of unigram entries. */ static unigram_t *NewUnigramTable (n_ug) int32 n_ug; { unigram_t *table; int32 i; table = (unigram_t *) CM_calloc (n_ug, sizeof (unigram_t)); for (i = 0; i < n_ug; i++) { table[i].wid = NO_WORD; table[i].prob1.f = -99.0; table[i].bo_wt1.f = -99.0; } return table; } /* * returns a pointer to a new language model record. The size is passed in * as a parameter. */ lm_t * NewModel (n_ug, n_bg, n_tg, n_dict) int32 n_ug; int32 n_bg; int32 n_tg; int32 n_dict; { lm_t *model; int32 i; model = (lm_t *) CM_calloc (1, sizeof (lm_t)); /* * Allocate one extra unigram and bigram entry: sentinels to terminate * followers (bigrams and trigrams, respectively) of previous entry. */ model->unigrams = NewUnigramTable (n_ug+1); model->bigrams = (bigram_t *) CM_calloc (n_bg+1, sizeof (bigram_t)); if (n_tg > 0) model->trigrams = (trigram_t *) CM_calloc (n_tg, sizeof (trigram_t)); /* Allocate dictwid_map only once; shared among all LMs; valid only for current LM */ if (dictwid_map == NULL) dictwid_map = (int32 *) CM_calloc (n_dict, sizeof (int32)); model->dictwid_map = dictwid_map; for (i = 0; i < n_dict; i++) model->dictwid_map[i] = 0x80000000; /* an illegal index into unigrams */ if (n_tg > 0) { model->tseg_base = (int32 *) CM_calloc ((n_bg+1)/bg_seg_sz+1, sizeof (int32)); #if 0 E_INFO("%8d = tseg_base entries allocated\n", (n_bg+1)/bg_seg_sz+1); #endif } model->max_ucount = model->ucount = n_ug; model->bcount = n_bg; model->tcount = n_tg; model->dict_size = n_dict; model->HT.size = 0; model->HT.inuse = 0; model->HT.tab = NULL; return model; } static int32 wstr2wid (lm_t *model, char *w) { caddr_t val; if (hash_lookup (&(model->HT), w, &val) != 0) return NO_WORD; return ((int32) val); } /* * Read and return #unigrams, #bigrams, #trigrams as stated in input file. */ static void ReadNgramCounts (fp, n_ug, n_bg, n_tg) FILE *fp; int32 *n_ug, *n_bg, *n_tg; /* return the info here */ { char string[256]; int32 ngram, ngram_cnt; /* skip file until past the '\data\' marker */ do fgets (string, sizeof (string), fp); while ( (strcmp (string, "\\data\\\n") != 0) && (! feof (fp)) ); if (strcmp (string, "\\data\\\n") != 0) E_FATAL("No \\data\\ mark in LM file\n"); *n_ug = *n_bg = *n_tg = 0; while (fgets (string, sizeof (string), fp) != NULL) { if (sscanf (string, "ngram %d=%d", &ngram, &ngram_cnt) != 2) break; switch (ngram) { case 1: *n_ug = ngram_cnt; break; case 2: *n_bg = ngram_cnt; break; case 3: *n_tg = ngram_cnt; break; default: E_FATAL("Unknown ngram (%d)\n", ngram); break; } } /* Position file to just after the unigrams header '\1-grams:\' */ while ( (strcmp (string, "\\1-grams:\n") != 0) && (! feof (fp)) ) fgets (string, sizeof (string), fp); /* Check counts; NOTE: #trigrams *CAN* be 0 */ if ((*n_ug <= 0) || (*n_bg <= 0) || (*n_tg < 0)) E_FATAL("Bad or missing ngram count\n"); } /* * Read in the unigrams from given file into the LM structure model. On * entry to this procedure, the file pointer is positioned just after the * header line '\1-grams:'. */ static void ReadUnigrams (fp, model) FILE *fp; /* input file */ lm_t *model; /* to be filled in */ { char string[256]; char name[128]; int32 wcnt; float p1, bo_wt; double ignored_prob = 0.0; E_INFO("Reading unigrams\n"); fflush (stdout); wcnt = 0; while ((fgets (string, sizeof(string), fp) != NULL) && (strcmp (string, "\\2-grams:\n") != 0)) { if (sscanf (string, "%f %s %f", &p1, name, &bo_wt) != 3) { if (string[0] != '\n') E_WARN("Format error; unigram ignored: %s", string); continue; } if (wcnt >= model->ucount) E_FATAL("Too many unigrams\n"); /* Associate name with word id */ word_str[wcnt] = (char *) salloc (name); hash_add (&(model->HT), word_str[wcnt], (caddr_t) wcnt); model->unigrams[wcnt].prob1.f = p1; model->unigrams[wcnt].bo_wt1.f = bo_wt; model->unigrams[wcnt].wid = wcnt; wcnt++; } if (model->ucount != wcnt) { E_WARN("lm_t.ucount(%d) != #unigrams read(%d)\n", model->ucount, wcnt); model->ucount = wcnt; } } /* * Read bigrams from given file into given model structure. File may be arpabo * or arpabo-id format, depending on idfmt = 0 or 1. */ static void ReadBigrams (FILE *fp, lm_t *model, int32 idfmt) { char string[1024], word1[256], word2[256]; int32 w1, w2, prev_w1, bgcount, p; bigram_t *bgptr; float p2, bo_wt; int32 n_fld, n; E_INFO("Reading bigrams\n"); fflush (stdout); bgcount = 0; bgptr = model->bigrams; prev_w1 = -1; n_fld = (model->tcount > 0) ? 4 : 3; bo_wt = 0.0; while (fgets (string, sizeof(string), fp) != NULL) { if (! idfmt) n = sscanf (string, "%f %s %s %f", &p2, word1, word2, &bo_wt); else n = sscanf (string, "%f %d %d %f", &p2, &w1, &w2, &bo_wt); if (n < n_fld) { if (string[0] != '\n') break; continue; } if (! idfmt) { if ((w1 = wstr2wid (model, word1)) == NO_WORD) E_FATAL("Unknown word: %s\n", word1); if ((w2 = wstr2wid (model, word2)) == NO_WORD) E_FATAL("Unknown word: %s\n", word2); } else { if ((w1 >= model->ucount) || (w2 >= model->ucount) || (w1 < 0) || (w2 < 0)) E_FATAL("Bad bigram: %s", string); } /* HACK!! to quantize probs to 4 decimal digits */ p = (int) (p2*10000); p2 = (float) (p*0.0001); p = (int) (bo_wt*10000); bo_wt = (float) (p*0.0001); if (bgcount >= model->bcount) E_FATAL("Too many bigrams\n"); bgptr->wid = w2; bgptr->prob2 = sorted_id (&sorted_prob2, &p2); if (model->tcount > 0) bgptr->bo_wt2 = sorted_id (&sorted_bo_wt2, &bo_wt); if (w1 != prev_w1) { if (w1 < prev_w1) E_FATAL("Bigrams not in unigram order\n"); for (prev_w1++; prev_w1 <= w1; prev_w1++) model->unigrams[prev_w1].bigrams = bgcount; prev_w1 = w1; } bgcount++; bgptr++; if ((bgcount & 0x0000ffff) == 0) { printf ("."); fflush (stdout); } } if ((strcmp (string, "\\end\\\n") != 0) && (strcmp (string, "\\3-grams:\n") != 0)) E_FATAL("Bad bigram: %s\n", string); for (prev_w1++; prev_w1 <= model->ucount; prev_w1++) model->unigrams[prev_w1].bigrams = bgcount; } /* * Very similar to ReadBigrams. */ static void ReadTrigrams (FILE *fp, lm_t *model, int32 idfmt) { char string[1024], word1[256], word2[256], word3[256]; int32 i, n, w1, w2, w3, prev_w1, prev_w2, tgcount, prev_bg, bg, endbg, p; int32 seg, prev_seg, prev_seg_lastbg, tgoff; trigram_t *tgptr; bigram_t *bgptr; float p3; E_INFO("Reading trigrams\n"); fflush (stdout); tgcount = 0; tgptr = model->trigrams; prev_w1 = -1; prev_w2 = -1; prev_bg = -1; prev_seg = -1; while (fgets (string, sizeof(string), fp) != NULL) { if (! idfmt) n = sscanf (string, "%f %s %s %s", &p3, word1, word2, word3); else n = sscanf (string, "%f %d %d %d", &p3, &w1, &w2, &w3); if (n != 4) { if (string[0] != '\n') break; continue; } if (! idfmt) { if ((w1 = wstr2wid (model, word1)) == NO_WORD) E_FATAL("Unknown word: %s\n", word1); if ((w2 = wstr2wid (model, word2)) == NO_WORD) E_FATAL("Unknown word: %s\n", word2); if ((w3 = wstr2wid (model, word3)) == NO_WORD) E_FATAL("Unknown word: %s\n", word3); } else { if ((w1 >= model->ucount) || (w2 >= model->ucount) || (w3 >= model->ucount) || (w1 < 0) || (w2 < 0) || (w3 < 0)) E_FATAL("Bad trigram: %s", string); } /* HACK!! to quantize probs to 4 decimal digits */ p = (int) (p3*10000); p3 = (float) (p*0.0001); if (tgcount >= model->tcount) E_FATAL("Too many trigrams\n"); tgptr->wid = w3; tgptr->prob3 = sorted_id (&sorted_prob3, &p3); if ((w1 != prev_w1) || (w2 != prev_w2)) { /* Trigram for a new bigram; update tg info for all previous bigrams */ if ((w1 < prev_w1) || ((w1 == prev_w1) && (w2 < prev_w2))) E_FATAL("Trigrams not in bigram order\n"); bg = (w1 != prev_w1) ? model->unigrams[w1].bigrams : prev_bg+1; endbg = model->unigrams[w1+1].bigrams; bgptr = model->bigrams + bg; for (; (bg < endbg) && (bgptr->wid != w2); bg++, bgptr++); if (bg >= endbg) E_FATAL("Missing bigram for trigram: %s", string); /* bg = bigram entry index for <w1,w2>. Update tseg_base */ seg = bg >> log_bg_seg_sz; for (i = prev_seg+1; i <= seg; i++) model->tseg_base[i] = tgcount; /* Update trigrams pointers for all bigrams until bg */ if (prev_seg < seg) { if (prev_seg >= 0) { tgoff = tgcount - model->tseg_base[prev_seg]; if (tgoff > 65535) E_FATAL("Offset from tseg_base > 65535; reduce log2(bg_seg_sz)\n"); } prev_seg_lastbg = ((prev_seg+1) << log_bg_seg_sz) - 1; bgptr = model->bigrams + prev_bg; for (++prev_bg, ++bgptr; prev_bg <= prev_seg_lastbg; prev_bg++, bgptr++) bgptr->trigrams = tgoff; for (; prev_bg <= bg; prev_bg++, bgptr++) bgptr->trigrams = 0; } else { tgoff = tgcount - model->tseg_base[prev_seg]; if (tgoff > 65535) E_FATAL("Offset from tseg_base > 65535; reduce log2(bg_seg_sz)\n"); bgptr = model->bigrams + prev_bg; for (++prev_bg, ++bgptr; prev_bg <= bg; prev_bg++, bgptr++) bgptr->trigrams = tgoff; } prev_w1 = w1; prev_w2 = w2; prev_bg = bg; prev_seg = seg; } tgcount++; tgptr++; if ((tgcount & 0x0000ffff) == 0) { printf ("."); fflush (stdout); } } if (strcmp (string, "\\end\\\n") != 0) E_FATAL("Bad trigram: %s\n", string); for (prev_bg++; prev_bg <= model->bcount; prev_bg++) { if ((prev_bg & (bg_seg_sz-1)) == 0) model->tseg_base[prev_bg >> log_bg_seg_sz] = tgcount; if ((tgcount - model->tseg_base[prev_bg >> log_bg_seg_sz]) > 65535) E_FATAL("Offset from tseg_base > 65535; reduce log2(bg_seg_sz)\n"); model->bigrams[prev_bg].trigrams = tgcount - model->tseg_base[prev_bg >> log_bg_seg_sz]; } } static FILE *lm_file_open (filename, usepipe) char *filename; int32 usepipe; { char command[1024]; FILE *fp; if (usepipe) { #ifdef WIN32 sprintf (command, "D:\\compress\\gzip.exe -d -c %s", filename); if ((fp = _popen (command, "r")) == NULL) E_FATAL("Cannot popen %s\n", command); #else sprintf (command, "zcat %s", filename); if ((fp = popen (command, "r")) == NULL) E_FATAL("Cannot popen %s\n", command); #endif } else { fp = CM_fopen (filename, "r"); } return (fp); } /* * Reads in a trigram language model from the given file. */ int32 lm_read (char *filename, char *lmname) { lm_t *model; FILE *fp = NULL; int32 usingPipe = 0; int32 n_unigram; int32 n_bigram; int32 n_trigram; int32 dict_size; int32 i, k; char dumpfile[4096]; struct stat statbuf; int32 idfmt; E_INFO("Reading LM file %s (name \"%s\")\n", filename, lmname); /* Check if a compressed file */ k = strlen(filename); #ifdef WIN32 usingPipe = (k > 3) && ((strcmp (filename+k-3, ".gz") == 0) || (strcmp (filename+k-3, ".GZ") == 0)); #else usingPipe = (k > 2) && ((strcmp (filename+k-2, ".Z") == 0) || (strcmp (filename+k-2, ".z") == 0)); #endif /* Check if an .arpabo-id format file; More HACK!! Hardwired check for -id */ if (usingPipe) k -= 2; idfmt = ((k > 3) && (strncmp (filename+k-3, "-id", 3) == 0)); fp = lm_file_open (filename, usingPipe); if (stat(filename, &statbuf) < 0) E_FATAL("stat(%s) failed\n", filename); /* Read #unigrams, #bigrams, #trigrams from file */ ReadNgramCounts (fp, &n_unigram, &n_bigram, &n_trigram); E_INFO("ngrams 1=%d, 2=%d, 3=%d\n", n_unigram, n_bigram, n_trigram); /* Determine dictionary size (for dict-wid -> LM-wid map) */ dict_size = n_unigram; if (dict_size >= 65535) E_FATAL("#dict-words(%d) > 65534\n", dict_size); /* Allocate space for LM, including initial OOVs and placeholders; initialize it */ model = lmp = NewModel (n_unigram, n_bigram, n_trigram, dict_size); word_str = (char **) CM_calloc (n_unigram, sizeof (char *)); /* Create name for binary dump form of Darpa LM file */ #if (! WIN32) for (i = strlen(filename)-1; (i >= 0) && (filename[i] != '/'); --i); #else for (i = strlen(filename)-1; (i >= 0) && (filename[i] != '\\') && (filename[i] != '/'); --i); #endif i++; /* form dumpfilename */ sprintf (dumpfile, "%s/%s.DMP", dumpdir, filename+i); ReadUnigrams (fp, model); E_INFO("%8d = #unigrams created\n", model->ucount); init_sorted_list (&sorted_prob2); if (model->tcount > 0) init_sorted_list (&sorted_bo_wt2); ReadBigrams (fp, model, idfmt); model->bcount = FIRST_BG(model,model->ucount); model->n_prob2 = sorted_prob2.free; model->prob2 = vals_in_sorted_list (&sorted_prob2); free_sorted_list (&sorted_prob2); E_INFO("%8d = #bigrams created\n", model->bcount); E_INFO("%8d = #prob2 entries\n", model->n_prob2); if (model->tcount > 0) { /* Create trigram bo-wts array */ model->n_bo_wt2 = sorted_bo_wt2.free; model->bo_wt2 = vals_in_sorted_list (&sorted_bo_wt2); free_sorted_list (&sorted_bo_wt2); E_INFO("%8d = #bo_wt2 entries\n", model->n_bo_wt2); init_sorted_list (&sorted_prob3); ReadTrigrams (fp, model, idfmt); model->tcount = FIRST_TG(model,model->bcount); model->n_prob3 = sorted_prob3.free; model->prob3 = vals_in_sorted_list (&sorted_prob3); E_INFO("%8d = #trigrams created\n", model->tcount); E_INFO("%8d = #prob3 entries\n", model->n_prob3); free_sorted_list (&sorted_prob3); } /* Dump binary form of LM file */ lm3g_dump (dumpfile, model, filename, (int32)statbuf.st_mtime); if (usingPipe) { #ifdef WIN32 _pclose (fp); #else pclose (fp); #endif } else fclose (fp); fflush (stdout); fflush (stderr); return 0; } #if (__BIG_ENDIAN__) #define SWAPW(x) x = ( (((x)<<8)&0x0000ff00) | (((x)>>8)&0x00ff) ) #define SWAPL(x) x = ( (((x)<<24)&0xff000000) | (((x)<<8)&0x00ff0000) | \ (((x)>>8)&0x0000ff00) | (((x)>>24)&0x000000ff) ) #else #define SWAPW(x) #define SWAPL(x) #endif static fwrite_int32 (fp, val) FILE *fp; int32 val; { SWAPL(val); fwrite (&val, sizeof(int32), 1, fp); } static fwrite_ug (fp, ug) FILE *fp; unigram_t *ug; { unigram_t tmp_ug = *ug; SWAPL(tmp_ug.wid); SWAPL(tmp_ug.prob1.l); SWAPL(tmp_ug.bo_wt1.l); SWAPL(tmp_ug.bigrams); fwrite (&tmp_ug, sizeof(unigram_t), 1, fp); } static fwrite_bg (fp, bg) FILE *fp; bigram_t *bg; { bigram_t tmp_bg = *bg; SWAPW(tmp_bg.wid); SWAPW(tmp_bg.prob2); SWAPW(tmp_bg.bo_wt2); SWAPW(tmp_bg.trigrams); fwrite (&tmp_bg, sizeof(bigram_t), 1, fp); } static fwrite_tg (fp, tg) FILE *fp; trigram_t *tg; { trigram_t tmp_tg = *tg; SWAPW(tmp_tg.wid); SWAPW(tmp_tg.prob3); fwrite (&tmp_tg, sizeof(trigram_t), 1, fp); } static char *fmtdesc[] = { "BEGIN FILE FORMAT DESCRIPTION", "Header string length (int32) and string (including trailing 0)", "Original LM filename string-length (int32) and filename (including trailing 0)", "(int32) version number (present iff value <= 0)", "(int32) original LM file modification timestamp (iff version# present)", "(int32) string-length and string (including trailing 0) (iff version# present)", "... previous entry continued any number of times (iff version# present)", "(int32) 0 (terminating sequence of strings) (iff version# present)", "(int32) log_bg_seg_sz (present iff different from default value of LOG_BG_SEG_SZ)", "(int32) lm_t.ucount (must be > 0)", "(int32) lm_t.bcount", "(int32) lm_t.tcount", "lm_t.ucount+1 unigrams (including sentinel)", "lm_t.bcount+1 bigrams (including sentinel)", "lm_t.tcount trigrams (present iff lm_t.tcount > 0)", "(int32) lm_t.n_prob2", "(int32) lm_t.prob2[]", "(int32) lm_t.n_bo_wt2 (present iff lm_t.tcount > 0)", "(int32) lm_t.bo_wt2[] (present iff lm_t.tcount > 0)", "(int32) lm_t.n_prob3 (present iff lm_t.tcount > 0)", "(int32) lm_t.prob3[] (present iff lm_t.tcount > 0)", "(int32) (lm_t.bcount+1)/bg_seg_sz+1 (present iff lm_t.tcount > 0)", "(int32) lm_t.tseg_base[] (present iff lm_t.tcount > 0)", "(int32) Sum(all word string-lengths, including trailing 0 for each)", "All word strings (including trailing 0 for each)", "END FILE FORMAT DESCRIPTION", NULL, }; /* * Dump internal LM to file. Format described above. * Remember to swap bytes if necessary. */ static int32 lm3g_dump (file, model, lmfile, mtime) char *file; /* output file */ lm_t *model; char *lmfile; /* original Darpa LM filename */ int32 mtime; /* lmfile last mod time */ { int32 i, k; FILE *fp; E_INFO("Dumping LM to %s\n", file); if ((fp = fopen (file, "wb")) == NULL) { E_ERROR("Cannot create file %s\n", file); return 0; } k = strlen(darpa_hdr)+1; fwrite_int32 (fp, k); fwrite (darpa_hdr, sizeof(char), k, fp); k = strlen(lmfile)+1; fwrite_int32 (fp, k); fwrite (lmfile, sizeof(char), k, fp); /* Write version# and LM file modification date */ if (log_bg_seg_sz != LOG_BG_SEG_SZ) /* Hack!! */ fwrite_int32 (fp, -2); /* version # */ else fwrite_int32 (fp, -1); /* version # */ fwrite_int32 (fp, mtime); /* Write file format description into header */ for (i = 0; fmtdesc[i] != NULL; i++) { k = strlen(fmtdesc[i])+1; fwrite_int32 (fp, k); fwrite (fmtdesc[i], sizeof(char), k, fp); } fwrite_int32 (fp, 0); /* HACK!! Write only if different from previous version */ if (log_bg_seg_sz != LOG_BG_SEG_SZ) fwrite_int32 (fp, log_bg_seg_sz); fwrite_int32 (fp, model->ucount); fwrite_int32 (fp, model->bcount); fwrite_int32 (fp, model->tcount); for (i = 0; i <= model->ucount; i++) fwrite_ug (fp, &(model->unigrams[i])); for (i = 0; i <= model->bcount; i++) fwrite_bg (fp, &(model->bigrams[i])); for (i = 0; i < model->tcount; i++) fwrite_tg (fp, &(model->trigrams[i])); fwrite_int32 (fp, model->n_prob2); for (i = 0; i < model->n_prob2; i++) fwrite_int32 (fp, model->prob2[i].l); if (model->tcount > 0) { fwrite_int32 (fp, model->n_bo_wt2); for (i = 0; i < model->n_bo_wt2; i++) fwrite_int32 (fp, model->bo_wt2[i].l); fwrite_int32 (fp, model->n_prob3); for (i = 0; i < model->n_prob3; i++) fwrite_int32 (fp, model->prob3[i].l); k = (model->bcount+1)/bg_seg_sz + 1; fwrite_int32 (fp, k); for (i = 0; i < k; i++) fwrite_int32 (fp, model->tseg_base[i]); } k = 0; for (i = 0; i < model->ucount; i++) k += strlen(word_str[i])+1; fwrite_int32 (fp, k); for (i = 0; i < model->ucount; i++) fwrite (word_str[i], sizeof(char), strlen(word_str[i])+1, fp); fclose (fp); return 0; } main (int32 argc, char *argv[]) { char *lmfile; if ((argc < 3) || (argc > 4)) { E_INFO("Usage: %s <LMfile> <Dump-directory> [log2(bg-seg-size); default=%d]\n", argv[0], LOG_BG_SEG_SZ); exit(0); } lmfile = argv[1]; dumpdir = argv[2]; log_bg_seg_sz = LOG_BG_SEG_SZ; /* Default */ if ((argc > 3) && (sscanf (argv[3], "%d", &log_bg_seg_sz) != 1)) E_FATAL("Usage: %s <LMfile> <Dump-directory> [log2(bg-seg-size); default=%d]\n", argv[0], LOG_BG_SEG_SZ); if ((log_bg_seg_sz < 1) || (log_bg_seg_sz > 15)) E_FATAL("log2(bg-seg-size) argument must be in range 1..15\n"); bg_seg_sz = 1 << log_bg_seg_sz; lm_read(lmfile, ""); } <file_sep>/cmuclmtk/Makefile.am SUBDIRS = src test EXTRA_DIST = perl/Smoothing.pm \ perl/cmu_ngram_interp \ perl/simplified_chinese.wfreq \ perl/InputFilter/ICSI.pm \ perl/InputFilter/CMU.pm \ perl/InputFilter/HUB5.pm \ perl/InputFilter/SWB.pm \ perl/InputFilter/MS98.pm \ perl/InputFilter/ISL.pm \ perl/InputFilter/NIST.pm \ perl/cmu_ngram_pronounce \ perl/unihan.dic \ perl/InputFilter.pm \ perl/class_tagger.pl \ perl/NGramModel.pm \ perl/t/test.xml \ perl/t/cmu.test.lsn \ perl/t/cmu.test.fillermap \ perl/t/cmu.test.trs \ perl/t/cmu3.test.trs \ perl/t/if_cmu.t \ perl/t/ngram.t \ perl/t/test_interp.xml \ perl/t/lminterp.t \ perl/t/cmu2.test.lsn \ perl/t/cmu.test.vocab \ perl/t/lmtrain.t \ perl/t/vocab.t \ perl/t/context.ccs \ perl/t/cmu.files \ perl/NGramModel/ARPA.pm \ perl/Vocabulary.pm \ perl/cmu_build_vocab \ perl/unihan_to_sphinx.pl \ perl/cmu_ngram_train \ perl/NGramFactory.pm \ perl/LMTraining.pm \ perl/cmu_lm_train \ perl/lrSegmenter.perl \ perl/cmu_normalize_text \ perl/cmu_ngram_test \ perl/lm_changecase.pl \ perl/Makefile.PL <file_sep>/SphinxTrain/src/programs/make_quests/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 2004 <NAME> University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: cmd_ln.c * * Description: * * Author: * *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <stdio.h> #include <stdlib.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ This is an implementation of Dr. <NAME>'s automatic question \n\ generation. (Copied from Rita's comment) The current algorithm \n\ clusters CI distributions using a hybrid bottom-up top-down \n\ clustering algorithm to build linguistic questions for decision \n\ trees.\n\ (From Arthur : I need to do some tracing before understand it \n\ what's the internal of the code)"; const char examplestr[] = "Example: \n\ make_quest -moddeffn mdef -meanfn mean -varfn var -mixwfn \n\ mixwfn -npermute 8 -niter 1 -qstperstt 20 -questfn \n\ questions -type .cont."; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Model definition file of the ci models" }, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "means file for tree building using continuous HMMs" }, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "variances file for tree building using continuous HMMs" }, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "variances file contains full covariances" }, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "1.0e-08", "The minimum variance"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "PDF's for tree building using semicontinuous HMMs" }, { "-npermute", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "6", "The minimum variance"}, { "-niter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "Number of iterations"}, { "-qstperstt", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "8", "something per state"}, { "-tempfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "/tmp/TEMP.QUESTS", "(Obsolete) File to write temprorary results to " }, { "-questfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File to write questions to" }, { "-type", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "HMM type" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2005/07/09 03:02:10 arthchan2003 * 1, Remove tempfn and anything the used tempfn. It is never used in the entire SphinxTrain codebase. 2, change the example such that -tempfn is removed but -type .cont. is added. 3, Did **not** removed -tempfn because some users might just update the code but not the perl script. This keep backward compatibility (but it is definitely stupid). 4, Change the perl script as well. People who update the code and script will then learn the correct usage. 5, Check type such that if it is not .cont. or .semi., nothing stupid will happen. (Well, in general, it is a sin for us to release this program. *sigh*) * * Revision 1.6 2004/11/29 01:43:46 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/11/29 01:11:34 egouvea * Fixed license terms in some new files. * * Revision 1.4 2004/11/29 00:49:22 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.3 2004/08/10 22:32:43 arthchan2003 * Fix the dollar problem of make_quests * * Revision 1.2 2004/08/10 21:58:51 arthchan2003 * Incorporate help and example for the four final tools * * Revision 1.1 2004/06/17 19:39:49 arthchan2003 * add back all command line information into the code * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2000/11/17 16:10:41 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libs3decoder/kb.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * kb.h -- Knowledge bases, search parameters, and auxiliary structures for decoding * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 07-Jul-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Added kb_t.ci_active. * * 02-Jun-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_KB_H_ #define _S3_KB_H_ #include <libutil/libutil.h> #include "kbcore.h" #include "lextree.h" #include "vithist.h" #include "ascr.h" #include "beam.h" /* * There can be several unigram lextrees. If we're at the end of frame f, we can only * transition into the roots of lextree[(f+1) % n_lextree]; same for fillertree[]. This * alleviates the problem of excessive Viterbi pruning in lextrees. */ typedef struct { kbcore_t *kbcore; /* Core model structures */ int32 n_lextree; /* See above comment about n_lextree */ lextree_t **ugtree; lextree_t **fillertree; int32 n_lextrans; /* #Transitions to lextree (root) made so far */ vithist_t *vithist; /* Viterbi history, built during search */ float32 ***feat; /* Feature frames */ int32 nfr; /* #Frames in feat in current utterance */ int32 *ssid_active; /* For determining the active senones in any frame */ int32 *comssid_active; int32 *sen_active; int32 bestscore; /* Best HMM state score in current frame */ int32 bestwordscore; /* Best wordexit HMM state score in current frame */ ascr_t *ascr; /* Senone and composite senone scores for one frame */ beam_t *beam; /* Beamwidth parameters */ char *uttid; int32 utt_hmm_eval; int32 utt_sen_eval; int32 utt_gau_eval; int32 *hmm_hist; /* Histogram: #frames in which a given no. of HMMs are active */ int32 hmm_hist_bins; /* #Bins in above histogram */ int32 hmm_hist_binsize; /* Binsize in above histogram (#HMMs/bin) */ ptmr_t tm_sen; ptmr_t tm_srch; int32 tot_fr; float64 tot_sen_eval; /* Senones evaluated over the entire session */ float64 tot_gau_eval; /* Gaussian densities evaluated over the entire session */ float64 tot_hmm_eval; /* HMMs evaluated over the entire session */ float64 tot_wd_exit; /* Words hypothesized over the entire session */ FILE *matchsegfp; } kb_t; void kb_init (kb_t *kb); void kb_lextree_active_swap (kb_t *kb); #endif <file_sep>/archive_s3/s3.0/src/libio/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../../Makefile.defines VPATH = .:.. TARGET = libio.a OBJS = bio.o $(TARGET): $(OBJS) ar crv $@ $? ranlib $@ install: $(TARGET) cp $(TARGET) $(S3LIBDIR) clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/archive_s3/s3.0/pgm/misc/nbesterr.c /* * nbesterr.c -- N-best list oracle error rate (using DP alignment). * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 21-Mar-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <s3.h> #include <main/s3types.h> #include <main/mdef.h> #include <main/dict.h> #include "line2wid.h" #include "dp.h" /* Homophones structures */ typedef struct hom_s { s3wid_t w1, w2; /* w2 and w2 are considered equivalent */ struct hom_s *next; } hom_t; static hom_t *homlist; static mdef_t *mdef; static dict_t *dict; static s3wid_t startwid, finishwid, silwid; static s3wid_t oovbegin; #define MAX_UTT_LEN 1024 static s3wid_t hom_lookup (s3wid_t w) { hom_t *h; for (h = homlist; h && (h->w1 != w); h = h->next); return (h ? h->w2 : BAD_WID); } static void make_dagnode (dagnode_t *d, s3wid_t wid, int32 sf, int32 ef) { d->wid = wid; d->seqid = 0; d->sf = sf; d->fef = ef; d->lef = d->fef; d->reachable = 0; d->next = NULL; d->predlist = NULL; d->succlist = NULL; } static dag_t *hyp_load (char *line) { dag_t *dag; char wd[4096], *lp; int32 len, scr, n, sf, k; s3wid_t wid; dagnode_t *d, *prevd; /* Read data */ lp = line; if (sscanf (line, "T %d A %d L %d%n", &scr, &scr, &scr, &len) != 3) { if (strncmp (line, "End;", 4) != 0) E_FATAL("Bad line: %s\n", line); return (NULL); } lp += len; /* Create new DAG */ dag = ckd_calloc (1, sizeof(dag_t)); dag->node_sf = (dagnode_t **) ckd_calloc (S3_MAX_FRAMES, sizeof(dagnode_t *)); dag->nnode = 0; dag->nlink = 0; dag->nfrm = 0; /* Add the <s>.0 node at the beginning of the DAG */ d = (dagnode_t *) mymalloc (sizeof(dagnode_t)); make_dagnode (d, startwid, 0, 0); dag->node_sf[0] = d; dag->nfrm = 1; dag->nnode = 1; dag->entry.src = NULL; dag->entry.dst = d; dag->entry.next = NULL; dag->exit.src = NULL; dag->exit.dst = d; dag->exit.next = NULL; prevd = d; if (sscanf (lp, "%d %d %d %s%n", &sf, &scr, &scr, wd, &len) != 4) E_FATAL("Bad line: %s\n", lp); lp += len; wid = dict_wordid (dict, wd); if (NOT_WID(wid)) E_FATAL("Bad word(%s) in line: %s\n", wd, line); assert (wid == startwid); assert (sf == 0); n = 0; while ((k = sscanf (lp, "%d %d %d %s%n", &sf, &scr, &scr, wd, &len)) == 4) { lp += len; wid = dict_wordid (dict, wd); if (NOT_WID(wid)) E_FATAL("Bad word(%s) in line: %s\n", wd, line); d = (dagnode_t *) mymalloc (sizeof(dagnode_t)); make_dagnode (d, wid, sf, sf); d->next = dag->node_sf[sf]; dag->node_sf[sf] = d; dag->nnode++; dag_link (prevd, d); dag->nlink++; prevd = d; n++; } assert (n > 0); assert (k == 1); dag->nfrm = sf; /* Create a dummy final node and make it the exit node */ d = (dagnode_t *) mymalloc (sizeof(dagnode_t)); make_dagnode (d, silwid, dag->nfrm-1, dag->nfrm-1); assert (dag->node_sf[dag->nfrm-1] == NULL); d->next = NULL; dag->node_sf[dag->nfrm-1] = d; dag->nnode++; dag_link (prevd, d); dag->nlink++; dag->exit.dst = d; return dag; } static dag_t *nbest_load (char *file, char *uttid, dagnode_t *ref, int32 nref) { FILE *fp; dag_t *dag; char line[16384], wd[4096], *lp; char bestline[16384]; int32 len, scr, n, sf, k, best, nhyp; s3wid_t wid; dagnode_t *d, *prevd; dpnode_t retval; E_INFO("Reading DAG file: %s\n", file); if ((fp = fopen (file, "r")) == NULL) { E_ERROR("fopen(%s,r) failed\n", file); return NULL; } /* Read data */ best = (int32)0x7fffffff; while (fgets (line, sizeof(line), fp) != NULL) { if (line[0] == '#') continue; dag = hyp_load (line); if (dag) { dag_append_sentinel (dag, silwid); retval = dp (uttid, dict, oovbegin, ref, nref, dag, &nhyp, 0, 0); dag_destroy (dag); if (best > retval.e) { strcpy (bestline, line); best = retval.e; } } } fclose (fp); dag = hyp_load (bestline); return dag; } static int32 refline2wds (char *line, dagnode_t *ref, int32 *noov, char *uttid) { int32 i, n, k; s3wid_t w, wid[MAX_UTT_LEN]; n = 0; uttid[0] = '\0'; *noov = 0; if ((n = line2wid (dict, line, wid, MAX_UTT_LEN-1, 1, uttid)) < 0) E_FATAL("Error in parsing ref line: %s\n", line); wid[n++] = silwid; for (i = 0; i < n; i++) { if (dict_filler_word (dict, wid[i]) && (i < n-1)) E_FATAL("Filler word (%s) in ref: %s\n", dict_wordstr(dict, wid[i]), line); if (wid[i] >= oovbegin) { /* Perhaps one of a homophone pair */ w = hom_lookup (wid[i]); if (IS_WID(w)) wid[i] = w; if (wid[i] >= oovbegin) (*noov)++; } make_dagnode (ref+i, wid[i], i, i); } return n; } static void process_reffile (char *reffile) { FILE *rfp; char line[16384], uttid[4096], file[4096], lc_uttid[4096]; int32 i, k; dagnode_t ref[MAX_UTT_LEN]; int32 nref, noov, nhyp; int32 tot_err, tot_ref, tot_corr, tot_oov, tot_hyp; dag_t *dag; dpnode_t retval; timing_t *tm; char *latdir; if ((rfp = fopen(reffile, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", reffile); latdir = (char *) cmd_ln_access ("-latdir"); tot_err = 0; tot_ref = 0; tot_hyp = 0; tot_corr = 0; tot_oov = 0; tm = timing_new ("Utt"); while (fgets(line, sizeof(line), rfp) != NULL) { timing_reset (tm); timing_start (tm); if ((nref = refline2wds (line, ref, &noov, uttid)) < 0) E_FATAL("Bad line in file %s: %s\n", reffile, line); /* Read lattice or hypfile, whichever is specified */ sprintf (file, "%s/%s.nbest", latdir, uttid); dag = nbest_load (file, uttid, ref, nref); if (! dag) { /* Try lower casing uttid */ strcpy (lc_uttid, uttid); lcase (lc_uttid); sprintf (file, "%s/%s.nbest", latdir, lc_uttid); dag = nbest_load (file, uttid, ref, nref); } if (dag) { /* Append sentinel silwid node to end of DAG */ dag_append_sentinel (dag, silwid); /* Find best path (returns #errors/#correct and updates *nhyp) */ retval = dp (uttid, dict, oovbegin, ref, nref, dag, &nhyp, 0, 1); dag_destroy (dag); } else { retval.c = 0; retval.e = nref-1; nhyp = 0; } timing_stop (tm); tot_ref += nref-1; tot_hyp += nhyp; tot_err += retval.e; tot_corr += retval.c; tot_oov += noov; printf("(%s) << %d ref; %d %.1f%% oov; %d hyp; %d %.1f%% corr; %d %.1f%% err; %.1fs CPU >>\n", uttid, nref-1, noov, (nref > 1) ? (noov * 100.0) / (nref-1) : 0.0, nhyp, retval.c, (nref > 1) ? (retval.c * 100.0) / (nref-1) : 0.0, retval.e, (nref > 1) ? (retval.e * 100.0) / (nref-1) : 0.0, tm->t_cpu); printf("== %7d ref; %5d %5.1f%% oov; %7d hyp; %7d %5.1f%% corr; %6d %5.1f%% err; %5.1fs CPU; %s\n", tot_ref, tot_oov, (tot_ref > 0) ? (tot_oov * 100.0) / tot_ref : 0.0, tot_hyp, tot_corr, (tot_ref > 0) ? (tot_corr * 100.0) / tot_ref : 0.0, tot_err, (tot_ref > 0) ? (tot_err * 100.0) / tot_ref : 0.0, tm->t_tot_cpu, uttid); fflush (stderr); fflush (stdout); } fclose (rfp); printf("SUMMARY: %d ref; %d %.3f%% oov; %d hyp; %d %.3f%% corr; %d %.3f%% err; %.1fs CPU\n", tot_ref, tot_oov, (tot_ref > 0) ? (tot_oov * 100.0) / tot_ref : 0.0, tot_hyp, tot_corr, (tot_ref > 0) ? (tot_corr * 100.0) / tot_ref : 0.0, tot_err, (tot_ref > 0) ? (tot_err * 100.0) / tot_ref : 0.0, tm->t_tot_cpu); } static void homfile_load (char *file) { FILE *fp; char line[16380], w1[4096], w2[4096]; int32 k, n; s3wid_t wid1, wid2; s3cipid_t ci[1]; hom_t *h; E_INFO("Reading homophones file %s\n", file); if ((fp = fopen(file, "r")) == NULL) E_FATAL("fopen(%s,r) failed\n", file); ci[0] = (s3cipid_t) 0; /* Dummy */ n = 0; while (fgets (line, sizeof(line), fp) != NULL) { if ((k = sscanf (line, "%s %s", w1, w2)) == 2) { wid1 = dict_wordid (dict, w1); if (NOT_WID(wid1)) { E_INFO("Adding %s to dictionary\n", w1); wid1 = dict_add_word (dict, w1, ci, 1); if (NOT_WID(wid1)) E_FATAL("dict_add_word(%s) failed\n", w1); } wid2 = dict_wordid (dict, w2); if ((NOT_WID(wid2)) || (wid2 >= oovbegin)) E_FATAL("%s not in dictionary\n", w2); h = (hom_t *) mymalloc (sizeof(hom_t)); h->w1 = wid1; h->w2 = wid2; h->next = homlist; homlist = h; n++; } else E_FATAL("Bad homophones line: %s\n", line); } E_INFO("%d homophone pairs read\n", n); fclose (fp); } static arg_t arglist[] = { { "-mdef", CMD_LN_STRING, NULL, "Model definition input file" }, { "-dict", CMD_LN_STRING, NULL, "Pronunciation dictionary input file (pronunciations not relevant)" }, { "-fdict", CMD_LN_STRING, NULL, "Filler word pronunciation dictionary input file (pronunciations not relevant)" }, { "-ref", CMD_LN_STRING, NULL, "Input reference (correct) file" }, { "-hom", CMD_LN_STRING, NULL, "Homophones input file" }, { "-sil", CMD_LN_STRING, "<sil>", "Silence word" }, { "-latdir", CMD_LN_STRING, ".", "Input lattice directory (-latdir/-hyp mutually exclusive)" }, { NULL, CMD_LN_INT32, NULL, NULL } }; main (int32 argc, char *argv[]) { char *reffile, *mdeffile, *dictfile, *fdictfile, *homfile; if (argc == 1) { cmd_ln_print_help (stderr, arglist); exit(0); } cmd_ln_parse (arglist, argc, argv); if ((mdeffile = (char *) cmd_ln_access ("-mdef")) == NULL) E_FATAL("-mdef argument missing\n"); if ((dictfile = (char *) cmd_ln_access ("-dict")) == NULL) E_FATAL("-dict argument missing\n"); if ((fdictfile = (char *) cmd_ln_access ("-fdict")) == NULL) E_FATAL("-fdict argument missing\n"); if ((reffile = (char *) cmd_ln_access ("-ref")) == NULL) E_FATAL("-ref argument missing\n"); unlimit(); mdef = mdef_init (mdeffile); if (mdef->n_ciphone <= 0) E_FATAL("0 CIphones in %s\n", mdeffile); dict = dict_init (mdef, dictfile, fdictfile); oovbegin = dict->n_word; startwid = dict_wordid (dict, "<s>"); finishwid = dict_wordid (dict, "</s>"); silwid = dict_wordid (dict, (char *) cmd_ln_access("-sil")); assert (dict_filler_word (dict, silwid)); homlist = NULL; if ((homfile = (char *) cmd_ln_access ("-hom")) != NULL) homfile_load (homfile); process_reffile (reffile); #if (0 && (! WIN32)) fflush (stdout); fflush (stderr); system ("ps aguxwww | grep dpalign"); #endif exit(0); } <file_sep>/misc_scripts/mandarin_oov.py #!/usr/bin/env python import sys import codecs def read_arpa(arpa): fh = codecs.open(arpa, "r", "utf8") indata = False in1gram = False words = set() for spam in fh: if spam == u"\\data\\\n": indata = True continue if indata and spam == u"\\1-grams:\n": in1gram = True continue if in1gram and spam == u"\\2-grams:\n": break if spam == u"\n": continue if in1gram: prob, word, bo = spam.split() words.add(word) return words def find_best_oov(vocab, words): """ Find a minimum OOV segmentation of words, returning the number of OOVs and word count of that segmentation. """ # Expand words into a graph based on vocab. Each section of # unparsed characters becomes an arc with cost N where N is the # length of the section. In-vocabulary words have cost 0. Note # that this means we will not get a unique segmentation of the # in-vocabulary portions. chars = u"".join(words) # Create one state for each position in the word plus a start state states = [] for i in range(0, len(chars)): states.append([]) # For each position in the sentence, create arcs for every word # starting at that position, and sort them longest-first for i in range(0, len(chars)): for j in range(i+1, len(chars)+1): # Create an arc for this word if chars[i:j] in vocab: states[i].append((0, chars[i:j])) else: # FIXME: Could probably make these implicit? states[i].append((j-i, chars[i:j])) states[i].sort(reverse=True) # Find the shortest path through that graph state_costs = [999999] * (len(states) + 1) state_prevs = [0] * (len(states) + 1) state_costs[0] = 0 Q = range(0, len(states)) while Q: # Find lowest-cost state pcost = 999999 for i, stateid in enumerate(Q): if state_costs[stateid] < pcost: pcost = state_costs[stateid] break del Q[i] # Expand its outgoing arcs, updating costs, prevs for cost, word in states[stateid]: destid = stateid + len(word) dcost = pcost + cost if dcost < state_costs[destid]: state_costs[destid] = dcost state_prevs[destid] = stateid # Backtrace to get segmentation and OOVs (since the segmentation # counts an OOV segment as a single word, we do too) pos = len(state_prevs)-1 seg = [] oov = [] while pos > 0: bp = state_prevs[pos] word = chars[bp:pos] cost = state_costs[pos] - state_costs[bp] seg.insert(0, word) if cost > 0: oov.append(word) pos = bp return seg, oov if __name__ == '__main__': try: arpa, txt = sys.argv[1:] except: sys.stderr.write("Usage: %s ARPA TXT\n" % sys.argv[0]) sys.exit(2) vocab = read_arpa(arpa) oovset = {} noov = 0 nwords = 0 for spam in codecs.open(txt, "r", "utf8"): words = spam.split() # Remove start and end sentence markers (and possibly uttid) if words[0] == "<s>": del words[0] for i in range(len(words)-1, -1, -1): if words[i] == "</s>": del words[i:] break if words[-1].startswith('('): del words[-1:] seg, oov = find_best_oov(vocab, words) for w in oov: oovset[w] = oovset.get(w, 0) + 1 noov += len(oov) nwords += len(seg) print u" ".join(seg).encode('utf8') print "%d words, %d oovs, OOV rate %.2f%%" % (nwords, noov, float(noov)/nwords*100) if noov > 0: print "OOVs and counts:" for w, c in sorted(oovset.items(), key=lambda x: x[1], reverse=True): print w.encode('utf8'), c <file_sep>/SphinxTrain/include/s3/s2_param.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * file: s2_param.h * * traceability: * * description: * * author: * *********************************************************************/ #ifndef S2_PARAM_H #define S2_PARAM_H #define S2_N_CODEWORD 256 /* number of codewords */ #define S2_N_STATE 6 /* 5 state w/ dummy end state */ #define S2_TRANSITION 6 /* index of transition id in tying DAG */ #define S2_CEP_VECLEN 13 /* dimension of the cepstrum vector */ #define S2_CEP_FEATURE 0 #define S2_DCEP_FEATURE 1 #define S2_POW_FEATURE 2 #define S2_2DCEP_FEATURE 3 #define S2_CEPF_VECLEN 12 /* dimension of the cepstrum feature */ #define S2_D1CEPF_VECLEN 12 /* dimension of the +/- 2 frm diff cep feature */ #define S2_D2CEPF_VECLEN 12 /* dimension of the +/- 2 frm diff cep feature */ #define S2_DCEPF_VECLEN 24 /* concatenated +/- 2 and +/- 4 frame */ #define S2_POWF_VECLEN 3 /* dimension of the pow feature */ #define S2_2DCEPF_VECLEN 12 /* dimension of the 2nd ord. diff cep feature */ #define S2_N_FEATURE 4 /* number of independent feature streams */ #define S2_SHORT_DIFFW 2 /* +/- # frames for short duration dcep */ #define S2_LONG_DIFFW 4 /* +/- # frames for short duration dcep */ #define S2_2ND_ORD_DIFFW 3 /* effective +/- # frames for 2nd ord dcep */ #define MIN_FLOAT32 1e-36 #define S2_ALPHA_BETA_EPSILON 0.01 #endif /* S2_PARAM_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.1 1995/10/12 17:47:11 eht * Initial revision * * */ <file_sep>/archive_s3/s3.2/src/libutil/bitvec.c /* * bitvec.c -- Bit vector type. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 05-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon * Started. */ #include "bitvec.h" int32 bitvec_count_set (bitvec_t vec, int32 len) { int32 n, i; for (i = 0, n = 0; i < len; i++) if (bitvec_is_set (vec, i)) n++; return n; } <file_sep>/archive_s3/s3.0/pgm/misc/newrc.c /* * rc.c -- Right context transformations * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 08-Apr-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * Input lines of the form: * 354 .PERIOD => (TD) p ih r iy ax dd () * 9 IN => (S) [[ AX => IX ]] n (F) * 6 HELP PAY => (AX) hh eh l [[ => PD ]] p ey (F) * Output last phone transformations only. */ #include <libutil/libutil.h> static char *phonestr[] = { "AA", "AE", "AH", "AO", "AW", "AX", "AXR", "AY", "B", "BD", "CH", "D", "DD", "DH", "DX", "EH", "ER", "EY", "F", "G", "GD", "HH", "IH", "IX", "IY", "JH", "K", "KD", "L", "M", "N", "NG", "OW", "OY", "P", "PD", "R", "S", "SH", "T", "TD", "TH", "TS", "UH", "UW", "V", "W", "Y", "Z", "ZH", "--", /* Dummy empty-phone */ NULL }; static int32 phone_str2id (char *str) { int32 i; ucase (str); for (i = 0; phonestr[i] && (strcmp (phonestr[i], str) != 0); i++); if (! phonestr[i]) E_FATAL("Unknown phone: %s\n", str); return i; } static int32 tmpp1; static int32 *tmpcount; static int32 cmp_count (int32 *a, int32 *b) { if (tmpcount[*b] > tmpcount[*a]) return 1; else if (tmpcount[*b] < tmpcount[*a]) return -1; else if (*a == tmpp1) return -1; else if (*b == tmpp1) return 1; else return 0; } #define MAX_WORDS 4092 main (int32 argc, char *argv[]) { char line[16384], **wptr; int32 i, j, k, prevk, n, np, ****mapcount, *mapid; int32 p1, lc, rc, p2; if (argc > 1) { E_INFO("Usage: %s < <result-of-pronerralign>\n", argv[0]); exit(0); } wptr = (char **) ckd_calloc (MAX_WORDS, sizeof(char *)); for (np = 0; phonestr[np]; np++); E_INFO("%d phones\n", np-1); E_INFO("Allocating %d x %d x %d x %d mapcount array\n", np, np, np, np); mapcount = (int32 ****) ckd_calloc_3d (np, np, np, sizeof(int32 *)); mapid = (int32 *) ckd_calloc (np, sizeof(int32)); tmpcount = (int32 *) ckd_calloc (np, sizeof(int32)); for (i = 0; i < np; i++) { for (j = 0; j < np; j++) { for (k = 0; k < np; k++) { mapcount[i][j][k] = (int32 *) ckd_calloc (np, sizeof(int32)); } } } prevk = 0; while (fgets (line, sizeof(line), stdin) != NULL) { if ((n = str2words (line, wptr, MAX_WORDS)) < 0) E_FATAL("str2words(%s) failed; increase %d(?)\n", line, MAX_WORDS); /* Read first (count) field */ if (n == 0) continue; if (sscanf (wptr[0], "%d", &k) != 1) E_FATAL("First field not a count: %s\n", wptr[0]); if (k != prevk) { printf (" %d", k); fflush (stdout); prevk = k; } if (k <= 0) break; /* Find => separator after word list */ for (i = 0; (i < n) && (strcmp (wptr[i], "=>") != 0); i++); i++; /* Hopefully at (lc) */ /* Must have at least: (lc) p1 p2 (rc) */ if (n-i <= 3) continue; assert (i > 2); assert (wptr[i][0] == '('); /* (lc) */ j = strlen(wptr[n-1]) - 1; /* (rc); strip () from it */ assert ((wptr[n-1][0] == '(') && (wptr[n-1][j] == ')')); if (strcmp (wptr[n-1], "()") == 0) strcpy (wptr[n-1], "--"); else { wptr[n-1][j] = '\0'; (wptr[n-1])++; } if ((strcmp (wptr[n-2], "]]") != 0) && (strcmp (wptr[n-3], "]]") != 0)) { /* No error */ #if 0 printf ("%6d %-5s %-5s %-5s %s\n", k, wptr[n-3], wptr[n-2], wptr[n-1], wptr[1]); #endif lc = phone_str2id (wptr[n-3]); p1 = phone_str2id (wptr[n-2]); rc = phone_str2id (wptr[n-1]); p2 = p1; mapcount[p1][lc][rc][p2] += k; } else if (strcmp (wptr[n-2], "]]") == 0) { /* * Last phone got transformed. Look for: * (lc) p [[ => ee ]] (rc), * (lc) p [[ ee => ]] (rc), or * (lc) p [[ pp => ee ]] (rc) */ if (n-i <= 6) continue; /* Not enough fields */ if ((strcmp (wptr[n-4], "=>") == 0) && (strcmp (wptr[n-5], "[[") == 0) && (strcmp (wptr[n-6], "]]") != 0)) { /* (lc) p [[ => ee ]] (rc) */ #if 0 printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-6], wptr[n-3], wptr[n-1], "--", wptr[1]); #endif lc = phone_str2id (wptr[n-6]); p1 = phone_str2id (wptr[n-3]); rc = phone_str2id (wptr[n-1]); p2 = np-1; mapcount[p1][lc][rc][p2] += k; } else if ((strcmp (wptr[n-3], "=>") == 0) && (strcmp (wptr[n-5], "[[") == 0) && (strcmp (wptr[n-6], "]]") != 0)) { #if 0 printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-6], "--", wptr[n-1], wptr[n-4], wptr[1]); #endif lc = phone_str2id (wptr[n-6]); p1 = np-1; rc = phone_str2id (wptr[n-1]); p2 = phone_str2id (wptr[n-4]); mapcount[p1][lc][rc][p2] += k; } else if ((strcmp (wptr[n-4], "=>") == 0) && (strcmp (wptr[n-6], "[[") == 0) && (strcmp (wptr[n-7], "]]") != 0) && (n-i > 7)) { #if 0 printf ("%6d %-5s %-5s %-5s => %-5s %s\n", k, wptr[n-7], wptr[n-3], wptr[n-1], wptr[n-5], wptr[1]); #endif lc = phone_str2id (wptr[n-7]); p1 = phone_str2id (wptr[n-3]); rc = phone_str2id (wptr[n-1]); p2 = phone_str2id (wptr[n-5]); mapcount[p1][lc][rc][p2] += k; } } } printf ("\n"); for (p1 = 0; p1 < np; p1++) { for (lc = 0; lc < np; lc++) { for (rc = 0; rc < np; rc++) { k = 0; for (p2 = 0; p2 < np; p2++) k += mapcount[p1][lc][rc][p2]; if (k > 0) { printf ("%-4s %-4s %-4s %5d", phonestr[p1], phonestr[lc], phonestr[rc], k); for (p2 = 0; p2 < np; p2++) { tmpcount[p2] = mapcount[p1][lc][rc][p2]; mapid[p2] = p2; } tmpp1 = p1; qsort (mapid, np, sizeof(int32), cmp_count); for (p2 = 0; p2 < np; p2++) { if (mapcount[p1][lc][rc][mapid[p2]]) printf (" %s %d", phonestr[mapid[p2]], mapcount[p1][lc][rc][mapid[p2]]); } printf ("\n"); } } } } } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/GraphLoader.java package edu.cmu.sphinx.tools.confdesigner; import edu.cmu.sphinx.tools.executor.ExecutorListener; import edu.cmu.sphinx.util.props.*; import java.util.*; /** * DOCUMENT ME! * * @author <NAME> */ public class GraphLoader { private SceneController confController; private ConfigScene scene; public GraphLoader(SceneController sceneController) { confController = sceneController; this.scene = confController.getScene(); } public boolean mergeIntoScene(ConfigurationManager cm) { confController.getCm().addSubConfiguration(cm); loadScene(confController.getCm(), null, cm.getComponentNames()); return true; } public boolean loadScene(ConfigurationManager cm, List<ExecutorListener> executorListeners, Collection<String> addCompNames) { Map<String, ConfNode> nodes = new HashMap<String, ConfNode>(); for (String compName : addCompNames) { assert !nodes.keySet().contains(compName) : "scene already contains node named '" + compName + "'"; nodes.put(compName, confController.addNode(cm.getPropertySheet(compName), compName)); } scene.validate(); // connect all components for (String compName : addCompNames) { connect2Graph(cm, compName, nodes); } scene.validate(); return true; } private void connect2Graph(ConfigurationManager cm, String compName, Map<String, ConfNode> nodes) { PropertySheet ps = cm.getPropertySheet(compName); for (String propName : ps.getRegisteredProperties()) { if (ps.getType(propName) == PropertySheet.PropertyType.COMP) { String propValue = (String) ps.getRaw(propName); if (propValue == null) continue; propValue = ConfigurationManagerUtils.getPropertyManager(ps).getStrippedComponentName(propValue); ConfNode sourceNode = nodes.get(propValue); ConfNode targetNode = nodes.get(compName); assert sourceNode != null && targetNode != null; ConfPin sourcePort = sourceNode.getThisPin(); ConfPin targetPort = targetNode.getPin(propName); scene.createEdge(new ConfEdge(sourcePort, targetPort)); } else if (ps.getType(propName) == PropertySheet.PropertyType.COMPLIST) { S4PropWrapper s4PropWrapper = null; try { s4PropWrapper = ps.getProperty(propName, S4ComponentList.class); } catch (PropertyException e) { e.printStackTrace(); } Class<? extends Configurable> listType = ((S4ComponentList) s4PropWrapper.getAnnotation()).type(); List<String> listComps = (List<String>) ps.getRaw(propName); if (listComps == null) continue; for (int i = 0; i < listComps.size(); i++) { String componentName = listComps.get(i); componentName = ConfigurationManagerUtils.getPropertyManager(ps).getStrippedComponentName(componentName); ConfNode targetNode = nodes.get(compName); ConfNode sourceNode = nodes.get(componentName); if(targetNode == null || sourceNode == null) continue; assert sourceNode != null; assert targetNode != null; ConfPin sourcePort = sourceNode.getPin(ConfNode.PARENT_PIN); if (getUnusedListPins(targetNode, propName, scene).size() <= 1) { targetNode.addInputPin(scene, propName, i + 1, listType); } List<ConfPin> freeListPins = getUnusedListPins(targetNode, propName, scene); scene.validate(); scene.createEdge(new ConfEdge(sourcePort, freeListPins.get(0))); } } scene.validate(); } } public static List<ConfPin> getUnusedListPins(ConfNode targetNode, String propListName, ConfigScene scene) { List<ConfPin> freeListPins = new ArrayList<ConfPin>(); for (ConfPin listPin : targetNode.getListPins(propListName)) { if (scene.findPinEdges(listPin, false, true).size() == 0) freeListPins.add(listPin); } return freeListPins; } } <file_sep>/archive_s3/s3.0/pgm/misc/mfc.c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #if (! WIN32) #include <sys/file.h> #include <sys/errno.h> #include <sys/param.h> #else #include <fcntl.h> #endif #include <libutil/libutil.h> #include <libio/libio.h> main (int argc, char *argv[]) { struct stat statbuf; char *file; FILE *fp; int32 byterev; int32 n, n_float32, fr; float32 cep[13]; if (argc < 2) { printf ("Usage: %s <mfcfile> [<numbered>]\n", argv[0]); exit(-1); } file = argv[1]; if (stat (file, &statbuf) != 0) { E_ERROR("stat(%s) failed\n", file); return -1; } if ((fp = fopen(file, "rb")) == NULL) { E_ERROR("fopen(%s,rb) failed\n", file); return -1; } /* Read #floats in header */ if (fread (&n_float32, sizeof(int32), 1, fp) != 1) { fclose (fp); return -1; } /* Check of n_float32 matches file size */ byterev = FALSE; if ((n_float32*sizeof(float32) + 4) != statbuf.st_size) { n = n_float32; SWAP_INT32(&n); if ((n*sizeof(float32) + 4) != statbuf.st_size) { E_ERROR("Header size field: %d(%08x); filesize: %d(%08x)\n", n_float32, n_float32, statbuf.st_size, statbuf.st_size); fclose (fp); return -1; } n_float32 = n; byterev = TRUE; } if (n_float32 <= 0) { E_ERROR("Header size field: %d\n", n_float32); fclose (fp); return -1; } if (byterev && (argc < 3)) E_INFO("Byte-reversing %s\n", file); fr = 0; while (fread (cep, sizeof(float32), 13, fp) == 13) { if (byterev) SWAP_FLOAT32(cep); if (argc > 2) printf ("%4d ", fr); printf ("%8.3f\n", cep[0]); fr++; } } <file_sep>/archive_s3/s3.0/src/libmain/wid.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * wid.c -- Mapping word-IDs between LM and dictionary. * * * HISTORY * * 01-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include "dict.h" #include "lm.h" s3lmwid_t *wid_dict_lm_map (dict_t *dict, lm_t *lm) { int32 u, n; s3wid_t w; s3lmwid_t *map; assert (dict_size(dict) > 0); map = (s3lmwid_t *) ckd_calloc (dict_size(dict), sizeof(s3lmwid_t)); for (n = 0; n < dict_size(dict); n++) map[n] = BAD_LMWID; n = 0; for (u = 0; u < lm->n_ug; u++) { w = dict_wordid (dict, lm->wordstr[u]); lm->ug[u].dictwid = w; if (NOT_WID(w)) { n++; } else { if (dict_filler_word (dict, w)) E_ERROR("Filler dictionary word '%s' found in LM\n", lm->wordstr[u]); if (w != dict_basewid (dict, w)) { E_ERROR("LM word '%s' is an alternative pronunciation in dictionary\n", lm->wordstr[u]); w = dict_basewid (dict, w); lm->ug[u].dictwid = w; } for (; IS_WID(w); w = dict_nextalt(dict, w)) map[w] = (s3lmwid_t) u; } } if (n > 0) E_INFO("%d LM words not in dictionary; ignored\n", n); return map; } <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/ConfDesigner.java /* * Created by JFormDesigner on Fri May 04 20:41:31 CEST 2007 */ package edu.cmu.sphinx.tools.confdesigner; import edu.cmu.sphinx.decoder.Decoder; import edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer; import edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager; import edu.cmu.sphinx.frontend.FrontEnd; import edu.cmu.sphinx.frontend.transform.DiscreteCosineTransform; import edu.cmu.sphinx.frontend.util.WavWriter; import edu.cmu.sphinx.tools.confdesigner.actions.*; import edu.cmu.sphinx.tools.confdesigner.conftree.ConfigSelector; import edu.cmu.sphinx.tools.confdesigner.util.SceneFinder; import edu.cmu.sphinx.tools.executor.ExecutableExecutor; import edu.cmu.sphinx.tools.executor.ExecutorListener; import edu.cmu.sphinx.util.props.Configurable; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.*; import java.util.List; import java.util.prefs.Preferences; /** @author <NAME> */ public class ConfDesigner extends JFrame implements ExecutorListener { public static final String CONF_DESIGNER = "ConfDesigner"; private JDialog sateliteDialog; JTabbedPane tabPane; private List<File> recentFiles = new ArrayList<File>(); private ActionListener recentFileListener; private static Preferences prefs; private SessionManager sesMan; private Map<PropertySheet, JMenuItem> curSceneExecutors = new HashMap<PropertySheet, JMenuItem>(); Map<SceneContext, JComponent> projectsTabs = new HashMap<SceneContext, JComponent>(); private static Clipboard clipboard; public ConfDesigner() { initComponents(); sesMan = new SessionManager(this); // cmLocation = new File("lala.sxl"); // cmLocation = new File("../../sphinx4/src/demo/sphinx/hellongram/hellongram.config.xml"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { super.windowClosing(e); exitItemActionPerformed(); } }); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { getPrefs().putInt("mainwin.width", getWidth()); getPrefs().putInt("mainwin.height", getHeight()); getPrefs().putInt("mainwin.xpos", (int) getLocation().getX()); getPrefs().putInt("mainwin.ypos", (int) getLocation().getY()); } }); recentFileListener = new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < recentMenu.getItemCount(); i++) { if (recentMenu.getItem(i).equals(e.getSource())) { File recentFile = recentFiles.get(i); if (recentFile.getName().endsWith(SessionManager.FORMAT_SUFFIX)) sesMan.loadScene(recentFile); else if (recentFile.getName().endsWith(SessionManager.PROJECT_FORMAT_SUFFIX)) sesMan.loadProject(recentFile); else assert false : "invaled recent file " + recentFile.getAbsolutePath(); } } } }; setFocusable(true); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()) sceneFinder.requestFocus(); // if (e.getKeyCode() == KeyEvent.VK_S && e.isControlDown()) // saveImage2File(null); } }); // addDummyNodes(scene); tabPane = new JTabbedPane(); tabPane.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON2) closeTabItemActionPerformed(); } }); tabPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { Component selectedTab = tabPane.getSelectedComponent(); SceneContext newActiveScene = null; for (SceneContext sc : projectsTabs.keySet()) { if (projectsTabs.get(sc).equals(selectedTab)) newActiveScene = sc; } if (newActiveScene != null) { sesMan.setActiveScene(newActiveScene); ConfDesigner.this.setTitle(CONF_DESIGNER + " - " + newActiveScene.getLocation().getName()); } } }); sesMan.addSesManListener(new SesManListener() { public void newActiveScene(SceneContext sc) { // if (sesMan.numConfigs() > 1) // tabPane.getModel().setSelectedIndex(tabPane.indexOfComponent(projectsTabs.get(sc))); SceneController sceneController = sc.getSceneController(); ConfigScene scene = sceneController.getScene(); sceneController.getScene().getView().requestFocusInWindow(); birdViewPanel.removeAll(); birdViewPanel.add(scene.createSatelliteView()); birdViewPanel.validate(); scene.setSnap2Grid(snap2GridItem.isSelected()); configurableTree.setController(sceneController); for (PropertySheet ps : curSceneExecutors.keySet()) removedExecutor(ps); for (PropertySheet ps : sc.getCurSceneExecutors()) addedExecutor(ps); propSheetPanel.setConfigurationManager(sceneController.getCm()); // if there is a single selected object reselect it in order to show it wihtin the props-panel Set<?> selectedObjects = sc.getScene().getSelectedObjects(); if (selectedObjects.size() == 1) { Object selObject = selectedObjects.iterator().next(); if (selObject instanceof ConfNode) propSheetPanel.rebuildPanel(((ConfNode) selObject).getPropSheet()); } } public void addedScene(SceneContext sc) { JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(sc.getSceneController().getScene().getView()); projectsTabs.put(sc, scrollPane); if (sesMan.numConfigs() == 1) { if (!(scenePane.getComponents().length > 0 && scenePane.getComponent(0) instanceof JScrollPane)) { scenePane.removeAll(); scenePane.add(scrollPane); ConfDesigner.this.setTitle(CONF_DESIGNER + " - " + sc.getLocation().getName()); } } else { if (scenePane.getComponents().length == 0) { scenePane.add(tabPane); } else if (scenePane.getComponent(0) instanceof JScrollPane) { JScrollPane scrollPaneOld = (JScrollPane) scenePane.getComponent(0); scenePane.removeAll(); scenePane.add(tabPane); tabPane.addTab(sesMan.getSceneContexts().get(0).getLocation().getName(), scrollPaneOld); } tabPane.addTab(sc.getLocation().getName(), scrollPane); tabPane.validate(); tabPane.getModel().setSelectedIndex(tabPane.indexOfComponent(scrollPane)); } sc.getSceneController().addExecutorListener(ConfDesigner.this); scenePane.validate(); sesMan.setActiveScene(sc); } public void removedScene(SceneContext sc) { sc.getSceneController().removeExecutorListener(ConfDesigner.this); if (sesMan.numConfigs() > 0) { tabPane.remove(projectsTabs.get(sc)); } else { scenePane.removeAll(); tabPane.removeAll(); SceneContext initalSceneContext = new SceneContext(null); sesMan.registerSceneContext(initalSceneContext); sesMan.setActiveScene(initalSceneContext); } tabPane.validate(); scenePane.validate(); } }); expSceneImgItem.setAction(new ExportImageAction(sesMan, false, this)); fitViewItem.setAction(new FitViewAction(sesMan)); helpItem.setAction(new UrlAction("Help", "http://en.wikipedia.org/wiki/ConfDesigner", this)); pasteItem.setAction(new PasteSubGraphAction(sesMan, getClipBoard())); copyItem.setAction(new CopySubGraphAction(sesMan, getClipBoard())); DeleteSubGraphAction deleteAction = new DeleteSubGraphAction(sesMan); deleteItem.setAction(deleteAction); cutItem.setAction(new CutSubGraphAction(sesMan, getClipBoard(), deleteAction)); snap2GridItem.setSelected(ConfDesigner.getPrefs().getBoolean("snap2Grid", true)); snap2GridItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sesMan.getActiveScene().getScene().setSnap2Grid(snap2GridItem.isSelected()); ConfDesigner.getPrefs().putBoolean("snap2Grid", snap2GridItem.isSelected()); } }); // intit the view SceneContext initalSceneContext = new SceneContext(null); sesMan.registerSceneContext(initalSceneContext); sesMan.setActiveScene(initalSceneContext); updateRecentFiles(null); } public void addConfigurables(Collection<Class<? extends Configurable>> configClasses) { configurableTree.addConfigurables(configClasses); } private void addDummyNodes(ConfigScene scene) throws IOException, PropertyException { // ConfigurationManager cm = new ConfigurationManager(Utils.getURL(Azubi.DEFAULT_CONFIG_XML)); sesMan.getActiveScene().getSceneController().addNode(ThreadedAcousticScorer.class, null); sesMan.getActiveScene().getSceneController().addNode(FrontEnd.class, null); sesMan.getActiveScene().getSceneController().addNode(SimpleBreadthFirstSearchManager.class, null); sesMan.getActiveScene().getSceneController().addNode(Decoder.class, null); sesMan.getActiveScene().getSceneController().addNode(WavWriter.class, null); sesMan.getActiveScene().getSceneController().addNode(DiscreteCosineTransform.class, null); scene.validate(); } public SessionManager getSesMan() { return sesMan; } public void addedExecutor(final PropertySheet executablePS) { JMenuItem menuItem = new JMenuItem(); menuItem.addActionListener(new ExecutableExecutor(executablePS)); menuItem.setText("Start '" + executablePS.getInstanceName() + "'"); runMenu.setEnabled(true); runMenu.add(menuItem); curSceneExecutors.put(executablePS, menuItem); } public void removedExecutor(PropertySheet ps) { JMenuItem item = curSceneExecutors.remove(ps); if (item == null) return; runMenu.remove(item); runMenu.validate(); if (curSceneExecutors.isEmpty()) { runMenu.setEnabled(false); runMenu.setToolTipText("Can not find any exectutables within the current scene"); } else { runMenu.setEnabled(true); runMenu.setToolTipText(null); } } private void classFilterFieldActionPerformed() { // getSomeInput String filterText = classFilterField.getText(); configurableTree.setFilter(filterText); } private void filterResetButtonActionPerformed() { SwingUtilities.invokeLater(new Runnable() { public void run() { configurableTree.setFilter(null); classFilterField.setText(""); classFilterField.requestFocus(); } }); } private void newItemActionPerformed() { SceneContext newSC = new SceneContext(null); sesMan.registerSceneContext(newSC); sesMan.setActiveScene(newSC); // sceneController.setCm(new ConfigurationManager()); // propSheetPanel.setConfigurationManager(sceneController.getCm()); } private void showBirdViewItemActionPerformed() { if (sateliteDialog == null) { sateliteDialog = new JDialog(this); sateliteDialog.setBounds(50, 500, 200, 150); JPanel panel = new JPanel(new BorderLayout()); panel.add(sesMan.getActiveScene().getScene().createSatelliteView()); sateliteDialog.getContentPane().add(panel); } // showBirdViewItem.setSelected(!showBirdViewItem.isSelected()); sateliteDialog.setVisible(showBirdViewItem.isSelected()); } private void layoutGraphItemActionPerformed() { sesMan.getActiveScene().getScene().layoutScene(); System.err.println("scene layout updated"); } private void aboutItemActionPerformed() { JOptionPane.showMessageDialog(this, "ConfDesigner 1.0 beta 2+", "About", JOptionPane.INFORMATION_MESSAGE); } private void sceneFinderActionPerformed() { boolean searchSucessful = new SceneFinder(this, sesMan.getActiveScene().getSceneController()).process(sceneFinder.getText()); if (searchSucessful) sceneFinder.setText(""); } public PropertyEditorPanel getPropSheetPanel() { return propSheetPanel; } void saveItemActionPerformed() { SceneContext tab = sesMan.getActiveScene(); sesMan.saveScene(tab); } void saveAsItemActionPerformed() { SceneContext activeScene = sesMan.getActiveScene(); sesMan.saveSceneAs(activeScene); } private void loadItemActionPerformed() { sesMan.loadScene(); } private void loadPrjItemActionPerformed() { sesMan.loadProject(); // TODO add your code here } private void closeTabItemActionPerformed() { sesMan.processUnsavedChanges(Arrays.asList(sesMan.getActiveScene())); sesMan.unRegisterSceneContext(sesMan.getActiveScene()); } private void closePrjItemActionPerformed() { sesMan.closeAll(); } private void exitItemActionPerformed() { closePrjItemActionPerformed(); System.exit(0); } private void savePrjItemActionPerformed() { sesMan.saveProject(); } private void savePrjAsItemActionPerformed() { sesMan.saveProjectAs(); } public void setSceneName(SceneContext scene, String newSceneName) { if (sesMan.getActiveScene().equals(scene)) setTitle(ConfDesigner.CONF_DESIGNER + " - " + newSceneName); if (tabPane.getComponentCount() > 0) tabPane.setTitleAt(tabPane.indexOfComponent(projectsTabs.get(scene)), newSceneName); } public synchronized static Preferences getPrefs() { if (prefs == null) { prefs = Preferences.userNodeForPackage(ConfDesigner.class); } return prefs; } /** Updates the recent file dialog. */ public void updateRecentFiles(File fileLocation) { // get the list Preferences p = getPrefs(); recentFiles.clear(); for (int i = 0; i < 5; i++) { String path = p.get("recent" + i, null); if (path != null && new File(path).isFile()) { recentFiles.add(new File(path)); } } //update it if (fileLocation != null) if (recentFiles.isEmpty() || !recentFiles.get(0).equals(fileLocation)) recentFiles.add(0, fileLocation); for (int i = 0; i < recentFiles.size(); i++) { File file = recentFiles.get(i); p.put("recent" + i, file.getAbsolutePath()); } //update the menu recentMenu.removeAll(); for (File prefFile : recentFiles) { JMenuItem menuItem = new JMenuItem(prefFile.getName()); menuItem.addActionListener(recentFileListener); recentMenu.add(menuItem); } } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents // Generated using JFormDesigner Open Source Project license - Sphinx-4 (cmusphinx.sourceforge.net/sphinx4/) menuBar1 = new JMenuBar(); menu1 = new JMenu(); newTabItem = new JMenuItem(); loadItem = new JMenuItem(); saveTabItem = new JMenuItem(); saveTabAsItem = new JMenuItem(); loadPrjItem = new JMenuItem(); savePrjItem = new JMenuItem(); savePrjAsItem = new JMenuItem(); recentMenu = new JMenu(); closeTabItem = new JMenuItem(); closePrjItem = new JMenuItem(); exitItem = new JMenuItem(); menu2 = new JMenu(); cutItem = new JMenuItem(); copyItem = new JMenuItem(); pasteItem = new JMenuItem(); deleteItem = new JMenuItem(); menu3 = new JMenu(); snap2GridItem = new JCheckBoxMenuItem(); showBirdViewItem = new JCheckBoxMenuItem(); fitViewItem = new JMenuItem(); layoutGraphItem = new JMenuItem(); expSceneImgItem = new JMenuItem(); runMenu = new JMenu(); menu4 = new JMenu(); helpItem = new JMenuItem(); aboutItem = new JMenuItem(); hSpacer1 = new JPanel(null); label2 = new JLabel(); sceneFinder = new JTextField(); splitPane1 = new JSplitPane(); splitPane2 = new JSplitPane(); panel4 = new JPanel(); filterPanel = new JPanel(); label1 = new JLabel(); classFilterField = new JTextField(); filterResetButton = new JButton(); configurableTree = new ConfigSelector(); splitPane3 = new JSplitPane(); propSheetPanel = new PropertyEditorPanelNT(); birdViewPanel = new JPanel(); scenePane = new JPanel(); //======== this ======== setTitle("ConfDesigner"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== menuBar1 ======== { //======== menu1 ======== { menu1.setText("File"); //---- newTabItem ---- newTabItem.setText("New Tab"); newTabItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); newTabItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newItemActionPerformed(); } }); menu1.add(newTabItem); //---- loadItem ---- loadItem.setText("Load..."); loadItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); loadItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadItemActionPerformed(); } }); menu1.add(loadItem); //---- saveTabItem ---- saveTabItem.setText("Save Tab"); saveTabItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveTabItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveItemActionPerformed(); } }); menu1.add(saveTabItem); //---- saveTabAsItem ---- saveTabAsItem.setText("Save Tab As..."); saveTabAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK | KeyEvent.ALT_MASK)); saveTabAsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsItemActionPerformed(); } }); menu1.add(saveTabAsItem); menu1.addSeparator(); //---- loadPrjItem ---- loadPrjItem.setText("Load Project ..."); loadPrjItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)); loadPrjItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadPrjItemActionPerformed(); } }); menu1.add(loadPrjItem); //---- savePrjItem ---- savePrjItem.setText("Save Project"); savePrjItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)); savePrjItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { savePrjItemActionPerformed(); } }); menu1.add(savePrjItem); //---- savePrjAsItem ---- savePrjAsItem.setText("Save Project As ..."); savePrjAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK | KeyEvent.ALT_MASK | KeyEvent.SHIFT_MASK)); savePrjAsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { savePrjAsItemActionPerformed(); } }); menu1.add(savePrjAsItem); menu1.addSeparator(); //======== recentMenu ======== { recentMenu.setText("Open Recent"); } menu1.add(recentMenu); menu1.addSeparator(); //---- closeTabItem ---- closeTabItem.setText("Close Tab"); closeTabItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK)); closeTabItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeTabItemActionPerformed(); } }); menu1.add(closeTabItem); //---- closePrjItem ---- closePrjItem.setText("Close Project"); closePrjItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)); closePrjItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closePrjItemActionPerformed(); } }); menu1.add(closePrjItem); menu1.addSeparator(); //---- exitItem ---- exitItem.setText("Exit"); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exitItemActionPerformed(); } }); menu1.add(exitItem); } menuBar1.add(menu1); //======== menu2 ======== { menu2.setText("Edit"); //---- cutItem ---- cutItem.setText("Cut"); menu2.add(cutItem); //---- copyItem ---- copyItem.setText("Copy"); menu2.add(copyItem); //---- pasteItem ---- pasteItem.setText("Paste"); menu2.add(pasteItem); //---- deleteItem ---- deleteItem.setText("Delete"); menu2.add(deleteItem); } menuBar1.add(menu2); //======== menu3 ======== { menu3.setText("View"); //---- snap2GridItem ---- snap2GridItem.setText("Snap to Grid"); menu3.add(snap2GridItem); //---- showBirdViewItem ---- showBirdViewItem.setText("Show Birdview"); showBirdViewItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK)); showBirdViewItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showBirdViewItemActionPerformed(); } }); menu3.add(showBirdViewItem); menu3.addSeparator(); //---- fitViewItem ---- fitViewItem.setText("Fit View"); fitViewItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.ALT_MASK)); menu3.add(fitViewItem); //---- layoutGraphItem ---- layoutGraphItem.setText("Relayout Graph"); layoutGraphItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.ALT_MASK)); layoutGraphItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { layoutGraphItemActionPerformed(); } }); menu3.add(layoutGraphItem); menu3.addSeparator(); //---- expSceneImgItem ---- expSceneImgItem.setText("Export Scene Image"); menu3.add(expSceneImgItem); } menuBar1.add(menu3); //======== runMenu ======== { runMenu.setText("Run"); runMenu.setToolTipText("Can not find any exectutables within the current scene"); runMenu.setEnabled(false); } menuBar1.add(runMenu); //======== menu4 ======== { menu4.setText("Help"); //---- helpItem ---- helpItem.setText("Help"); helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); menu4.add(helpItem); //---- aboutItem ---- aboutItem.setText("About"); aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { aboutItemActionPerformed(); } }); menu4.add(aboutItem); } menuBar1.add(menu4); menuBar1.add(hSpacer1); //---- label2 ---- label2.setText(" find : "); menuBar1.add(label2); //---- sceneFinder ---- sceneFinder.setMaximumSize(new Dimension(100, 100)); sceneFinder.setPreferredSize(new Dimension(80, 20)); sceneFinder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sceneFinderActionPerformed(); } }); menuBar1.add(sceneFinder); } setJMenuBar(menuBar1); //======== splitPane1 ======== { splitPane1.setDividerSize(2); splitPane1.setResizeWeight(0.1); splitPane1.setDividerLocation(300); //======== splitPane2 ======== { splitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT); splitPane2.setResizeWeight(0.8); splitPane2.setDividerLocation(300); splitPane2.setDividerSize(2); splitPane2.setLastDividerLocation(350); //======== panel4 ======== { panel4.setPreferredSize(new Dimension(200, 400)); panel4.setMinimumSize(null); panel4.setMaximumSize(null); panel4.setLayout(new BorderLayout()); //======== filterPanel ======== { filterPanel.setLayout(new BorderLayout()); //---- label1 ---- label1.setText(" class filter : "); filterPanel.add(label1, BorderLayout.WEST); //---- classFilterField ---- classFilterField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { classFilterFieldActionPerformed(); } }); filterPanel.add(classFilterField, BorderLayout.CENTER); //---- filterResetButton ---- filterResetButton.setText("x"); filterResetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { filterResetButtonActionPerformed(); } }); filterPanel.add(filterResetButton, BorderLayout.EAST); } panel4.add(filterPanel, BorderLayout.SOUTH); //---- configurableTree ---- configurableTree.setMaximumSize(new Dimension(2111, 2111)); configurableTree.setMinimumSize(new Dimension(100, 200)); configurableTree.setPreferredSize(null); panel4.add(configurableTree, BorderLayout.CENTER); } splitPane2.setTopComponent(panel4); //======== splitPane3 ======== { splitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT); splitPane3.setResizeWeight(1.0); splitPane3.setMinimumSize(null); splitPane3.setPreferredSize(new Dimension(456, 300)); //---- propSheetPanel ---- propSheetPanel.setMinimumSize(null); propSheetPanel.setMaximumSize(null); propSheetPanel.setPreferredSize(new Dimension(100, 100)); splitPane3.setTopComponent(propSheetPanel); //======== birdViewPanel ======== { birdViewPanel.setMinimumSize(null); birdViewPanel.setMaximumSize(null); birdViewPanel.setPreferredSize(new Dimension(150, 150)); birdViewPanel.setLayout(new BorderLayout()); } splitPane3.setBottomComponent(birdViewPanel); } splitPane2.setBottomComponent(splitPane3); } splitPane1.setLeftComponent(splitPane2); //======== scenePane ======== { scenePane.setPreferredSize(new Dimension(200, 200)); scenePane.setFocusTraversalPolicyProvider(true); scenePane.setLayout(new BorderLayout()); } splitPane1.setRightComponent(scenePane); } contentPane.add(splitPane1, BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables // Generated using JFormDesigner Open Source Project license - Sphinx-4 (cmusphinx.sourceforge.net/sphinx4/) private JMenuBar menuBar1; private JMenu menu1; private JMenuItem newTabItem; private JMenuItem loadItem; private JMenuItem saveTabItem; private JMenuItem saveTabAsItem; private JMenuItem loadPrjItem; private JMenuItem savePrjItem; private JMenuItem savePrjAsItem; private JMenu recentMenu; private JMenuItem closeTabItem; private JMenuItem closePrjItem; private JMenuItem exitItem; private JMenu menu2; private JMenuItem cutItem; private JMenuItem copyItem; private JMenuItem pasteItem; private JMenuItem deleteItem; private JMenu menu3; private JCheckBoxMenuItem snap2GridItem; private JCheckBoxMenuItem showBirdViewItem; private JMenuItem fitViewItem; private JMenuItem layoutGraphItem; private JMenuItem expSceneImgItem; private JMenu runMenu; private JMenu menu4; private JMenuItem helpItem; private JMenuItem aboutItem; private JPanel hSpacer1; private JLabel label2; private JTextField sceneFinder; private JSplitPane splitPane1; private JSplitPane splitPane2; private JPanel panel4; private JPanel filterPanel; private JLabel label1; private JTextField classFilterField; private JButton filterResetButton; private ConfigSelector configurableTree; private JSplitPane splitPane3; private PropertyEditorPanelNT propSheetPanel; private JPanel birdViewPanel; private JPanel scenePane; // JFormDesigner - End of variables declaration //GEN-END:variables public static void main(String[] args) throws IOException, PropertyException { if (args.length == 1 && (args[0].equals("-help") || args[0].equals("-h") || args[0].startsWith("--h"))) { System.out.println(CONF_DESIGNER + " [-l <semicolon-separated list of jars or class-directories which " + "contain configurables>] [-f <config-xml or config-project-files>]" + "\n\n Note: The -l defines only which jars/locations to parse in order to find configurables. " + "Nevertheless all these jars/directories need to be contained in the class-path of " + CONF_DESIGNER + "."); System.exit(0); } List<String> addtionalClasses = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-l")) { assert args.length > i; addtionalClasses.addAll(Arrays.asList(args[i + 1].split(";"))); } } // find the intial file to be loaded File preLoadFile = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-f")) { assert args.length > i : "-f requires a file-argument"; preLoadFile = new File(args[i + 1]); break; } } ConfDesigner gui = new ConfDesigner(); if (preLoadFile != null && preLoadFile.isFile()) { if (preLoadFile.getName().endsWith(SessionManager.FORMAT_SUFFIX)) gui.getSesMan().loadScene(preLoadFile); else { assert preLoadFile.getName().endsWith(SessionManager.PROJECT_FORMAT_SUFFIX); gui.getSesMan().loadProject(preLoadFile); } } gui.addConfigurables(ClassPathParser.getConfigurableClasses(addtionalClasses)); gui.setBounds(getPrefs().getInt("mainwin.xpos", 100), getPrefs().getInt("mainwin.ypos", 100), getPrefs().getInt("mainwin.width", 900), getPrefs().getInt("mainwin.height", 700)); gui.setVisible(true); } public synchronized static Clipboard getClipBoard() { if (clipboard == null) { clipboard = new Clipboard("myClip"); } return clipboard; } } <file_sep>/archive_s3/s3.0/pgm/misc/pron.c /* * pron.c -- Extract pronunciations for words * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-May-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * Input lines of the form: * 354 .PERIOD => (TD) p ih r iy ax dd () * 9 IN => (S) [[ AX => IX ]] n (F) * 6 HELP PAY => (AX) hh eh l [[ => PD ]] p ey (F) * Output observed pronunciations for words and their counts */ #include <libutil/libutil.h> #define MAX_WORDS 4092 main (int32 argc, char *argv[]) { char line[16384], **wptr; int32 i, j, k, n, lineno, count; if (argc > 1) { E_INFO("Usage: %s < <filtered-dp-output>\n", argv[0]); exit(0); } wptr = (char **) ckd_calloc (MAX_WORDS, sizeof(char *)); lineno = 0; while (fgets (line, sizeof(line), stdin) != NULL) { lineno++; if ((n = str2words (line, wptr, MAX_WORDS)) < 0) E_FATAL("str2words(%s) failed; increase %d(?)\n", line, MAX_WORDS); if (n == 0) continue; for (i = 0; i < n; i++) ucase (wptr[i]); /* Read first (count) field */ if (sscanf (wptr[0], "%d", &count) != 1) E_FATAL("First field not a count: %s\n", wptr[0]); if (count == 0) break; /* Find => separator after word list, skip if word list length > 1 */ for (i = 0; (i < n) && (strcmp (wptr[i], "=>") != 0); i++); i++; /* Hopefully at (lc) */ if (i != 3) continue; /* Must have at least: (lc) p1 p2 (rc); remove () from lc and rc */ if (n-i <= 3) continue; k = strlen(wptr[i]) - 1; assert ((wptr[i][0] == '(') && (wptr[i][k] == ')')); wptr[i][k] = '\0'; (wptr[i])++; k = strlen(wptr[n-1]) - 1; assert ((wptr[n-1][0] == '(') && (wptr[n-1][k] == ')')); wptr[n-1][k] = '\0'; (wptr[n-1])++; /* Check if there are no errors */ for (j = i; (j < n) && (strcmp (wptr[j], "[[") != 0); j++); if (j >= n) { for (j = i; j < n; j++) lcase (wptr[j]); } else { /* Check if the only error is deletion of first geminate phone */ if ((strcmp (wptr[i+1], "[[") == 0) && (strcmp (wptr[i+2], "=>") == 0) && (strcmp (wptr[i+4], "]]") == 0) && (strcmp (wptr[i+3], wptr[i]) == 0)) { for (j = i+5; (j < n) && (strcmp (wptr[j], "[[") != 0); j++); if (j >= n) { for (j = i; j < n; j++) lcase (wptr[j]); } } } printf ("%s", wptr[1]); /* The word */ if ((strcmp (wptr[i+1], "[[") == 0) && (strcmp (wptr[i+2], "=>") == 0) && (strcmp (wptr[i+4], "]]") == 0)) { if (strcmp (wptr[i+3], wptr[i]) == 0) printf (" %s", wptr[i]); else printf (" (%s)", wptr[i]); } /* Print observed pronunciation */ for (i++; i < n-1; i++) { if (strcmp (wptr[i], "[[") != 0) printf (" %s", wptr[i]); else { for (i++; (strcmp (wptr[i], "=>") != 0); i++) printf (" %s", wptr[i]); for (i++; (strcmp (wptr[i], "]]") != 0); i++); } } /* Print count */ printf (" %d\n", count); fflush (stdout); } } <file_sep>/web/script/nightlyBuild.sh #!/bin/sh . ${HOME}/.profile # Check that we have all executables if ! RSYNC=`command -v rsync 2>&1`; then exit 1; fi if ! SCP=`command -v scp 2>&1`; then exit 1; fi if ! SVN=`command -v svn 2>&1`; then exit 1; fi if ! TAR=`command -v gtar 2>&1`; then if ! TAR=`command -v tar 2>&1`; then exit 1; fi fi loopUntilSuccess () { cmd=$@ # start loop to download code count=0; while ! $cmd; do count=`expr $count + 1` if [ $count -gt 50 ]; then # not successful, and we attempted it too many times. Clean up and l eave. return $count fi done } createNightlyBuild () { location=$1 module=$2 name=`echo $module | awk -F/ '{print $NF}'` TMP_DIR=${HOME}/project/SourceForge/build/nightly mkdir -p $TMP_DIR cd $TMP_DIR if test x$module != xsphinxbase; then loopUntilSuccess ${SVN} export -q https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/sphinxbase touch sphinxbase/src/libsphinxbase/libsphinxbase.la fi loopUntilSuccess ${SVN} export -q https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/$location $module cd $module || exit 1 # Somehow, we need to run autogen.sh twice... test -e autogen.sh && ./autogen.sh -q test -e autogen.sh && ./autogen.sh -q cd $TMP_DIR $TAR -czf /tmp/${name}.nightly.tar.gz $module || exit 1 chmod 664 /tmp/$name.nightly.tar.gz ${RSYNC} -e ssh /tmp/$name.nightly.tar.gz `whoami`,<EMAIL>:/home/frs/project/c/cm/cmusphinx/NightlyBuild/ cd /bin/rm -rf $TMP_DIR /bin/rm /tmp/${name}.nightly.tar.gz } nightlyBuildPage () { WEBPAGE=$1 cat <<-END > $WEBPAGE <html> <head> <title>Nightly Builds</title> <meta http-equiv=content-type content=text/html;charset=ISO-8859-1> <!-- Created by $0 on `hostname` --> </head> <body> <h1>Sphinx Open Source nightly builds available at SourceForge.net</h1> <h2>Applications</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/dictator.tar.gz">Eval Dictator tarball</a> or <a href="http://cmusphinx.org/download/nightly/dictator.jar">Eval Dictator jar</a></li> </ul> <h2>Common Libraries</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/sphinxbase.nightly.tar.gz">sphinxbase</a></li> </ul> <h2>Decoders</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/s3flat.nightly.tar.gz">s3flat</a></li> <li><a href="http://cmusphinx.org/download/nightly/pocketsphinx.nightly.tar.gz">pocketsphinx</a></li> <li><a href="http://cmusphinx.org/download/nightly/sphinx2.nightly.tar.gz">sphinx2</a></li> <li><a href="http://cmusphinx.org/download/nightly/sphinx3.nightly.tar.gz">sphinx3</a></li> <li><a href="http://cmusphinx.org/download/nightly/sphinx4.nightly.tar.gz">sphinx4</a></li> </ul> <h2>Acoustic Model Training</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/SphinxTrain.nightly.tar.gz">SphinxTrain</a></li> </ul> <h2>Language Model Training</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/SimpleLM.nightly.tar.gz">SimpleLM</a></li> <li><a href="http://cmusphinx.org/download/nightly/cmuclmtk.nightly.tar.gz">cmuclmtk</a></li> </ul> <h2>Tools</h2> <ul> <li><a href="http://cmusphinx.org/download/nightly/cepview.nightly.tar.gz">cepview</a></li> <li><a href="http://cmusphinx.org/download/nightly/lm3g2dmp.nightly.tar.gz">lm3g2dmp</a></li> </ul> <p>Last update on `date`</p> </body> </html> END } pushd ${HOME} createNightlyBuild cmuclmtk cmuclmtk createNightlyBuild sphinx2 sphinx2 createNightlyBuild sphinx3 sphinx3 createNightlyBuild sphinx4 sphinx4 #createNightlyBuild tools tools #updateDictator.sh createNightlyBuild sphinxbase sphinxbase createNightlyBuild pocketsphinx pocketsphinx createNightlyBuild SphinxTrain SphinxTrain #createNightlyBuild archive_s3/s3 s3flat #createNightlyBuild share/cepview cepview #createNightlyBuild share/lm3g2dmp lm3g2dmp #createNightlyBuild SimpleLM SimpleLM popd nightlypage=nightlybuild.html nightlyBuildPage $nightlypage ${SCP} -o "BatchMode yes" $nightlypage www.speech.cs.cmu.edu:/usr1/httpd/html/sphinx/download/nightly/index.html /bin/rm $nightlypage <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/propedit/EditorTableModel.java package edu.cmu.sphinx.tools.confdesigner.propedit; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.List; /** * DOCUMENT ME! * * @author <NAME> */ public class EditorTableModel extends AbstractTableModel { List<TableProperty> props = new ArrayList<TableProperty>(); public int getRowCount() { return props.size(); } public int getColumnCount() { return 2; } public Object getValueAt(int rowIndex, int columnIndex) { TableProperty property = props.get(rowIndex); //todo remove this!! if (property == null) return "test"; if (columnIndex == 0) { return property.toString(); } else { return property.getValue(); } } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { assert columnIndex == 1; props.get(rowIndex).setValue(aValue); } public void addProperty(TableProperty property) { assert property != null; props.add(property); fireTableDataChanged(); } public void clear() { props.clear(); fireTableDataChanged(); } public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex > 0 && !(getValueAt(rowIndex, columnIndex) instanceof JComboBox); } public TableProperty getProperty(int row) { return props.get(row); } } <file_sep>/archive_s3/s3.2/src/libutil/filename.h /* * filename.h -- File and path name operations. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 30-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #ifndef _LIBUTIL_FILENAME_H_ #define _LIBUTIL_FILENAME_H_ #include "prim_type.h" /* * Strip off leading path components from the given path and copy the base into base. * Caller must have allocated base. */ void path2basename (char *path, char *base); /* * Strip off the smallest trailing file-extension suffix and copy the rest into the * given root argument. Caller must have allocated root. */ void strip_fileext (char *file, char *root); #endif <file_sep>/tools/riddler/build.xml <?xml version="1.0" encoding="UTF-8"?> <!-- You may freely edit this file. See commented blocks below for --> <!-- some examples of how to customize the build. --> <!-- (If you delete it and reopen the project it will be recreated.) --> <project name="riddler" default="all" basedir="."> <description>Builds, tests, and runs the project riddler.</description> <property name="srcDir.dotNet" value="${basedir}/dotNet"/> <property environment="env"/> <target name="init-machine-properties" depends="setOSConditions,init-properties.win,init-properties.other"/> <target name="init-properties.win"> <property file="${basedir}/properties/${env.USERNAME}.properties"/> </target> <target name="init-properties.other"> <property file="${basedir}/properties/${env.USER}.properties"/> </target> <!--<target name="all" depends="deploy, run, undeploy"/>--> <target name="all" depends="deploy, run"/> <target name="clean" depends="init-common,undeploy"> <delete dir="${build.base.dir}"/> </target> <target name="assemble" depends="init-common, compile, pkg-server"/> <target name="init-common" depends="setToolProperty,init-machine-properties,setGlassfishClassPath"> <mkdir dir="${build.classes.dir}"/> <mkdir dir="${build.generated.dir}"/> <mkdir dir="${assemble.dir}"/> </target> <target name="setToolProperty" depends="setOSConditions,setToolWin,setToolUnix"> </target> <target name="setOSConditions"> <condition property="isUnix"> <os family="unix"/> </condition> <condition property="isWindows"> <os family="windows" /> </condition> </target> <target name="setToolWin" if="isWindows"> <property name="APPCLIENT" value="${env.GLASSFISH_HOME}/bin/appclient.bat"/> <property name="ASADMIN" value="${env.GLASSFISH_HOME}/bin/asadmin.bat"/> <property name="WSIMPORT" value="${env.GLASSFISH_HOME}/bin/wsimport.bat"/> <property name="WSGEN" value="${env.GLASSFISH_HOME}/bin/wsgen.bat"/> </target> <target name="setToolUnix" if="isUnix"> <property name="APPCLIENT" value="${env.GLASSFISH_HOME}/bin/appclient"/> <property name="ASADMIN" value="${env.GLASSFISH_HOME}/bin/asadmin"/> <property name="WSIMPORT" value="${env.GLASSFISH_HOME}/bin/wsimport"/> <property name="WSGEN" value="${env.GLASSFISH_HOME}/bin/wsgen"/> </target> <target name="setGlassfishClassPath" unless="glassfish.classpath"> <path id="glassfish_classpath_jars"> <fileset dir="${env.GLASSFISH_HOME}/lib" includes="*.jar"/> </path> <pathconvert pathsep=":" property="glassfish.classpath" refid="glassfish_classpath_jars"/> </target> <target name="compile" depends="init-common"> <javac srcdir="java" destdir="${build.classes.dir}" classpath="${glassfish.classpath}" debug="on" failonerror="true"/> </target> <target name="pkg-server" depends="init-common"> <echo message="my build classes dir is:${build.classes.dir}" level="verbose"/> <mkdir dir="${build.classes.dir}/tmp"/> <mkdir dir="${build.classes.dir}/tmp/META-INF"/> <mkdir dir="${build.classes.dir}/tmp/META-INF/wsdl"/> <copy todir="${build.classes.dir}/tmp"> <fileset dir="${build.classes.dir}"> <include name="edu/cmu/sphinx/tools/riddler/ejb/**/*.class"/> <include name="edu/cmu/sphinx/tools/riddler/shared/**/*.class"/> <include name="edu/cmu/sphinx/tools/riddler/persist/**/*.class"/> </fileset> </copy> <copy todir="${build.classes.dir}/tmp/META-INF/wsdl"> <fileset dir="${build.generated.dir}"> <include name="**/*.*"/> </fileset> </copy> <echo message="Creating archive file ${assemble.dir}/${appname}.jar" level="verbose"/> <jar jarfile="${assemble.dir}/${appname}.jar" update="true"> <fileset dir="${build.classes.dir}/tmp" casesensitive="yes"> <include name="**/*class*"/> </fileset> <fileset dir="${build.classes.dir}/tmp" casesensitive="yes"> <include name="META-INF/wsdl/*.*"/> </fileset> <metainf dir="${basedir}/conf" includes="persistence.xml"/> </jar> <echo message="created jar file ${assemble.dir}/${appname}.jar" level="verbose"/> </target> <target name="pkg-client" depends="init-common"> <jar jarfile="${assemble.dir}/${appname}-client.jar" update="true"> <fileset dir="${build.classes.dir}"> <include name="edu/cmu/sphinx/tools/riddler/client/**/*.class"/> <include name="edu/cmu/sphinx/tools/riddler/shared/**/*.class"/> <include name="edu/cmu/sphinx/tools/riddler/persist/**/*.class"/> </fileset> </jar> <echo message="created jar file ${assemble.dir}/${appname}-client.jar" level="verbose"/> </target> <target name="deploy" depends="init-common, assemble"> <echo message="Deploying ${assemble.dir}/${appname}.jar from ${basedir}." level="verbose"/> <echo message="asadmin deploy --user ${admin.user} --passwordfile ${admin.password.file} --host ${admin.host} --port ${admin.port} --contextroot ${appname} --upload=true --target ${appserver.instance.name}"/> <exec executable="${ASADMIN}" failonerror="false"> <arg line="deploy"/> <arg line="--user ${admin.user}"/> <arg line="--passwordfile ${admin.password.file}"/> <arg line="--host ${admin.host}"/> <arg line="--port ${admin.port}"/> <arg line="--contextroot ${appname}"/> <arg line="--upload=true"/> <arg line="--target ${appserver.instance.name}"/> <arg line="${assemble.dir}/${appname}.jar"/> </exec> </target> <target name="run" depends="deploy,pkg-client"> <echo message="Executing standalone client."/> <java fork="true" classname="edu.cmu.sphinx.tools.riddler.client.Main"> <classpath> <pathelement location="${env.GLASSFISH_HOME}/lib/javaee.jar"/> <pathelement location="${env.GLASSFISH_HOME}/lib/appserv-rt.jar"/> <pathelement location="${assemble.dir}/${appname}-client.jar"/> </classpath> <jvmarg value="-Dorg.omg.CORBA.ORBInitialHost=localhost"/> </java> </target> <target name="undeploy" depends="init-common"> <echo message="Undeploying {appname}" level="verbose"/> <echo message="asadmin undeploy --user ${admin.user} --passwordfile ${admin.password.file} --host ${admin.host} --port ${admin.port} ${appname}"/> <exec executable="${ASADMIN}" failonerror="false"> <arg line="undeploy"/> <arg line="--user ${admin.user}"/> <arg line="--passwordfile ${admin.password.file}"/> <arg line="--host ${admin.host}"/> <arg line="--port ${admin.port}"/> <arg line="${appname}"/> </exec> </target> <taskdef resource="org/apache/ant/dotnet/antlib.xml"> <classpath> <pathelement location="${basedir}/../common/lib/ant-dotnet.jar"/> </classpath> </taskdef> <target name="genStubs" depends="deploy,genStubs.win,genStubs.other" description="container target for WSDL generation tasks"/> <target name="genStubs.win" if="isWindows"> <property name="MSDEV.home" value="C:/tool/MSVS8"/> <exec command="${MSDEV.home}/SDK/v2.0/Bin/wsdl.exe"> <arg value="/out:${srcDir.dotNet}\RiddlerStubs.cs"/> <arg value="/namespace:edu.cmu.sphinx.riddler"/> <!--<arg value="http://localhost:8080/${ant.project.name}/${ant.project.name}?wsdl"/>--> <arg value="http://localhost:8080/RiddlerBeanService/RiddlerBean?wsdl"/> </exec> </target> <target name="genStubs.other" unless="isWindows"> <!-- TODO garrett 1/6/07: invoke Mono's WSDL-to-C# tool --> </target> <target name="test" depends="genStubs"> <mkdir dir="${build.base.dir}"/> <nant> <target name="build"/> <build> <target name="build"> <!--<csc target="library" output="${build.base.dir}/riddler-tests.dll">--> <csc target="library" output="${build.base.dir}/riddler-tests.dll"> <sources basedir="${srcDir.dotNet}"> <include name="**/*.cs" /> </sources> <references> <include name="${env.NUNIT_HOME}/bin/nunit.framework.dll"/> </references> </csc> </target> </build> </nant> <nunit> <testassembly name="${build.base.dir}/riddler-tests.dll"/> </nunit> </target> </project> <file_sep>/SphinxTrain/include/s2/log.h /* ==================================================================== * Copyright (c) 1989-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* last edit by <NAME> on October 10, 1989 */ #define BASE 1.0001 #define LOG_BASE 9.9995000333297321e-05 #define R_LOG_BASE 1.0000499991668185e+04 /* #define MIN_LOG (-1 << 29) */ #define MIN_LOG (-1 << 27) #define ADDITION_TABLE_SIZE 99042 #define SUBTRACTION_TABLE_SIZE 99042 #define FIX(X) ((X) <= MIN_LOG ? MIN_LOG : (X)) #define EXP(X) (exp ((X) * LOG_BASE)) #define LOG(X) ((X) <= 0 ? MIN_LOG : (int) (log ((double) (X)) * R_LOG_BASE)) #define MULTIPLY(X, Y) ((X) + (Y) <= MIN_LOG ? MIN_LOG : (X) + (Y)) #define ADD(X, Y) ((X) > (Y) ? (Y) <= MIN_LOG || (unsigned) ((X) - (Y)) >= ADDITION_TABLE_SIZE ? (X) : (X) + Addition_Table[(X) - (Y)] : (X) <= MIN_LOG || (unsigned) ((Y) - (X)) >= ADDITION_TABLE_SIZE ? (Y) : (Y) + Addition_Table[(Y) - (X)]) #define SUBTRACT(X, Y) ((X) <= (Y) ? MIN_LOG : (unsigned) ((X) - (Y)) >= SUBTRACTION_TABLE_SIZE ? (X) : (X) - Subtraction_Table[(X) - (Y)]) /* ADD_ASSIGN (X, Y) is equivalent to X = ADD (X, Y) and MULTIPLY_ASSIGN (X, Y) is equivalent to X = MULTIPLY (X, Y) but they are faster */ #define MULTIPLY_ASSIGN(X, Y) ((X) + (Y) <= MIN_LOG ? ((X) = MIN_LOG) : ((X) += (Y))) #define ADD_ASSIGN(X, Y) ((X) > (Y) ? (Y) <= MIN_LOG || (unsigned) ((X) - (Y)) >= ADDITION_TABLE_SIZE ? (X) : ((X) += Addition_Table[(X) - (Y)]) : (X) <= MIN_LOG || (unsigned) ((Y) - (X)) >= ADDITION_TABLE_SIZE ? ((X) = (Y)) : ((X) = (Y) + Addition_Table[(Y) - (X)])) #define SUBTRACT_ASSIGN(X, Y) ((X) <= (Y) ? ((X) = MIN_LOG) : (unsigned) ((X) - (Y)) >= SUBTRACTION_TABLE_SIZE ? (X) : ((X) -= Subtraction_Table[(X) - (Y)])) #include <math.h> extern short Addition_Table[ADDITION_TABLE_SIZE]; extern int Subtraction_Table[SUBTRACTION_TABLE_SIZE]; <file_sep>/SphinxTrain/src/libs/libcommon/lexicon.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: lexicon.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/lexicon.h> #include <s3/ckd_alloc.h> #include <s3/n_words.h> #include <s3/read_line.h> #include <s3/s3.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> static int add_word(char *ortho, uint32 wid, lexicon_t *l, lex_entry_t *e) { e->ortho = ortho; e->word_id = wid; if (hash_enter(l->ht, e->ortho, (void *)e) != 0) { E_FATAL("hash add failed\n"); } return S3_SUCCESS; } static int add_phones(uint32 n_phone, lex_entry_t *e, acmod_set_t *acmod_set) { uint32 i; char *nxt_phone; e->phone = ckd_calloc(n_phone, sizeof(char *)); e->ci_acmod_id = ckd_calloc(n_phone, sizeof(uint32)); e->phone_cnt = n_phone; for (i = 0; (nxt_phone = strtok(NULL, " \t")); i++) { e->phone[i] = nxt_phone; e->ci_acmod_id[i] = acmod_set_name2id(acmod_set, nxt_phone); if (e->ci_acmod_id[i] == NO_ACMOD) { E_ERROR("Unknown phone %s\n", nxt_phone); ckd_free(e->phone); e->phone = NULL; ckd_free(e->ci_acmod_id); e->ci_acmod_id = NULL; e->phone_cnt = 0; return S3_ERROR; } } assert(i == n_phone); return S3_SUCCESS; } lexicon_t *lexicon_new() { lexicon_t *new; new = ckd_calloc(1, sizeof(lexicon_t)); new->head = new->tail = NULL; new->entry_cnt = 0; new->ht = hash_new("lex", 64000); return new; } lex_entry_t *lexicon_append_entry(lexicon_t *lex) { lex_entry_t *new; new = ckd_calloc(1, sizeof(lex_entry_t)); if (lex->head == NULL) { lex->head = lex->tail = new; } else { lex->tail->next = new; lex->tail = new; } lex->entry_cnt++; return new; } lexicon_t *lexicon_read(lexicon_t *prior_lex, const char *filename, acmod_set_t *acmod_set) { FILE *lex_fp; char line[1024]; char *lex_line; lexicon_t *lex; lex_entry_t *next_entry = NULL; uint32 wid, start_wid; uint32 n_phone; uint32 lineno = 0; int reuse_entry = FALSE; char *word; lex_fp = fopen(filename, "r"); if (lex_fp == NULL) { E_FATAL_SYSTEM("Unable to open lexicon %s for reading\n", filename); } if (prior_lex) lex = prior_lex; else lex = lexicon_new(); if (lex->phone_set == NULL) lex->phone_set = acmod_set; for (start_wid = wid = lex->entry_cnt; read_line(line, 1023, &lineno, lex_fp) != NULL; /* wid incremented in body of loop */ ) { if (line[0] == '\n') { E_WARN("Lexicon %s has a blank line at line %d\n", filename, lineno); continue; } if (!reuse_entry) { next_entry = lexicon_append_entry(lex); } else { reuse_entry = FALSE; /* reset to standard case */ } /* allocate space for string. It will be parsed * by strtok() */ lex_line = strdup(line); /* get the word and make a hash table entry for this lexicon entry */ word = strtok(lex_line, " \t"); if (add_word(word, wid, lex, next_entry) != S3_SUCCESS) { E_ERROR("%s duplicate entry?\n", word); reuse_entry = TRUE; /* Since this line is skipped, reuse * the lex entry for the next line */ continue; } /* n_words() counts the # of space separated "words" on a line */ n_phone = n_words(line)-1; #ifdef LEXICON_VERBOSE E_INFO("%s %d phones\n", line, n_phone); #endif /* read the phones, convert to ids and add them to the phone list for this entry */ if (add_phones(n_phone, next_entry, acmod_set) != S3_SUCCESS) { E_ERROR("pronunciation for %s has undefined phones; skipping.\n", word); reuse_entry = TRUE; continue; } ++wid; /* only happens should everything be successful */ } E_INFO("%d entries added from %s\n", wid - start_wid, filename); fclose(lex_fp); return lex; } lex_entry_t *lexicon_lookup(lexicon_t *lex, char *ortho) { lex_entry_t *cur; if (hash_lookup(lex->ht, ortho, (void **)&cur) == 0) { return cur; } else if (lex->lts_rules) { int i, wid; char *word; E_INFO("No defined pronunciation for %s, using LTS prediction: ", ortho); wid = lex->entry_cnt; cur = lexicon_append_entry(lex); lts_apply(ortho, "", lex->lts_rules, cur); /* Check that all the phones are in the mdef (we have real * problems if not!) */ for (i = 0; i < cur->phone_cnt; ++i) { E_INFOCONT("%s ", cur->phone[i]); cur->ci_acmod_id[i] = acmod_set_name2id(lex->phone_set, cur->phone[i]); if (cur->ci_acmod_id[i] == NO_ACMOD) { E_INFOCONT("\n"); E_ERROR("Unknown phone %s\n", cur->phone[i]); ckd_free(cur->phone); cur->phone = NULL; ckd_free(cur->ci_acmod_id); cur->ci_acmod_id = NULL; cur->phone_cnt = 0; return NULL; } } E_INFOCONT("\n"); word = ckd_salloc(ortho); if (add_word(word, wid, lex, cur) != S3_SUCCESS) { E_ERROR("Failed to add LTS pronunciation to lexicon!\n"); return NULL; } return cur; } else return NULL; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.8 2005/09/16 20:08:40 dhdfu * fix a memory problem - hash_enter does not copy keys * * Revision 1.7 2005/09/15 20:05:55 dhdfu * fix handling of wids, add a FIXME because for some reason the hashing is not working (though otherwise things are fine) * * Revision 1.6 2005/09/15 19:56:42 dhdfu * fix small bugs, LTS support works now * * Revision 1.5 2005/09/15 19:36:01 dhdfu * Add (as yet untested) support for letter-to-sound rules (from CMU * Flite) when constructing sentence HMMs in Baum-Welch. Currently only * rules for CMUdict exist. Of course this is not a substitute for * actually checking pronunciations... * * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.11 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.10 1996/07/29 16:36:56 eht * Incorporate Ravi's new hashing module * * Revision 1.9 1995/11/10 19:27:23 eht * Fix the case when a word has a zero length pronunciation * * Revision 1.7 1995/10/10 18:35:40 eht * Included <s3/n_words.h> for n_words() prototype * * Revision 1.6 1995/10/10 17:50:43 eht * *** empty log message *** * * Revision 1.5 1995/10/09 20:56:36 eht * Changes needed for prim_type.h * * Revision 1.4 1995/10/09 15:02:03 eht * Changed ckd_alloc interface to get rid of __FILE__, __LINE__ arguments * * Revision 1.3 1995/09/08 19:11:14 eht * Updated to use new acmod_set module. Prior to testing * on TI digits. * * Revision 1.2 1995/09/07 19:02:14 eht * Added ability to ignore (with a warning message) blank lines * * Revision 1.1 1995/06/02 14:52:54 eht * Initial revision * * */ <file_sep>/SphinxTrain/src/libs/libs2io/s2_write_cb.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s2_write_cb.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s2_write_cb.h> #include <s3/s2_param.h> #include <s3/s2io.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/common.h> #include <sys_compat/file.h> #include <stdio.h> #include <assert.h> #include <string.h> static uint32 cb_vlen[S2_N_FEATURE] = { S2_CEPF_VECLEN+1, S2_DCEPF_VECLEN+1, S2_POWF_VECLEN, S2_2DCEPF_VECLEN+1 }; static uint32 f_vlen[S2_N_FEATURE] = { S2_CEPF_VECLEN, S2_DCEPF_VECLEN, S2_POWF_VECLEN, S2_2DCEPF_VECLEN }; static int screwball_offset[S2_N_FEATURE] = { 1, 1, 0, 1 }; int s2_write_cb(gauden_t *g, const char *out_dir_name, const char **cb_base, const char *mean_ext, const char *var_ext, int do_floor) { vector_t ***mean; vector_t ***var; float32 *raw; uint32 i, j, f, s; char cb_filename[MAXPATHLEN+1]; if (!g) { E_FATAL("NULL pointer to new format gaussian.\n"); } if (g->n_feat != S2_N_FEATURE) { E_ERROR("New format gaussian has wrong num features (%d should be %d).\n", g->n_feat, S2_N_FEATURE); return S3_ERROR; } for (i = 0; i < S2_N_FEATURE; i++) { if (!g->veclen || (g->veclen[i] != f_vlen[i])) { fprintf(stderr, "%s(%d): New format gaussian feature %d wrong length (%d should be %d).\n", __FILE__, __LINE__, i, g->veclen[i], f_vlen[i]); return S3_ERROR; } } mean = gauden_mean(g); var = gauden_var(g); #if 0 fflush(stdout); fprintf(stderr, "%s(%d): constant power variance\n", __FILE__, __LINE__); fflush(stderr); /* power variance is a constant for S2 */ for (i = 0; i < S2_N_CODEWORD; i++) { for (j = 0; j < f_vlen[S2_POW_FEATURE]; j++) { var[0][S2_POW_FEATURE][i][j] = pv[j]; } } #endif /* COMMENT */ fflush(stdout); fprintf(stderr, "%s(%d): writing gau den to (", __FILE__, __LINE__); for (s = 0; s < 1; s++) { /* PUT NUMBER OF PHONE SETS HERRE!!! */ for (f = 0; f < S2_N_FEATURE; f++) { sprintf(cb_filename, "%s/%s.%s", out_dir_name, cb_base[f], mean_ext); fprintf(stderr, "\n\t%s ", cb_filename); fflush(stderr); /* first the means */ raw = ckd_calloc(S2_N_CODEWORD * cb_vlen[f], sizeof(float32)); for (j = 0; j < S2_N_CODEWORD; j++) { memcpy(&raw[(j * cb_vlen[f]) + screwball_offset[f]], mean[s][f][j], f_vlen[f] * sizeof(float32)); } if (awritefloat(cb_filename, raw, (S2_N_CODEWORD * cb_vlen[f])) < 0) E_FATAL("could not write to %s\n", cb_filename); ckd_free(raw); raw = NULL; /* then the (diagonal co-)variances */ if (var) { sprintf(cb_filename, "%s/%s.%s", out_dir_name, cb_base[f], var_ext); fprintf(stderr, "%s", cb_filename); fflush(stderr); raw = ckd_calloc(S2_N_CODEWORD * cb_vlen[f], sizeof(float32)); for (j = 0; j < S2_N_CODEWORD; j++) { memcpy(&raw[(j * cb_vlen[f]) + screwball_offset[f]], var[s][f][j], f_vlen[f] * sizeof(float32)); } if (awritefloat(cb_filename, raw, (S2_N_CODEWORD * cb_vlen[f])) < 0) E_FATAL("could not write to %s\n", cb_filename); ckd_free(raw); raw = NULL; } } /* end for f (feature) */ } /* end for cb_set */ return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.8 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.7 1996/01/23 18:12:42 eht * Changes to remove either: * unused local variables * broken printf() format specifications * missing function prototypes in header files * * Revision 1.6 1995/11/30 21:01:38 eht * Get rid of some debugging printfs * Also deal with not outputting var's if they are not available * * Revision 1.5 1995/10/17 14:03:23 eht * Changed to port to Windows NT * * Revision 1.4 1995/10/12 17:42:40 eht * Get SPHINX-II header files from <s2/...> * * Revision 1.3 1995/10/10 12:27:37 eht * Changed to use <s3/prim_type.h> * * Revision 1.2 1995/10/09 15:08:24 eht * changed ckd_alloc interface to remove need for __FILE__, __LINE__ * arguments * * Revision 1.1 1995/09/07 19:25:49 eht * Initial revision * * */ <file_sep>/SphinxTrain/python/cmusphinx/__init__.py """\ SphinxTrain Python Modules. """ __all__ = ['arpalm', 'mfcc', 'mllt', 's2mfc', 's3file', 's3gaucnt', 's3gau', 's3lda', 's3mdef', 'mllr', 's3mixw', 's3model', 's3tmat', 's3dict', 's3senmgau', 'feat', 'gmm', 'divergence', 'hypseg'] __author__ = "<NAME> <<EMAIL>>" __version__ = "$Revision$" <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/conftree/ConfigSelector.java package edu.cmu.sphinx.tools.confdesigner.conftree; import edu.cmu.sphinx.tools.confdesigner.SceneController; import edu.cmu.sphinx.util.props.Configurable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * DOCUMENT ME! * * @author <NAME> */ public class ConfigSelector extends JPanel { private List<ConfigurableTree> treeList = new ArrayList<ConfigurableTree>(); public ConfigSelector() { setLayout(new BorderLayout()); JTabbedPane tabPane = new JTabbedPane(); ConfigurableTree packageTree = new PackageTree(); ConfigurableTree categoryTree = new CategoryTree(); ConfigurableTree virtModuleTree = new PackageTree(); treeList.add(packageTree); treeList.add(categoryTree); treeList.add(virtModuleTree); JScrollPane scrollPane; scrollPane = new JScrollPane(); scrollPane.setViewportView(packageTree); tabPane.addTab("package", scrollPane); scrollPane = new JScrollPane(); scrollPane.setViewportView(categoryTree); tabPane.addTab("category", scrollPane); scrollPane = new JScrollPane(); scrollPane.setViewportView(virtModuleTree); tabPane.addTab("virtual", scrollPane); add(tabPane); } public void setController(SceneController controller) { for (ConfigurableTree tree : treeList) { tree.setController(controller); } } public void addConfigurables(Collection<Class<? extends Configurable>> configClasses) { for (ConfigurableTree configurableTree : treeList) { configurableTree.addConfigurables(configClasses); } } public void setFilter(String filterText) { for (ConfigurableTree configurableTree : treeList) { configurableTree.setFilter(filterText); } } } <file_sep>/misc_scripts/do_pp.sh #!/usr/bin/env bash # # compute PP on an utt by utt basis; # produce a table for mapping id to PP, coverage and WER if [ $# != 1 ] ; then echo "usage: do_pp.sh <testset> (e.g: 1046, PP50, etc)" ; exit ; fi testset=$1 ref=traveler_$testset.ref ctl=traveler_$testset.ctl CMUCLMTK=/work/air/cmusphinx/cmuclmtk/bin lm=eng_lm_20090930_final.lm # compute perplexities and coverage (using hacked evallm) echo "uttperp -text etc/$ref" \ | $CMUCLMTK/evallm -arpa etc/$lm -context etc/cmucuslmtk.ccs \ > $$.do_pp scripts/extract_PP_coverage.pl $$.do_pp > $$.lmtk_PP_output rm $$.do_pp # map uttid to PP and utterance in a 3 column file pr -m -s \ -T etc/$ctl \ $$.lmtk_PP_output \ etc/$ref \ > traveler_$testset.pp_map rm $$.lmtk_PP_output # <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/corpus/Note.java package edu.cmu.sphinx.tools.corpus; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Mar 3, 2006 * Time: 9:40:28 PM */ /** * A Note is a piece of text associated with a span of time. It might be used to describe * a region of data in a Word or and Utterance. */ public class Note { String text; int beginTime; int endTime; public int getBeginTime() { return beginTime; } public void setBeginTime(int beginTime) { this.beginTime = beginTime; } public int getEndTime() { return endTime; } public void setEndTime(int endTime) { this.endTime = endTime; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Note(int beginTime, int endTime, String text) { this.beginTime = beginTime; this.endTime = endTime; this.text = text; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Note note = (Note) o; if (beginTime != note.beginTime) return false; if (endTime != note.endTime) return false; if (text != null ? !text.equals(note.text) : note.text != null) return false; return true; } public int hashCode() { int result; result = (text != null ? text.hashCode() : 0); result = 29 * result + beginTime; result = 29 * result + endTime; return result; } } <file_sep>/SphinxTrain/src/libs/libcommon/btree.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: btree.c * * Description: * * Author: * *********************************************************************/ #include <s3/btree.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <assert.h> #include <stddef.h> #include <stdio.h> bt_t * bt_new() { bt_t *out; out = (bt_t *)ckd_calloc(1, sizeof(bt_t)); return out; } bt_node_t * bt_new_node(uint32 key) { bt_node_t *out; out = (bt_node_t *)ckd_calloc(1, sizeof(bt_node_t)); out->key = key; return out; } void bt_free_node(bt_node_t *n) { ckd_free(n); } void bt_free_tree(bt_t *t) { bt_free_subtree(t->root); ckd_free((void *)t); } bt_node_t * bt_find_node_subtree(bt_node_t *node, uint32 key) { bt_node_t *ret = NULL; if (node->key == key) { return node; } if (node->l) { ret = bt_find_node_subtree(node->l, key); } else { } if (ret) return ret; if (node->r) { ret = bt_find_node_subtree(node->r, key); } else { } return ret; } bt_node_t * bt_find_node(bt_t *t, uint32 key) { bt_node_t *ret; if (t->root) { ret = bt_find_node_subtree(t->root, key); } else { return NULL; } return ret; } void bt_free_subtree(bt_node_t *n) { bt_free_subtree(n->l); bt_free_subtree(n->r); bt_free_node(n); } bt_node_t * bt_add_left(bt_node_t *p, uint32 key) { bt_node_t *l; l = bt_new_node(key); l->p = p; p->l = l; return l; } bt_node_t * bt_add_right(bt_node_t *p, uint32 key) { bt_node_t *r; r = bt_new_node(key); r->p = p; p->r = r; return r; } void bt_visit_pre(bt_node_t *n, void *data, node_op_fn_t op) { if (n == NULL) return; assert(op != NULL); op(data, n); bt_visit_pre(n->l, data, op); bt_visit_pre(n->r, data, op); } void bt_visit_post(bt_node_t *n, void *data, node_op_fn_t op) { if (n == NULL) return; assert(op != NULL); bt_visit_post(n->l, data, op); bt_visit_post(n->r, data, op); op(data, n); } void bt_visit(bt_node_t *n, void *data, node_op_fn_t op) { if (n == NULL) return; assert(op != NULL); bt_visit_post(n->l, data, op); op(data, n); bt_visit_post(n->r, data, op); } void bt_print(bt_node_t *n, void *data, node_op_fn_t op) { if (n == NULL) return; assert(op != NULL); printf("( "); op(data, n); bt_print(n->l, data, op); printf(" "); bt_print(n->r, data, op); printf(" )"); } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 96/06/17 14:33:25 eht * Added include of <stdio.h> since standard i/o is used here * * Revision 1.2 1996/03/25 15:30:20 eht * *** empty log message *** * * Revision 1.1 1996/03/04 15:55:30 eht * Initial revision * * */ <file_sep>/CLP/src/Consensus.cc //----------------------------------------------------------------------------------------------------- // Consensus.cc : finds the consensus hypothesis and the confusion network corresponding to a lattice //----------------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //-------------------------------------------------------------------------------------- #include <cstdlib> #include <climits> #include <cassert> #include <iostream> #include <fstream> #include <iomanip> #include <ctype.h> #include <string> #include <sys/types.h> #include <sys/stat.h> using namespace std; #include "common_lattice.h" #include "Prob.h" #include "GetOpt.h" #include "LatticeInfo.h" #include "Link.h" #include "Lattice.h" #include "Prons.h" #include "Cluster.h" #include "Clustering.h" void Usage() { cout << "\nUSAGE:\n"; cout << "consensus -i <filelist> [-c <outfile>] [-C <outdir>] -R <pronfile> [-G <logfile>] [-S <scale>] [-L <LMweight>] [-l <PMweight>] " << endl << " [-P <PMweight>] [-p <PMoldscale>] [-I <WIP>] [-D <DELweight>] [-T <thresh>] [-t <percentage>] [-m <intraword>] [-M <interword>] " << endl << " [-e <lowEpsT>} [-E <highEpsT>] [-w <lowWordT>] [-W <highWordT>] [-f] [-o] [-s] [-b] [-n]" << endl << endl << "where " << endl << "-f - specifies that the format of the input files is FSM (default SLF)" << endl << "-o - don't use the time information available(if) in the file " << endl << "-s - don't use the phonetic similarity " << endl << "-i <filelist> - the input file (default stdin)" << endl << "-B <basedir> - base directory for input files (default none)" << endl << "-x <extension> - file extension for input files (default none)" << endl << "-F - use full path from filelist as label (deafult false)" << endl << "-c <outfile> - the output file for the consensus hyp (default stdout)" << endl << "-C <outdir> - the output dir for the conf nets in FSM format (default don't output)" << endl << "-R <pronfile> - the file containing the number of prons and the most likely pron for a word" << endl << "-G <logfile> - the log file showing the values of the parameters used to produce the output" << endl << "-S <scale> - the scale for the posterior distribution (default 1)" << endl << "-L <LMweight> - language model weight (default 1)" << endl << "-l <LMoldscale> - specify this value only if the LM scores are already scaled (we need to unscale them before using the new LM weight" << endl << "-P <PMweight> - pronunciation model weight (default 0)" << endl << "-p <PMoldscale> - specify this value only if the PM scores are already scaled" << endl << "-I <wdpenalty> - word insertion penalty " << endl << "-D <DELweight> - the weight of the deletion (default 1)" << endl << "-T <thresh> - the threshold used for pruning low posterior links (default 0; i.e no pruning)" << endl << "-t <percetage> - the percentage of links that are kept; this is an alternative pruning method" << endl << "-m <intraword> - the method used in the intraword clustering (max or avg; default max)" << endl << "-M <interword> - the method used in the interword clustering (max or avg; default max)" << endl << "-e <lowEpsT> - prune eps if its score is less than lowEpsT (default 0; i.e no pruning)" << endl << "-E <highEpsT> - prune all the other words in the bin if the score of deletion (eps) is greater than highEpsT (default 1; i.e no pruning)" << endl << "-w <lowWordT> - prune all the words with score less than lowWordT (default 0; i.e no pruning)" << endl << "-W <highWordT> - prune all the other words if the highest scoring one has a score greater than highWordT (default 1; i.e no pruning)" << endl << "-b - constrain the intra-word clustering step (default false)" << endl << "-n - constrain the inter-word clustering step (default false)" << endl << endl; } float lmweight = 0.0; float prweight = 0.0; float wdpenalty = 0.0; float delweight = 1.0; float thresh = INT_MAX; // none of the links is pruned float scale = 1.0; float lmoldscale = 0.0; float proldscale = 0.0; float lowEpsT = 0.0; float highEpsT = 1.0; float lowWordT = 0.0; float highWordT = 1.0; string type = "SLF"; string method_intraword = "max"; string method_interword = "max"; bool wdpenalty_was_set = false; bool lmscale_was_set = false; bool lmweight_was_set = false; bool prscale_was_set = false; bool prweight_was_set = false; bool percentage_pruning = false; bool score_pruning = false; bool use_time_info = true; bool use_phon_info = true; bool constrain_intra = false; bool constrain_inter = false; bool output_fullpath = false; int main(int argc, char * argv[]) { GetOpt opt(argc, argv, "fosnbi:c:C:R:S:G:L:l:P:p:I:E:e:W:w:D:T:t:m:M:B:x:F"); int ch; string infile(""), outfile(""), outdir(""); string pronfile(""),logfile(""); string basedir(""); string fileext(""); bool first = true; while((ch = opt()) != EOF || first){ first = false; switch(ch) { case 'f': type = "FSM"; break; case 'i': infile = opt.optarg; break; case 'c': outfile = opt.optarg; break; case 'C': outdir = opt.optarg; break; case 'R': pronfile = opt.optarg; break; case 'G': logfile = opt.optarg; break; case 'S': scale = atof(opt.optarg); break; case 'P': prweight = atof(opt.optarg); prweight_was_set = 1; break; case 'p': proldscale = atof(opt.optarg); break; case 'L': lmweight = atof(opt.optarg); lmweight_was_set = 1; break; case 'l': lmoldscale = atof(opt.optarg); break; case 'I': wdpenalty = atof(opt.optarg); wdpenalty_was_set = 1; break; case 'D': delweight = atof(opt.optarg); break; case 'm': method_intraword = opt.optarg; break; case 'M': method_interword = opt.optarg; break; case 'e': lowEpsT = atof(opt.optarg); break; case 'E': highEpsT = atof(opt.optarg); break; case 'w': lowWordT = atof(opt.optarg); break; case 'W': highWordT = atof(opt.optarg); break; case 'T': thresh = atof(opt.optarg); score_pruning = true; break; case 't': thresh = atof(opt.optarg); percentage_pruning = true; break; case 'o': use_time_info = false; break; case 's': use_phon_info = false; break; case 'b': constrain_intra = true; break; case 'n': constrain_inter = true; break; case 'B': basedir = opt.optarg; break; case 'x': fileext = opt.optarg; break; case 'F': output_fullpath = true; break; default: Usage(); exit(1); break; } } if (percentage_pruning && score_pruning){ cerr << "ERROR: contradictory pruning methods!" << endl; percentage_pruning = false; } Prons P(pronfile); ofstream flog; if (logfile != ""){ flog.open(logfile.c_str()); assert(flog); } if (outdir != "") mkdir(outdir.c_str(),0777); float lmscale_from_header; float prscale_from_header; float wdpenalty_from_header; float WIP = 0; float LMweight = 1; float PRweight = 1; ifstream flist(infile.c_str()); assert(flist); first = true; //we get all the info about the parameters from the first lattice string file_name, flist_item; while(getlineH(flist, flist_item)){ if (basedir != "") file_name = basedir + "/" + flist_item; else file_name = flist_item; if (fileext != "") file_name += fileext; // /////////////////////////////////////////////////////////////////////////////////////// // // // READ THE LATTICE // // // // /////////////////////////////////////////////////////////////////////////////////////// // read the lattice header for SLF lattices; count the number of links for FSM lattices LatticeInfo info(file_name, type); Lattice lat(info, P); // /////////////////////////////////////////////////////////////////////////////////////// // // // Figure out the values of different parameters by combining the information // // in the lattice header with the values of the arguments in the command line // // Output these values in a log file. // // // // /////////////////////////////////////////////////////////////////////////////////////// if (use_time_info == false) lat.set_no_time_info(); if (lat.Type() == "SLF"){ if (first){ lmscale_from_header = info.LMscale(); prscale_from_header = info.PRscale(); wdpenalty_from_header = info.Wdpenalty(); if (wdpenalty_was_set) WIP = wdpenalty; else if (wdpenalty_from_header != 0) WIP = wdpenalty_from_header; if (WIP < 0) WIP *= -1; if (lmweight_was_set) LMweight = lmweight; else if (lmscale_from_header != 0) LMweight = lmscale_from_header; // if the lm scores are already scaled, unscale them if (lmoldscale > 0) LMweight /= lmoldscale; if (prweight_was_set) PRweight = prweight; else if (prscale_from_header != 0) PRweight = prscale_from_header; // if the pron scores are already scaled, unscale them if (proldscale > 0) PRweight /= proldscale; if (logfile != ""){ flog << endl << "Formula used for computing the link probabilities is: "; flog << "1/" << scale << "*( AC + " << LMweight << "*LM + " << PRweight << "*PR" << " - " << WIP << ")" << endl; flog << "where AC, LM and PR are the unscaled acoustic, language and pronunciation model scores" << endl; if (lmoldscale > 1) flog << "LM scores found in the lattice file were already weighted by " << lmoldscale << endl; if (proldscale > 1) flog << "PM scores found in the lattice file were already weighted by " << proldscale << endl; } } // if PRweight is positive you need a pronunciation model; if the lattice doesn't contain any pronunciation scores // then put uniform pronunciation probababilities if (PRweight > 0){ unsigned has_unif_pron_prob = lat.put_uniform_pron_prob(P); if (logfile != "" && first){ flog << endl << "Pronunciation model: "; if (has_unif_pron_prob) flog << "uniform\n"; else flog << "taken from the input file\n"; flog << "Pronunciations file: " << pronfile.c_str() << endl << endl; } } // compute the link scores as a combination of LM, PR, AC and WIP lat.compute_link_scores(LMweight, PRweight, WIP, scale); } if (wdpenalty != 0 && lat.Type() == "FSM"){ if (logfile != "" && first) flog << endl << "The link scores were modified by WIP = " << wdpenalty << endl; if (scale < 0) wdpenalty *= -1; lat.add_WIP(wdpenalty); } if (prweight != 0 && lat.Type() == "FSM"){ if (logfile != "" && first) flog << endl << "The pronunciation probs were added to the link scores; PR weight = " << prweight << endl; if (scale < 0) prweight *= -1; lat.add_prons(P, prweight); } if (scale != 1 && lat.Type() == "FSM"){ lat.scale_link_scores(scale); if (logfile != "" && first) flog << endl << "The link scores are scaled by: " << scale << endl; } if (logfile != "" && first){ if (percentage_pruning) flog << "Keep " << thresh << "% links" << endl; else flog << "Threshold: " << thresh << endl; flog << endl; if (outdir != ""){ flog << "Thresholds used for pruning the bins in the confusion networks: "; flog << "lowEpsT(" << lowEpsT << "), highEpsT(" << highEpsT << "), lowWordT(" << lowWordT << "), highWordT(" << highWordT << ")\n"; } if (delweight != 1) flog << "Weight of the deletion is:" << delweight << endl; flog << endl; flog << "Using time information : " << lat.has_time_info() << endl; flog << "Using phon similarity : " << use_phon_info << endl << endl; } // compute the Forward Backward scores lat.do_ForwardBackward(); // if the lattice doesn't have time information, assign to each node a number representing the length of the // longest path from the lattice start to it if (lat.has_time_info() == false) lat.put_max_dist(P); // prune links if (percentage_pruning) lat.mark_pruned_percentage(thresh); else if (score_pruning) lat.mark_pruned_score(thresh); // /////////////////////////////////////////////////////////////////////////////////////// // // // CLUSTER INITIALIZATION // // // // /////////////////////////////////////////////////////////////////////////////////////// Clustering C(&lat, P); // /////////////////////////////////////////////////////////////////////////////////////// // // // INTRA-WORD CLUSTERING // // // // /////////////////////////////////////////////////////////////////////////////////////// assert(method_intraword == "max" || method_intraword == "avg"); unsigned max_avg = 0; if (method_intraword == "avg") max_avg = 1; C.go_cluster(P,1,max_avg,constrain_intra); if (logfile != "" && first){ flog << "Intra-word Clustering method: " << method_intraword; if (method_intraword == "max") flog << " (single link clustering method)" << endl; else if (method_intraword == "avg") flog << " (complete link clustering method)" << endl; flog << "Constrain intra-word clustering: " << constrain_intra << endl << endl; } // compute the word posteriors from link posteriors in each class C.fill_words(); // /////////////////////////////////////////////////////////////////////////////////////// // // // INTER-WORD CLUSTERING // // // // /////////////////////////////////////////////////////////////////////////////////////// assert(method_interword == "max" || method_interword == "avg"); unsigned phon = 3; if (use_phon_info) phon = 2; max_avg = 0; if (method_interword == "avg") max_avg = 1; C.go_cluster(P, phon, max_avg, constrain_inter); if (logfile != "" && first){ flog << "Inter-word Clustering method: " << method_interword; if (method_interword == "max") flog << " (single link clustering method)" << endl; else if (method_interword == "avg") flog << " (complete link clustering method)" << endl; flog << "Constrain inter-word clustering: " << constrain_inter << endl << endl; } // if you constrained the merging steps in the inter-word clustering, you have to continue // merging until you get a total order if (constrain_inter == true) C.go_cluster(P, 4, 1, false); // ////////////////////////////////////////////////////////////////////////////////////// // put the remaining probability mass on the deletion; weight it differently if necessary C.add_EPS(delweight); // sort the clusters in the total order in topological order C.TopSort(); // output the consensus hyp and the confusion networks C.print_sausages_FSMformat(outdir, outfile, flist_item, lowEpsT, highEpsT, lowWordT, highWordT, P, output_fullpath); first = false; } flist.close(); return 0; } <file_sep>/SphinxTrain/src/programs/inc_comp/accum_wt_param.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: accum_wt_param.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "accum_wt_param.h" #include <s3/s3gau_io.h> #include <s3/gauden.h> #include <s3/ckd_alloc.h> #include <s3/matrix.h> #include <s3/s3.h> #include <sys_compat/file.h> int accum_wt_param(char **accum_dir, vector_t ****out_wt_mean, vector_t ****out_wt_var, int32 *out_pass2var, float32 ****out_dnom, uint32 *out_n_mgau, uint32 *out_n_feat, uint32 *out_n_density) { uint32 i; char fn[MAXPATHLEN]; vector_t ***in_wt_mean; vector_t ***in_wt_var; float32 ***in_dnom; vector_t ***acc_mean = 0; vector_t ***acc_var = 0; float32 ***acc_dnom = 0; uint32 n_mgau = 0; uint32 t_n_mgau; uint32 n_feat = 0; uint32 t_n_feat; uint32 n_density = 0; uint32 t_n_density; const uint32 *t_veclen; const uint32 *veclen = NULL; int32 pass2var; for (i = 0; accum_dir[i] != NULL; i++) { sprintf(fn, "%s/gauden_counts", accum_dir[i]); if (access(fn, F_OK) == 0) { E_INFO("Reading gaussian density count file %s\n", fn); if (s3gaucnt_read(fn, &in_wt_mean, &in_wt_var, &pass2var, &in_dnom, &t_n_mgau, &t_n_feat, &t_n_density, &t_veclen) != S3_SUCCESS) { fflush(stdout); perror(fn); return S3_ERROR; } if (n_mgau == 0) { n_mgau = t_n_mgau; n_feat = t_n_feat; n_density = t_n_density; veclen = t_veclen; acc_mean = gauden_alloc_param(n_mgau, n_feat, n_density, veclen); acc_var = gauden_alloc_param(n_mgau, n_feat, n_density, veclen); acc_dnom = (float32 ***)ckd_calloc_3d(n_mgau, n_feat, n_density, sizeof(float32)); } else { if (n_mgau != t_n_mgau) { E_ERROR("n_mgau, %u, in %s is inconsistent w/ the rest, %u.\n", t_n_mgau, fn, n_mgau); } if (n_feat != t_n_feat) { E_ERROR("n_feat, %u, in %s is inconsistent w/ the rest, %u.\n", t_n_feat, fn, n_feat); } if (n_density != t_n_density) { E_ERROR("n_density, %u, in %s is inconsistent w/ the rest, %u.\n", t_n_density, fn, n_density); } ckd_free((void *)t_veclen); } } else { in_wt_var = in_wt_mean = NULL; in_dnom = NULL; t_veclen = NULL; } if (in_wt_mean == NULL) { E_ERROR("Could not get weighted means for accumdir %s\n", accum_dir[i]); exit(1); } if (in_wt_var == NULL) { E_ERROR("Need weighted variances in accumdir %s to increment densities\n", accum_dir[i]); exit(1); } /* accumulate the parameters read in from the count file */ gauden_accum_param(acc_mean, in_wt_mean, n_mgau, n_feat, n_density, veclen); ckd_free((void *)in_wt_mean[0][0][0]); ckd_free_3d((void ***)in_wt_mean); gauden_accum_param(acc_var, in_wt_var, n_mgau, n_feat, n_density, veclen); ckd_free((void *)in_wt_var[0][0][0]); ckd_free_3d((void ***)in_wt_var); accum_3d(acc_dnom, in_dnom, n_mgau, n_feat, n_density); ckd_free_3d((void ***)in_dnom); } /* pass outputs to the caller */ *out_wt_mean = acc_mean; *out_wt_var = acc_var; *out_dnom = acc_dnom; *out_n_mgau = n_mgau; *out_n_feat = n_feat; *out_n_density = n_density; *out_pass2var = pass2var; return S3_SUCCESS; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1996/08/06 14:07:14 eht * Deal w/ 2 pass variance computation * * Revision 1.2 1996/07/29 16:26:54 eht * development release * * Revision 1.1 1996/01/26 18:22:55 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/pgm/sen2s2/Makefile # # Makefile # # HISTORY # # 23-Jul-1999 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # VPATH = .:.. include ../../Makefile.defines TARGET = sen2s2 OBJS = sen2s2.o $(TARGET): $(OBJS) $(CC) $(CFLAGS) -o $(TARGET) $(OBJS) -lmain -lmisc -lfeat -lio -lutil -lm clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# install: $(TARGET) cp $(TARGET) $(S3BINDIR) <file_sep>/cmuclmtk/src/programs/evallm.c /* ==================================================================== * Copyright (c) 1999-2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* $Log: evallm.c,v $ Revision 1.6 2006/06/19 21:02:08 archan Changed license from the original research-only license to the BSD license. Revision 1.5 2006/04/15 20:59:59 archan Added Arthur Toth's n-gram based sentence generator to evallm. Arthur has given me a very strong precaution to use the code. So, I will also make sure the current version will only be used by a few. Revision 1.4 2006/04/13 17:36:37 archan 0, This particular change enable 32bit LM creation in ARPA format. Binary reading and writing are more complicated issues. I will try to use the next 3 days to tackle them. 1, idngram2lm has been significantly rewritten. We start to see the most important 150 lines in LM counting code. (line 676 to 833 in v1.9) */ #define MAX_ARGS 200 #include "../liblmest/evallm.h" #include "../libs/pc_general.h" #include "../libs/ac_parsetext.h" #include "../libs/general.h" #include <stdio.h> #include <string.h> #include <stdlib.h> void help_message(){ fprintf(stderr,"evallm : Evaluate a language model.\n"); fprintf(stderr,"Usage : evallm [ -binary .binlm | \n"); fprintf(stderr," -arpa .arpa [ -context .ccs ] ]\n"); } void evallm_command_help_message() { printf("The user may specify one of the following commands: \n"); printf("\n"); printf(" - perplexity\n"); printf("\n"); printf("Computes the perplexity of a given text. May optionally specify words\n"); printf("from which to force back-off.\n"); printf("\n"); printf("Syntax: \n"); printf("\n"); printf("perplexity -text .text\n"); printf(" [ -probs .fprobs ]\n"); printf(" [ -oovs .oov_file ]\n"); printf(" [ -annotate .annotation_file ] \n"); printf(" [ -backoff_from_unk_inc | -backoff_from_unk_exc ]\n"); printf(" [ -backoff_from_ccs_inc | -backoff_from_ccs_exc ] \n"); printf(" [ -backoff_from_list .fblist ]\n"); printf(" [ -include_unks ]\n"); printf("\n"); printf(" - validate\n"); printf(" \n"); printf("Calculate the sum of the probabilities of all the words in the\n"); printf("vocabulary given the context specified by the user.\n"); printf("\n"); printf("Syntax: \n"); printf("\n"); printf("validate [ -backoff_from_unk -backoff_from_ccs |\n"); printf(" -backoff_from_list .fblist ]\n"); printf(" [ -forced_backoff_inc | -forced_back_off_exc ] \n"); printf(" word1 word2 ... word_(n-1)\n"); printf("\n"); printf("Where n is the n in n-gram. \n"); printf("\n"); printf(" - generate\n"); printf(" \n"); printf("Calculate the sum of the probabilities of all the words in the\n"); printf("vocabulary given the context specified by the user.\n"); printf("\n"); printf("Syntax: \n"); printf("\n"); printf("generate -seed seed_of_random_generator -size size_of_file -text output text file \n"); printf("\n"); printf(" - help\n"); printf("\n"); printf("Displays this help message.\n"); printf("\n"); printf("Syntax: \n"); printf("\n"); printf("help\n"); printf("\n"); printf(" - quit\n"); printf("\n"); printf("Exits the program.\n"); printf("\n"); printf("Syntax: \n"); printf("\n"); printf("quit\n"); } int main (int argc, char **argv) { ng_t ng; arpa_lm_t arpa_ng; char input_string[500]; int num_of_args; char *args[MAX_ARGS]; char *lm_filename_arpa; char *lm_filename_binary; flag told_to_quit; flag inconsistant_parameters; flag backoff_from_unk_inc; flag backoff_from_unk_exc; flag backoff_from_ccs_inc; flag backoff_from_ccs_exc; flag arpa_lm; flag binary_lm; flag include_unks; char *fb_list_filename; char *probs_stream_filename; char *annotation_filename; char *text_stream_filename; char *oov_filename; char *ccs_filename; int generate_size; int random_seed; double log_base; char wlist_entry[1024]; char current_cc[200]; vocab_sz_t current_cc_id; FILE *context_cues_fp; int n; /* Process command line */ report_version(&argc,argv); if (pc_flagarg(&argc, argv,"-help") || argc == 1 || (strcmp(argv[1],"-binary") && strcmp(argv[1],"-arpa"))) { help_message(); exit(1); } lm_filename_arpa = salloc(pc_stringarg(&argc, argv,"-arpa","")); if (strcmp(lm_filename_arpa,"")) arpa_lm = 1; else arpa_lm = 0; lm_filename_binary = salloc(pc_stringarg(&argc, argv,"-binary","")); if (strcmp(lm_filename_binary,"")) binary_lm = 1; else binary_lm = 0; if (arpa_lm && binary_lm) quit(-1,"Error : Can't use both -arpa and -binary flags.\n"); if (!arpa_lm && !binary_lm) quit(-1,"Error : Must specify either a binary or an arpa format language model.\n"); ccs_filename = salloc(pc_stringarg(&argc, argv,"-context","")); if (binary_lm && strcmp(ccs_filename,"")) fprintf(stderr,"Warning - context cues file not needed with binary language model file.\nWill ignore it.\n"); pc_report_unk_args(&argc,argv,2); /* Load language model */ if (arpa_lm) { fprintf(stderr,"Reading in language model from file %s\n", lm_filename_arpa); load_arpa_lm(&arpa_ng,lm_filename_arpa); }else { fprintf(stderr,"Reading in language model from file %s\n", lm_filename_binary); load_lm(&ng,lm_filename_binary); } fprintf(stderr,"\nDone.\n"); n=arpa_lm? arpa_ng.n: ng.n; if (arpa_lm) { arpa_ng.context_cue = (flag *) rr_calloc(arpa_ng.table_sizes[0],sizeof(flag)); arpa_ng.no_of_ccs = 0; if (strcmp(ccs_filename,"")) { context_cues_fp = rr_iopen(ccs_filename); while (fgets (wlist_entry, sizeof (wlist_entry),context_cues_fp)) { if (strncmp(wlist_entry,"##",2)==0) continue; sscanf (wlist_entry, "%s ",current_cc); warn_on_wrong_vocab_comments(wlist_entry); if (sih_lookup(arpa_ng.vocab_ht,current_cc,&current_cc_id) == 0) quit(-1,"Error : %s in the context cues file does not appear in the vocabulary.\n",current_cc); arpa_ng.context_cue[(unsigned short) current_cc_id] = 1; arpa_ng.no_of_ccs++; fprintf(stderr,"Context cue word : %s id = %lld\n",current_cc,current_cc_id); } rr_iclose(context_cues_fp); } } /* Process commands */ told_to_quit = 0; num_of_args = 0; while (!feof(stdin) && !told_to_quit) { printf("evallm : \n"); fgets(input_string, sizeof(input_string), stdin); if(strlen(input_string) < sizeof(input_string)-1) input_string[strlen(input_string)-1] = '\0'; //chop new-line else quit(1, "evallm input exceeds size of input buffer"); if (!feof(stdin)) { parse_comline(input_string,&num_of_args,args); log_base = pc_doublearg(&num_of_args,args,"-log_base",10.0); backoff_from_unk_inc = pc_flagarg(&num_of_args,args,"-backoff_from_unk_inc"); backoff_from_ccs_inc = pc_flagarg(&num_of_args,args,"-backoff_from_ccs_inc"); backoff_from_unk_exc = pc_flagarg(&num_of_args,args,"-backoff_from_unk_exc"); backoff_from_ccs_exc = pc_flagarg(&num_of_args,args,"-backoff_from_ccs_exc"); include_unks = pc_flagarg(&num_of_args,args,"-include_unks"); fb_list_filename = salloc(pc_stringarg(&num_of_args,args,"-backoff_from_list","")); text_stream_filename = salloc(pc_stringarg(&num_of_args,args,"-text","")); probs_stream_filename = salloc(pc_stringarg(&num_of_args,args,"-probs","")); annotation_filename = salloc(pc_stringarg(&num_of_args,args,"-annotate","")); oov_filename = salloc(pc_stringarg(&num_of_args,args,"-oovs","")); generate_size = pc_intarg(&num_of_args,args,"-size",10000); random_seed = pc_intarg(&num_of_args,args,"-seed",-1); inconsistant_parameters = 0; if (backoff_from_unk_inc && backoff_from_unk_exc) { fprintf(stderr,"Error : Cannot specify both exclusive and inclusive forced backoff.\n"); fprintf(stderr,"Use only one of -backoff_from_unk_exc and -backoff_from_unk_inc\n"); inconsistant_parameters = 1; } if (backoff_from_ccs_inc && backoff_from_ccs_exc) { fprintf(stderr,"Error : Cannot specify both exclusive and inclusive forced backoff.\n"); fprintf(stderr,"Use only one of -backoff_from_ccs_exc and -backoff_from_ccs_inc\n"); inconsistant_parameters = 1; } if (num_of_args > 0) { if (!inconsistant_parameters) { if (!strcmp(args[0],"perplexity")) { compute_perplexity(&ng, &arpa_ng, text_stream_filename, probs_stream_filename, annotation_filename, oov_filename, fb_list_filename, backoff_from_unk_inc, backoff_from_unk_exc, backoff_from_ccs_inc, backoff_from_ccs_exc, arpa_lm, include_unks, log_base); }else /* do perplexity sentence by sentence [20090612] (air) */ if (!strcmp(args[0],"uttperp")) { FILE *uttfh,*tempfh; char utt[4096]; /* live dangerously... */ char tmpfil[128]; if ((uttfh = fopen(text_stream_filename,"r")) == NULL) { printf("Error: can't open %s\n",text_stream_filename); exit(1); } strcpy(tmpfil,tempnam(NULL,"uttperp_")); while ( ! feof(uttfh) ) { fscanf(uttfh,"%[^\n]\n",utt); tempfh = fopen(tmpfil,"w"); fprintf(tempfh,"%s\n",utt); fclose(tempfh); compute_perplexity(&ng, &arpa_ng, tmpfil, /* text_stream_filename, */ probs_stream_filename, annotation_filename, oov_filename, fb_list_filename, backoff_from_unk_inc, backoff_from_unk_exc, backoff_from_ccs_inc, backoff_from_ccs_exc, arpa_lm, include_unks, log_base); } fclose(uttfh); // unlink(tmpfil); }else if(!strcmp(args[0],"validate")){ if (num_of_args != n) fprintf(stderr,"Error : must specify %d words of context.\n",n-1); else { /* Assume last n-1 parameters form context */ validate(&ng, &arpa_ng, &(args[num_of_args-n+1]), backoff_from_unk_inc, backoff_from_unk_exc, backoff_from_ccs_inc, backoff_from_ccs_exc, arpa_lm, fb_list_filename); } }else if (!strcmp(args[0],"stats")){ if (arpa_lm) display_arpa_stats(&arpa_ng); else display_stats(&ng); }else if (!strcmp(args[0],"generate")) { if(arpa_lm) generate_words(NULL,&arpa_ng,generate_size,random_seed,text_stream_filename); else generate_words(&ng,NULL,generate_size,random_seed,text_stream_filename); }else if (!strcmp(args[0],"quit")) told_to_quit=1; else if (!strcmp(args[0],"help")) evallm_command_help_message(); else fprintf(stderr,"Unknown command : %s\nType \'help\'\n", args[0]); } } } } fprintf(stderr,"evallm : Done.\n"); exit(0); } <file_sep>/tools/dictator/build/build.xml <?xml version="1.0" encoding="UTF-8"?> <project basedir="." default="all" name="Dictator"> <!-- Load the environment --> <property environment="env"/> <condition property="javadoc_level" value="${access}"> <isset property="access"/> </condition> <condition property="javadoc_level" value="public"> <not> <isset property="access"/> </not> </condition> <!-- ********************************************************** --> <!-- * * --> <!-- * Where to find things... * --> <!-- * * --> <!-- ********************************************************** --> <property name="version" value="0.1"/> <path id="libs"> <fileset dir="../../common/lib" includes="**/sphinx4.jar,**/batch.jar,**/javolution.jar,**/forms_rt.jar"/> <fileset file="${env.JAVA_HOME}/jre/lib/javaws.jar"/> </path> <property name="src_dir" value="../src/java/"/> <property name="alt_src_dir" value="../../common/src/java/"/> <property name="src_path" value="${src_dir};${alt_src_dir}"/> <property name="build_dir" value="."/> <property name="classes_dir" value="${build_dir}/classes"/> <property name="data_dir" value="../../common/data"/> <property name="lib_dir" value="."/> <property name="javadoc_dir" value="javadoc"/> <property name="javadoc_check_dir" value="${build_dir}/javadoc_check"/> <property name="javadoc_zip" value="javadoc.zip"/> <!-- ********************************************************** --> <!-- * * --> <!-- * Determine which sources should be compiled depending * --> <!-- * on the availability of lib/jsapi.jar. This creates a * --> <!-- * property called "patternset_to_compile" and sets its * --> <!-- * val to either "all_files" or "no_jsapi", which refers * --> <!-- * to the name of a patternset. The value of * --> <!-- * srcs_to_compile will be used in the javac target as a * --> <!-- * patternset refid. * --> <!-- * * --> <!-- ********************************************************** --> <patternset id="all_files" includes="edu/**,com/**" /> <patternset id="edu" includes="edu/**" excludes="com/**" /> <target name="set_patternset_to_compile"> <property name="patternset_to_compile" value="all_files"/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Determine which sources should be documented using * --> <!-- * javadoc depending on the availability of * --> <!-- * lib/jsapi.jar. This creates a property called * --> <!-- * "patternset_to_doc" and sets its val to either * --> <!-- * "all" or "no_jsapi", which refers to the name of a * --> <!-- * patternset. * --> <!-- * * --> <!-- ********************************************************** --> <target name="set_patternset_to_doc"> <property name="patternset_to_doc" value="edu"/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Builds srcs, jars, demos * --> <!-- * * --> <!-- ********************************************************** --> <target name="all" description="Build everything"> <antcall target="compile_src"/> <antcall target="jars"/> <echo message="Build complete."/> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Builds just the srcs. * --> <!-- * * --> <!-- ********************************************************** --> <target name="compile_src" depends="set_patternset_to_compile" description="Build just the 1.5 srcs"> <mkdir dir="${classes_dir}"/> <javac debug="true" source="1.5" sourcepath="${src_path}" srcdir="${src_dir};${alt_src_dir}" deprecation="true" destdir="${classes_dir}"> <patternset refid="${patternset_to_compile}"/> <classpath refid="libs"/> </javac> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Generates the jar files * --> <!-- * * --> <!-- ********************************************************** --> <target name="jars" depends="dictator_jar" description="Builds all the jar files"/> <!-- dictator.jar --> <property name="dictator_jar" value="${lib_dir}/dictator.jar"/> <target name="dictator_jar" depends="compile_src" description="Create ${lib_dir}/dictator.jar"> <mkdir dir="${lib_dir}"/> <copy file="${build_dir}/dictator.config.xml" tofile="${classes_dir}/dictator.config.xml"/> <copy file="${data_dir}/wsj5k.DMP" tofile="${classes_dir}/wsj5k.DMP"/> <jar destfile="${dictator_jar}" manifest="MANIFEST.MF" compress="true" includes="**" index="true" basedir="${classes_dir}"> <zipfileset src="../../common/lib/sphinx4.jar"/> <zipfileset src="../../common/lib/batch.jar"/> <zipfileset src="../../common/lib/forms_rt.jar"/> <zipfileset src="${data_dir}/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar"/> </jar> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Generates the javadoc * --> <!-- * * --> <!-- ********************************************************** --> <property name="javadoc_desc" value="Dictator"/> <target name="javadoc" depends="set_patternset_to_doc" description="Generate javadoc, optionally with '-Daccess=private'"> <delete dir="${javadoc_dir}"/> <mkdir dir="${javadoc_dir}"/> <javadoc sourcepath="${src_path}" source="1.5" additionalparam="-breakiterator" destdir="${javadoc_dir}" overview="${build_dir}/overview.html" windowtitle="${javadoc_desc}" doctitle="${javadoc_desc}" access="${javadoc_level}"> <link href="http://java.sun.com/products/java-media/speech/forDevelopers/jsapi-doc" offline="true" packagelistLoc="lib/jsapi" /> <packageset dir="${src_dir}" defaultexcludes="yes"> <patternset refid="${patternset_to_doc}"/> </packageset> <packageset dir="${alt_src_dir}" defaultexcludes="yes"> <patternset refid="${patternset_to_doc}"/> </packageset> <classpath refid="libs"/> </javadoc> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Checks javadocs * --> <!-- * * --> <!-- ********************************************************** --> <target name="javadoc_check" depends="set_patternset_to_doc" description="checks the javadocs"> <mkdir dir="${javadoc_check_dir}"/> <javadoc sourcepath="${src_path}" additionalparam="-source 1.5" packagenames="edu.*" destdir="${javadoc_check_dir}" overview="${build_dir}/overview.html" doclet="com.sun.tools.doclets.doccheck.DocCheck" docletpath="/lab/speech/java/doccheck1.2b2/doccheck.jar" access="${javadoc_level}"> <classpath refid="libs"/> </javadoc> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Run the dictator * --> <!-- * * --> <!-- ********************************************************** --> <target name="run" description="Run the dictator" depends="all"> <java fork="yes" jar="${dictator_jar}"> <jvmarg value="-Xmx256m"/> </java> </target> <!-- ********************************************************** --> <!-- * * --> <!-- * Deletes all build output and *~ file droppings * --> <!-- * * --> <!-- ********************************************************** --> <target name="clean" description="Delete all build output"> <delete> <fileset defaultexcludes="no" dir="." includes="**/*~"/> <fileset defaultexcludes="no" dir="${src_dir}" includes="**/*~"/> <fileset defaultexcludes="no" dir="${alt_src_dir}" includes="**/*~"/> </delete> <delete dir="${classes_dir}"/> <delete dir="${javadoc_dir}"/> </target> </project> <file_sep>/pocketsphinx/src/libpocketsphinx/glextree.c /* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file glextree.c * @brief Generic lexicon trees for token-fsg search (and maybe elsewhere) * @author <NAME> <<EMAIL>> */ #include "glextree.h" glexroot_t * glexroot_add_child(glextree_t *tree, glexroot_t *root, int32 phone) { glexroot_t *newroot; newroot = listelem_malloc(tree->root_alloc); newroot->phone = phone; newroot->n_down = 0; newroot->down.kids = NULL; newroot->sibs = root->down.kids; root->down.kids = newroot; ++root->n_down; ++tree->nlexroot; return newroot; } glexroot_t * glexroot_find_child(glexroot_t *root, int32 phone) { glexroot_t *start = root->down.kids; while (start) { if (start->phone == phone) return start; start = start->sibs; } return NULL; } glexroot_t * glextree_find_roots(glextree_t *tree, int lc, int ci) { glexroot_t *lcroot; if ((lcroot = glexroot_find_child(&tree->root, lc)) == NULL) return NULL; return glexroot_find_child(lcroot, ci); } static glexnode_t * glextree_add_node(glextree_t *tree, int pid, int nhmm) { glexnode_t *node = listelem_malloc(tree->node_alloc); node->hmms = ckd_calloc(nhmm, sizeof(*node->hmms)); node->down.kids = NULL; node->wid = -1; tree->nlexhmm += nhmm; ++tree->nlexnode; return node; } static void glextree_add_single_phone_word(glextree_t *tree, glexroot_t *ciroot, int lc, int32 w) { int ci, rc; ci = dict_first_phone(tree->dict, w); for (rc = 0; rc < bin_mdef_n_ciphone(tree->d2p->mdef); ++rc) { s3ssid_t ssid = dict2pid_lrdiph_rc(tree->d2p, ci, lc, rc); glexroot_t *rcroot; glexnode_t *node; glexlink_t *link; if (ssid == BAD_S3SSID) continue; /* Find or create the root node for this triphone. */ if ((rcroot = glexroot_find_child(ciroot, rc)) == NULL) rcroot = glexroot_add_child(tree, ciroot, rc); /* Create a root-leaf node (FIXME: this is kind of inefficient * to have one for each right context - would be better to * allocate a single one under ciroot somehow). */ node = glextree_add_node(tree, ci, 1); hmm_init(tree->ctx, node->hmms, FALSE, ssid, ci); node->wid = w; node->down.n_leaves = 1; /* Link it in. */ link = listelem_malloc(tree->link_alloc); link->dest = node; link->next = rcroot->down.nodes; rcroot->down.nodes = link; } } static glexnode_t * internal_node(glextree_t *tree, glexlink_t **cur, s3ssid_t ssid, int ci) { glexlink_t *link; /* Look for a node with the same ssid which is not a leaf node. */ /* E_INFO("Looking for ssid %d in link %p -> %p\n", ssid, cur, *cur); */ for (link = *cur; link; link = link->next) if (hmm_nonmpx_ssid(link->dest->hmms) == ssid && link->dest->wid == -1) break; /* Create it if not... */ if (link == NULL) { glexnode_t *node; node = glextree_add_node(tree, ci, 1); hmm_init(tree->ctx, node->hmms, FALSE, ssid, ci); link = listelem_malloc(tree->link_alloc); link->dest = node; link->next = *cur; /* E_INFO("Created link %p/%p\n", node, *cur); */ *cur = link; } return link->dest; } /** * Find a first non-root (i.e. second phone) node corresponding to ssid. */ static glexnode_t * find_first_internal_node(glextree_t *tree, s3ssid_t ssid) { void *val; if (hash_table_lookup_bkey(tree->internal, (char const *)&ssid, sizeof(ssid), &val) < 0) return NULL; return (glexnode_t *)val; } static void build_subtree_over_2phones(glextree_t *tree, glexlink_t **cur, int32 w) { glexnode_t *node; glexlink_t *link; xwdssid_t *rssid; s3ssid_t ssid; int pos = 1; ssid = dict2pid_internal(tree->d2p, w, 1); /* Try to find an existing first internal node. */ if ((node = find_first_internal_node(tree, ssid)) != NULL) { /* E_INFO("Found internal node %p for ssid %d\n", node, ssid); */ /* Link it into cur, which is the root node's successors (fan-in). */ link = listelem_malloc(tree->link_alloc); link->dest = node; link->next = *cur; *cur = link; /* Now move down a level. */ cur = &node->down.kids; } else { /* Create a new node under cur and move down a level. */ node = internal_node(tree, cur, ssid, dict_pron(tree->dict, w, pos)); /* E_INFO("Created internal node %p for ssid %d\n", node, ssid); */ cur = &node->down.kids; /* Enter node in the internal hash table. NOTE: * SphinxBase hash tables are a real pain and require * their keys to be externally allocated, so we * pre-allocate all ssids in a big array and index into * that. */ hash_table_enter_bkey(tree->internal, (char const *)(tree->ssidbuf + ssid), sizeof(ssid), node); } ++pos; /* Now walk down to the penultimate phone, building new nodes as * necessary. */ while (pos < dict_pronlen(tree->dict, w) - 1) { ssid = dict2pid_internal(tree->d2p, w, pos); node = internal_node(tree, cur, ssid, dict_pron(tree->dict, w, pos)); cur = &node->down.kids; ++pos; } /* Now node is the penultimate phone and cur points to its * children. There is probably an existing leaf node. */ rssid = dict2pid_rssid(tree->d2p, dict_last_phone(tree->dict, w), dict_second_last_phone(tree->dict, w)); for (link = *cur; link; link = link->next) if (link->dest->wid == w) break; if (link == NULL) { int rc; E_INFO("Allocating leaf node for %s - %d HMMs\n", dict_wordstr(tree->dict, w), rssid->n_ssid); node = glextree_add_node(tree, dict_last_phone(tree->dict, w), rssid->n_ssid); for (rc = 0; rc < rssid->n_ssid; ++rc) { hmm_init(tree->ctx, node->hmms + rc, FALSE, rssid->ssid[rc], dict_last_phone(tree->dict, w)); } node->wid = w; node->down.n_leaves = rssid->n_ssid; link = listelem_malloc(tree->link_alloc); link->dest = node; link->next = *cur; *cur = link; } } static void build_subtree_2phones(glextree_t *tree, glexlink_t **cur, int32 w) { xwdssid_t *rssid; glexnode_t *node; glexlink_t *link; void *val; int rc; /* Every two-phone word gets a unique leaf node, for obvious reasons. However, at least for triphones, there should be only one of them. So look it up. */ if (hash_table_lookup_bkey(tree->internal_leaf, (char const *)&w, sizeof(w), &val) == 0) { /* Found one, link it into the root node (fan-in) */ link = listelem_malloc(tree->link_alloc); link->dest = val; link->next = *cur; *cur = link; /* Nothing else to do. */ /* E_INFO("Reusing leaf node for %s\n", dict_wordstr(tree->dict, w)); */ return; } /* Create a new one. */ rssid = dict2pid_rssid(tree->d2p, dict_last_phone(tree->dict, w), dict_second_last_phone(tree->dict, w)); E_INFO("Allocating leaf node for %s - %d HMMs\n", dict_wordstr(tree->dict, w), rssid->n_ssid); node = glextree_add_node(tree, dict_last_phone(tree->dict, w), rssid->n_ssid); /* Enter it into the hash table and associated list. */ tree->internal_leaf_wids = glist_add_int32(tree->internal_leaf_wids, w); hash_table_enter_bkey(tree->internal_leaf, (char const *)&gnode_int32(tree->internal_leaf_wids), sizeof(int32), node); for (rc = 0; rc < rssid->n_ssid; ++rc) { hmm_init(tree->ctx, node->hmms + rc, FALSE, rssid->ssid[rc], dict_last_phone(tree->dict, w)); } node->wid = w; node->down.n_leaves = rssid->n_ssid; link = listelem_malloc(tree->link_alloc); link->dest = node; link->next = *cur; *cur = link; } static void glextree_add_multi_phone_word(glextree_t *tree, glexroot_t *ciroot, int lc, int32 w) { glexroot_t *rcroot; glexnode_t *node; s3ssid_t ssid; int rc; /* Find leaf corresponding to root node. */ rc = dict_second_phone(tree->dict, w); if ((rcroot = glexroot_find_child(ciroot, rc)) == NULL) rcroot = glexroot_add_child(tree, ciroot, rc); /* Find or create a root node for the initial triphone. */ ssid = dict2pid_ldiph_lc(tree->d2p, ciroot->phone, rc, lc); assert(ssid != BAD_S3SSID); /* Should never happen (which is a problem). */ /* This is the first phone's node. It may have siblings which are * single-phone words (but should have none for multi-phones). */ node = internal_node(tree, &rcroot->down.nodes, ssid, ciroot->phone); /* For triphones we just need to treat 2-phone words separately. */ if (dict_pronlen(tree->dict, w) == 2) build_subtree_2phones(tree, &node->down.kids, w); else build_subtree_over_2phones(tree, &node->down.kids, w); } void glextree_add_word(glextree_t *tree, int32 w) { glexroot_t *lcroot; /* Find or create root nodes for this word for all left contexts. */ for (lcroot = tree->root.down.kids; lcroot; lcroot = lcroot->sibs) { glexroot_t *ciroot; /* Is this a possible lc-ci combination? FIXME: Actually * there's no way to find out! */ if ((ciroot = glexroot_find_child (lcroot, dict_first_phone(tree->dict, w))) == NULL) { ciroot = glexroot_add_child(tree, lcroot, dict_first_phone(tree->dict, w)); } /* If it is a single phone word, then create root-leaf nodes * for every possible right context. */ if (dict_pronlen(tree->dict, w) == 1) { glextree_add_single_phone_word(tree, ciroot, lcroot->phone, w); } /* Otherwise, find or create a root node and add it to the tree. */ else { glextree_add_multi_phone_word(tree, ciroot, lcroot->phone, w); } } E_INFO("Added %s - %d lex roots, %d nodes, %d hmms\n", dict_wordstr(tree->dict, w), tree->nlexroot, tree->nlexnode, tree->nlexhmm); } glextree_t * glextree_build(hmm_context_t *ctx, dict_t *dict, dict2pid_t *d2p, glextree_wfilter_t filter, void *udata) { glextree_t *tree; glexroot_t *lcroot; int32 w, p; tree = ckd_calloc(1, sizeof(*tree)); tree->refcount = 1; tree->ctx = ctx; tree->dict = dict_retain(dict); tree->d2p = dict2pid_retain(d2p); tree->root_alloc = listelem_alloc_init(sizeof(glexroot_t)); tree->node_alloc = listelem_alloc_init(sizeof(glexnode_t)); tree->link_alloc = listelem_alloc_init(sizeof(glexlink_t)); tree->internal = hash_table_new(bin_mdef_n_sseq(d2p->mdef), HASH_CASE_YES); tree->internal_leaf = hash_table_new(dict_size(tree->dict) / 10, HASH_CASE_YES); /* Externally allocate ssid keys for the above hashtable. */ tree->ssidbuf = ckd_calloc(sizeof(s3ssid_t), bin_mdef_n_sseq(d2p->mdef)); for (p = 0; p < bin_mdef_n_sseq(d2p->mdef); ++p) tree->ssidbuf[p] = p; E_INFO("Building lexicon tree:\n"); /* First, build a root node for every possible left-context phone. * These can't be easily added at runtime, and it doesn't cost * very much to cover them all just in case (FIXME: actually it * might but we will worry about that later...) */ for (p = 0; p < bin_mdef_n_ciphone(d2p->mdef); ++p) { glexroot_add_child(tree, &tree->root, p); } E_INFO("\t%d left context roots\n", bin_mdef_n_ciphone(d2p->mdef)); /* Now build a tree of first and second phones under the newly allocated roots. */ for (w = 0; w < dict_size(dict); ++w) { if (filter && !(*filter)(tree, w, udata)) continue; glextree_add_word(tree, w); } /* Dump some tree statistics. */ for (lcroot = tree->root.down.kids; lcroot; lcroot = lcroot->sibs) { glexroot_t *ciroot; int n_ci = 0, n_rc = 0; for (ciroot = lcroot->down.kids; ciroot; ciroot = ciroot->sibs) { glexroot_t *rcroot; ++n_ci; for (rcroot = ciroot->down.kids; rcroot; rcroot = rcroot->sibs) { ++n_rc; } } E_INFO(" %s has %d ci roots, %d rc roots\n", bin_mdef_ciphone_str(d2p->mdef, lcroot->phone), n_ci, n_rc); } E_INFO("Tree has %d lex roots (%d KiB)\n", tree->nlexroot, tree->nlexroot * sizeof(glexroot_t) / 1024); E_INFO(" %d nodes (%d KiB), %d HMMs (%d KiB)\n", tree->nlexnode, tree->nlexnode * sizeof(glexnode_t) / 1024, tree->nlexhmm, tree->nlexhmm * sizeof(hmm_t) / 1024); return tree; } int glextree_has_word(glextree_t *tree, int32 wid) { glexroot_t *ciroot; glexroot_t *rcroot; /* Take advantage of the fact that we expand all left contexts. */ if ((ciroot = glextree_find_roots(tree, 0, dict_first_phone(tree->dict, wid))) == NULL) return FALSE; if (dict_pronlen(tree->dict, wid) == 1) { glexlink_t *link; /* Take advantage of the fact that we expand all right * contexts for single-phone words. */ rcroot = ciroot->down.kids; for (link = rcroot->down.nodes; link; link = link->next) if (link->dest->wid == wid) return TRUE; return FALSE; } else { glexnode_t *node; glexlink_t *link; int pos; /* Find the lextree root. */ if ((rcroot = glexroot_find_child (ciroot,dict_second_phone(tree->dict, wid))) == NULL) return FALSE; /* There will be only one node that isn't a single-phone word, * so take it. */ for (link = rcroot->down.nodes; link; link = link->next) if (link->dest->wid == -1) break; if (link == NULL) return FALSE; /* Now do second through penultimate phones. */ node = link->dest; for (pos = 1; pos < dict_pronlen(tree->dict, wid) - 1; ++pos) { for (link = node->down.kids; link; link = link->next) { if (hmm_nonmpx_ssid(link->dest->hmms) == dict2pid_internal(tree->d2p, wid, pos) && link->dest->wid == -1) break; } if (link == NULL) return FALSE; node = link->dest; } /* Leaf node will have wid attached to it. */ for (link = node->down.kids; link; link = link->next) if (link->dest->wid == wid) return TRUE; return FALSE; } } glextree_t * glextree_retain(glextree_t *tree) { if (tree == NULL) return NULL; ++tree->refcount; return tree; } int glextree_free(glextree_t *tree) { if (tree == NULL) return 0; if (--tree->refcount > 0) return tree->refcount; listelem_alloc_free(tree->root_alloc); listelem_alloc_free(tree->node_alloc); listelem_alloc_free(tree->link_alloc); ckd_free(tree->ssidbuf); hash_table_free(tree->internal); hash_table_free(tree->internal_leaf); glist_free(tree->internal_leaf_wids); ckd_free(tree->d2p); ckd_free(tree->dict); ckd_free(tree); return 0; } static void glexnode_clear(glexnode_t *node) { if (node->wid != -1) { long i; for (i = 0; i < node->down.n_leaves; ++i) hmm_clear(node->hmms + i); } else hmm_clear(node->hmms); } static void glexnode_clear_subtree(glexnode_t *node) { glexlink_t *link; glexnode_clear(node); if (node->wid != -1) /* leaf node. */ return; for (link = node->down.kids; link; link = link->next) glexnode_clear_subtree(link->dest); } int glextree_clear(glextree_t *tree) { glexroot_t *lcroot, *ciroot, *rcroot; hash_iter_t *itor; /* Reset all root nodes (probably we want to keep them in a list * to make this easier, or make this unnecessary in some way) */ for (lcroot = tree->root.down.kids; lcroot; lcroot = lcroot->sibs) { for (ciroot = lcroot->down.kids; ciroot; ciroot = ciroot->sibs) { for (rcroot = ciroot->down.kids; rcroot; rcroot = rcroot->sibs) { glexlink_t *ptr; for (ptr = rcroot->down.nodes; ptr; ptr = ptr->next) { glexnode_clear(ptr->dest); } } } } /* Reset internal leaf nodes. */ for (itor = hash_table_iter(tree->internal_leaf); itor; itor = hash_table_iter_next(itor)) { glexnode_clear((glexnode_t *)hash_entry_val(itor->ent)); } /* Reset subtrees rooted at each first internal node. */ for (itor = hash_table_iter(tree->internal); itor; itor = hash_table_iter_next(itor)) { glexnode_clear_subtree((glexnode_t *)hash_entry_val(itor->ent)); } return 0; } <file_sep>/archive_s3/s3.0/pgm/treedec/main.c /* * main.c -- Main tree decoder driver module. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 02-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include <libmain/cmn.h> #include <libmain/agc.h> #include <libmain/hyp.h> #include "kb.h" #include "lextree.h" static arg_t arglist[] = { { "-logbase", ARG_FLOAT32, "1.0001", "Base in which all log values calculated" }, { "-feat", ARG_STRING, "s3_1x39", "Feature type: s3_1x39 / s2_4x / cep_dcep[,%d] / cep[,%d] / %d,%d,...,%d" }, { "-mdef", REQARG_STRING, NULL, "Model definition input file" }, { "-dict", REQARG_STRING, NULL, "Pronunciation dictionary input file" }, { "-fdict", REQARG_STRING, NULL, "Filler word pronunciation dictionary input file" }, { "-compsep", ARG_STRING, "", /* Default: No compound word (NULL separator char) */ "Separator character between components of a compound word (NULL if none)" }, { "-lm", REQARG_STRING, NULL, "Word trigram language model input file" }, { "-fillpen", ARG_STRING, NULL, "Filler word probabilities input file" }, { "-silprob", ARG_FLOAT32, "0.1", "Default silence word probability" }, { "-fillprob", ARG_FLOAT32, "0.02", "Default non-silence filler word probability" }, { "-lw", ARG_FLOAT32, "9.5", "Language weight" }, { "-wip", ARG_FLOAT32, "0.2", "Word insertion penalty" }, { "-mean", REQARG_STRING, NULL, "Mixture gaussian means input file" }, { "-var", REQARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to -var file)" }, { "-senmgau", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, { "-mixw", REQARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to -mixw file)" }, { "-mgaubeam", ARG_FLOAT32, "1e-3", "Beam selecting best components within each mixture Gaussian [0(widest)..1(narrowest)]" }, { "-tmat", REQARG_STRING, NULL, "HMM state transition matrix input file" }, { "-tmatfloor", ARG_FLOAT32, "0.0001", "HMM state transition probability floor (applied to -tmat file)" }, { "-ctl", REQARG_STRING, NULL, "Control file listing utterances to be processed" }, { "-ctloffset", ARG_INT32, "0", "No. of utterances at the beginning of -ctlfn file to be skipped" }, { "-ctlcount", ARG_INT32, "1000000000", /* A big number to approximate the default: "until EOF" */ "No. of utterances to be processed (after -ctloffset)" }, { "-cepdir", ARG_STRING, ".", "Directory of mfc files (for utterances in -ctl file)" }, { "-cepext", ARG_STRING, "mfc", "File extension to be appended to utterances listed in -ctlfn file" }, { "-agc", ARG_STRING, "max", "Automatic Gain Control. max: C0 -= max(C0) in current utt; none: no AGC" }, { "-cmn", ARG_STRING, "current", "Cepstral Mean Normalization. current: C[1..n-1] -= mean(C[1..n-1]) in current utt; none: no CMN" }, { "-beam", ARG_FLOAT64, "1e-70", "Main pruning beam" }, { "-wordbeam", ARG_FLOAT64, "1e-30", "Default cross-word pruning beam" }, { "-wordmax", ARG_INT32, "1000", "Max word exit candidates to expand (limits whatever passes wordbeam)" }, { "-flatdepth", ARG_INT32, "100000000", "Tree depth at which it is flattened" }, { NULL, ARG_INT32, NULL, NULL } }; static void decode_utt (void *data, char *uttfile, int32 sf, int32 ef, char *uttid) { kb_t *kb; acoustic_t *am; int32 featwin, nfr, min_utt_frames, n_vithist; char cepfile[4096], latfile[4096]; vithist_t *finalhist; int32 i, f; glist_t hyplist; FILE *latfp; printf ("\n"); fflush (stdout); E_INFO("Utterance %s\n", uttid); kb = (kb_t *)data; am = kb->am; featwin = feat_window_size(am->fcb); /* Build complete cepfile name and read cepstrum data; check for min length */ ctl_infile (cepfile, cmd_ln_str("-cepdir"), cmd_ln_str("-cepext"), uttfile); if ((nfr = s2mfc_read (cepfile, sf, ef, featwin, am->mfc, S3_MAX_FRAMES)) < 0) { E_ERROR("%s: MFC read failed\n", uttid); return; } E_INFO("%s: %d frames\n", uttid, nfr-(featwin<<1)); ptmr_reset (kb->tm); ptmr_reset (kb->tm_search); ptmr_start (kb->tm); min_utt_frames = (featwin<<1) + 1; if (nfr < min_utt_frames) { E_ERROR("%s: Utterance shorter than %d frames; ignored\n", uttid, min_utt_frames, nfr); return; } /* CMN/AGC */ if (strcmp (cmd_ln_str("-cmn"), "current") == 0) cmn (am->mfc, nfr, feat_cepsize(am->fcb)); if (strcmp (cmd_ln_str("-agc"), "max") == 0) agc_max (am->mfc, nfr); /* Process utterance */ lextree_vit_start (kb, uttid); for (i = featwin, f = 0; i < nfr-featwin; i++, f++) { am->senscale[f] = acoustic_eval (am, i); ptmr_start (kb->tm_search); lextree_vit_frame (kb, f, uttid); printf (" %d,%d,%d", f, glist_count (kb->vithist[f]), glist_count (kb->lextree_active)); fflush (stdout); ptmr_stop (kb->tm_search); } printf ("\n"); finalhist = lextree_vit_end (kb, f, uttid); hyplist = vithist_backtrace (finalhist, kb->am->senscale); hyp_log (stdout, hyplist, _dict_wordstr, (void *)kb->dict); hyp_myfree (hyplist); printf ("\n"); /* Log the entire Viterbi word lattice */ sprintf (latfile, "%s.lat", uttid); if ((latfp = fopen(latfile, "w")) == NULL) { E_ERROR("fopen(%s,w) failed; using stdout\n", latfile); latfp = stdout; } n_vithist = vithist_log (latfp, kb->vithist, f, _dict_wordstr, (void *)kb->dict); if (latfp != stdout) fclose (latfp); else { printf ("\n"); fflush (stdout); } ptmr_stop (kb->tm); if (f > 0) { printf("TMR(%s): %5d frames; %.1fs CPU, %.2f xRT; %.1fs CPU(search), %.2f xRT; %.1fs Elapsed, %.2f xRT\n", uttid, f, kb->tm->t_cpu, kb->tm->t_cpu * 100.0 / f, kb->tm_search->t_cpu, kb->tm_search->t_cpu * 100.0 / f, kb->tm->t_elapsed, kb->tm->t_elapsed * 100.0 / f); printf("CTR(%s): %5d frames; %d Sen (%.1f/fr); %d HMM (%.1f/fr); %d Words (%.1f/fr)\n", uttid, f, kb->n_sen_eval, ((float64)kb->n_sen_eval) / f, kb->n_hmm_eval, ((float64)kb->n_hmm_eval) / f, n_vithist, ((float64) n_vithist) / f); } /* Cleanup */ glist_free (kb->lextree_active); kb->lextree_active = NULL; for (; f >= -1; --f) { /* I.e., including dummy START_WORD node at frame -1 */ glist_myfree (kb->vithist[f], sizeof(vithist_t)); kb->vithist[f] = NULL; } lm_cache_reset (kb->lm); } main (int32 argc, char *argv[]) { kb_t kb; kbcore_t *kbcore; bitvec_t active; int32 w; cmd_ln_parse (arglist, argc, argv); unlimit(); kbcore = kbcore_init (cmd_ln_float32("-logbase"), cmd_ln_str("-feat"), cmd_ln_str("-mdef"), cmd_ln_str("-dict"), cmd_ln_str("-fdict"), cmd_ln_str("-compsep"), cmd_ln_str("-lm"), cmd_ln_str("-fillpen"), cmd_ln_float32("-silprob"), cmd_ln_float32("-fillprob"), cmd_ln_float32("-lw"), cmd_ln_float32("-wip"), cmd_ln_str("-mean"), cmd_ln_str("-var"), cmd_ln_float32("-varfloor"), cmd_ln_str("-senmgau"), cmd_ln_str("-mixw"), cmd_ln_float32("-mixwfloor"), cmd_ln_str("-tmat"), cmd_ln_float32("-tmatfloor")); /* Here's the perfect candidate for inheritance */ kb.mdef = kbcore->mdef; kb.dict = kbcore->dict; kb.lm = kbcore->lm; kb.fillpen = kbcore->fillpen; kb.tmat = kbcore->tmat; kb.dict2lmwid = kbcore->dict2lmwid; if ((kb.am = acoustic_init (kbcore->fcb, kbcore->gau, kbcore->sen, cmd_ln_float32("-mgaubeam"), S3_MAX_FRAMES)) == NULL) { E_FATAL("Acoustic models initialization failed\n"); } kb.beam = logs3 (cmd_ln_float64("-beam")); kb.wordbeam = logs3 (cmd_ln_float64("-wordbeam")); kb.wordmax = cmd_ln_int32("-wordmax"); /* Mark the active words and build lextree */ active = bitvec_alloc (dict_size (kb.dict)); bitvec_clear_all (active, dict_size(kb.dict)); for (w = 0; w < dict_size(kb.dict); w++) { if (IS_LMWID(kb.dict2lmwid[w]) || dict_filler_word (kb.dict, w)) bitvec_set (active, w); } kb.lextree_root = lextree_build (kb.dict, kb.mdef, active, cmd_ln_int32("-flatdepth")); kb.vithist = (glist_t *) ckd_calloc (S3_MAX_FRAMES+2, sizeof(glist_t)); kb.vithist++; /* Allow for dummy frame -1 for start word */ kb.lextree_active = NULL; kb.wd_last_sf = (int32 *) ckd_calloc (dict_size(kb.dict), sizeof(int32)); kb.tm = (ptmr_t *) ckd_calloc (1, sizeof(ptmr_t)); kb.tm_search = (ptmr_t *) ckd_calloc (1, sizeof(ptmr_t)); ctl_process (cmd_ln_str("-ctl"), cmd_ln_int32("-ctloffset"), cmd_ln_int32("-ctlcount"), decode_utt, &kb); exit(0); } <file_sep>/archive_s3/s3/src/misc/line2wid.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * line2wid.c -- Convert a ref or hyp line (word string sequence) to an array of * word ids. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 27-Feb-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <main/dict.h> int32 is_uttid (char *word, char *uttid) { int32 k; k = strlen(word); if ((word[0] == '(') && (word[k-1] == ')')) { word[k-1] = '\0'; strcpy (uttid, word+1); word[k-1] = ')'; return 1; } return 0; } int32 line2wid (dict_t *dict, char *line, s3wid_t *wid, int32 max_n_wid, int32 add_oov, char *uttid) { char *lp, word[1024]; int32 n, k; s3wid_t w; s3cipid_t ci[1]; uttid[0] = '\0'; ci[0] = (s3cipid_t) 0; lp = line; n = 0; while (sscanf (lp, "%s%n", word, &k) == 1) { lp += k; if (n >= max_n_wid) return -n; if (is_uttid (word, uttid)) break; wid[n] = dict_wordid (dict, word); /* Up to caller to handle BAD_WIDs */ if (NOT_WID(wid[n])) { /* OOV word */ if (add_oov) { E_INFO("Adding %s to dictionary\n", word); wid[n] = dict_add_word (dict, word, NULL, 0); if (NOT_WID(wid[n])) E_FATAL("dict_add_word(%s) failed for line: %s\n", word, line); } else E_FATAL("Unknown word (%s) in line: %s\n", word, line); } n++; } if (sscanf (lp, "%s", word) == 1) /* Check that line really ended */ E_WARN("Nonempty data ignored after uttid(%s) in line: %s\n", uttid, line); return n; } <file_sep>/SphinxTrain/src/libs/libcommon/best_q.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: best_q.c * * Description: * * Author: * *********************************************************************/ #include <s3/best_q.h> #include <s3/metric.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/cmd_ln.h> #include <s3/div.h> #include <stdio.h> #include <string.h> float64 best_q(float32 ****mixw, /* ADDITION FOR CONTINUOUS_TREES 21 May 98 */ float32 ****means, float32 ****vars, uint32 *veclen, /* END ADDITION FOR CONTINUOUS_TREES */ uint32 n_model, uint32 n_state, uint32 n_stream, uint32 n_density, float32 *stwt, uint32 **dfeat, uint32 n_dfeat, quest_t *all_q, uint32 n_all_q, pset_t *pset, uint32 *id, uint32 n_id, float32 ***dist, /* ADDITION FOR CONTINUOUS_TREES 21 May 98 */ float64 node_wt_ent, /* Weighted entropy of node */ /* END ADDITION FOR CONTINUOUS_TREES */ quest_t **out_best_q) { float32 ***yes_dist; /* ADDITION FOR CONTINUOUS_TREES */ float32 ***yes_means=0; float32 ***yes_vars=0; float32 varfloor=0; float64 y_ent; /* END ADDITION FOR CONTINUOUS_TREES */ float64 yes_dnom, yes_norm; uint32 *yes_id; float32 ***no_dist; /* ADDITION FOR CONTINUOUS_TREES */ float32 ***no_means=0; float32 ***no_vars=0; float64 n_ent; /* END ADDITION FOR CONTINUOUS_TREES */ float64 no_dnom, no_norm; uint32 *no_id; uint32 n_yes, n_b_yes = 0; uint32 n_no, n_b_no = 0; uint32 i, j, k, q, b_q=0, s; uint32 ii; float64 einc, b_einc = -1.0e+50; /* ADDITION FOR CONTINUOUS_TREES; 20 May 98 */ char* type; uint32 continuous, sumveclen=0; type = (char *)cmd_ln_access("-ts2cbfn"); if (strcmp(type,".semi.")!=0 && strcmp(type,".cont.") != 0) E_FATAL("Type %s unsupported; trees can only be built on types .semi. or .cont.\n",type); if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; if (continuous == 1) { varfloor = *(float32 *)cmd_ln_access("-varfloor"); /* Allocating for sumveclen is overallocation, but it eases coding */ for (ii=0,sumveclen=0;ii<n_stream;ii++) sumveclen += veclen[ii]; yes_means = (float32 ***)ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); yes_vars = (float32 ***)ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); no_means = (float32 ***)ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); no_vars = (float32 ***)ckd_calloc_3d(n_state,n_stream,sumveclen,sizeof(float32)); } /* END ADDITIONS FOR CONTINUOUS_TREES */ n_yes = n_no = 0; yes_dist = (float32 ***)ckd_calloc_3d(n_state, n_stream, n_density, sizeof(float32)); no_dist = (float32 ***)ckd_calloc_3d(n_state, n_stream, n_density, sizeof(float32)); for (q = 0; q < n_all_q; q++) { memset(&yes_dist[0][0][0], 0, sizeof(float32) * n_state * n_stream * n_density); memset(&no_dist[0][0][0], 0, sizeof(float32) * n_state * n_stream * n_density); /* ADDITION FOR CONTINUOUS_TREES; If continuous hmm initialize means and vars to zero */ if (continuous == 1) { memset(&yes_means[0][0][0], 0, sizeof(float32) * n_state * n_stream * sumveclen); memset(&yes_vars[0][0][0], 0, sizeof(float32) * n_state * n_stream * sumveclen); memset(&no_means[0][0][0], 0, sizeof(float32) * n_state * n_stream * sumveclen); memset(&no_vars[0][0][0], 0, sizeof(float32) * n_state * n_stream * sumveclen); } /* END ADDITION FOR CONTINUOUS_TREES */ n_yes = n_no = 0; for (ii = 0; ii < n_id; ii++) { i = id[ii]; if (eval_quest(&all_q[q], dfeat[i], n_dfeat)) { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { yes_dist[s][j][k] += mixw[i][s][j][k]; } } } /* MODIFICATION FOR CONTINUOUS_TREES: ADDITIONS FOR CONTINUOUS CASE */ if (continuous == 1) { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < veclen[j]; k++) { yes_means[s][j][k] += mixw[i][s][j][0] * means[i][s][j][k]; yes_vars[s][j][k] += mixw[i][s][j][0] * (vars[i][s][j][k] + means[i][s][j][k]*means[i][s][j][k]); } } } } /* END MODIFICATION FOR CONTINUOUS_TREES */ ++n_yes; } else { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { no_dist[s][j][k] += mixw[i][s][j][k]; } } } /* MODIFICATION FOR CONTINUOUS_TREES: ADDITIONS FOR CONTINUOUS CASE */ if (continuous == 1) { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < veclen[j]; k++) { no_means[s][j][k] += mixw[i][s][j][0] * means[i][s][j][k]; no_vars[s][j][k] += mixw[i][s][j][0] * (vars[i][s][j][k] + means[i][s][j][k]*means[i][s][j][k]); } } } } /* END MODIFICATION FOR CONTINUOUS_TREES */ ++n_no; } } if ((n_yes == 0) || (n_no == 0)) { /* no split. All satisfy or all don't satisfy */ continue; } for (s = 0, einc = 0; s < n_state; s++) { for (k = 0, yes_dnom = 0; k < n_density; k++) { yes_dnom += yes_dist[s][0][k]; } if (yes_dnom == 0) break; yes_norm = 1.0 / yes_dnom; for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { yes_dist[s][j][k] *= yes_norm; } } for (k = 0, no_dnom = 0; k < n_density; k++) { no_dnom += no_dist[s][0][k]; } if (no_dnom == 0) break; no_norm = 1.0 / no_dnom; for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { no_dist[s][j][k] *= no_norm; } } /* MODIFICATION FOR CONTINUOUS_TREES: Do appropriate operations for discrete and continuous */ if (continuous == 1) { y_ent = 0; n_ent = 0; for (j = 0; j < n_stream; j++) { if (yes_dnom != 0) { for (k = 0; k < veclen[j]; k++) { yes_means[s][j][k] *= yes_norm; yes_vars[s][j][k] = yes_vars[s][j][k]*yes_norm - yes_means[s][j][k]*yes_means[s][j][k]; if (yes_vars[s][j][k] < varfloor) yes_vars[s][j][k] = varfloor; } } if (no_dnom != 0) { for (k = 0; k < veclen[j]; k++) { no_means[s][j][k] *= no_norm; no_vars[s][j][k] = no_vars[s][j][k]*no_norm - no_means[s][j][k]*no_means[s][j][k]; if (no_vars[s][j][k] < varfloor) no_vars[s][j][k] = varfloor; } } y_ent += yes_dnom * ent_cont(yes_means[s][j],yes_vars[s][j],veclen[j]); n_ent += no_dnom * ent_cont(no_means[s][j],no_vars[s][j],veclen[j]); } einc += (float64)stwt[s] * (y_ent + n_ent); } else { einc += (float64)stwt[s] * wt_ent_inc(yes_dist[s], yes_dnom, no_dist[s], no_dnom, dist[s], n_stream, n_density); } } /* END MODIFICATION FOR CONTINUOUS_TREES */ /* ADDITION FOR CONTINUOUS_TREES; In current code this is true only for continous HMM */ if (continuous == 1) { einc -= node_wt_ent; } /* END ADDITION FOR CONTINUOUS_TREES */ if (s < n_state) { /* Ended iteration over states prematurely; assume 'bad' question */ continue; } if (einc > b_einc) { b_einc = einc; b_q = q; n_b_yes = n_yes; n_b_no = n_no; } } if ((n_b_yes == 0) || (n_b_no == 0)) { /* No best question */ *out_best_q = NULL; return 0; } yes_id = (uint32 *)ckd_calloc(n_b_yes, sizeof(uint32)); no_id = (uint32 *)ckd_calloc(n_b_no, sizeof(uint32)); memset(&yes_dist[0][0][0], 0, sizeof(float32) * n_state * n_stream * n_density); memset(&no_dist[0][0][0], 0, sizeof(float32) * n_state * n_stream * n_density); n_yes = n_no = 0; for (ii = 0; ii < n_id; ii++) { i = id[ii]; if (eval_quest(&all_q[b_q], dfeat[i], n_dfeat)) { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { yes_dist[s][j][k] += mixw[i][s][j][k]; } } } yes_id[n_yes] = i; ++n_yes; } else { for (s = 0; s < n_state; s++) { for (j = 0; j < n_stream; j++) { for (k = 0; k < n_density; k++) { no_dist[s][j][k] += mixw[i][s][j][k]; } } } no_id[n_no] = i; ++n_no; } } ckd_free_3d((void ***)yes_dist); ckd_free((void *)yes_id); ckd_free_3d((void ***)no_dist); ckd_free((void *)no_id); /* ADDITION FOR CONTINUOUS_TREES */ if (continuous == 1) { ckd_free_3d((void ***)yes_means); ckd_free_3d((void ***)yes_vars); ckd_free_3d((void ***)no_means); ckd_free_3d((void ***)no_vars); } /* END ADDITION FOR CONTINUOUS_TREES */ *out_best_q = &all_q[b_q]; return b_einc; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/corpus/AudioDatabase.java package edu.cmu.sphinx.tools.corpus; import javax.sound.sampled.AudioFormat; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Mar 11, 2006 * Time: 1:57:03 PM */ public class AudioDatabase { private PCMAudioFile pcm; private TextFileOfDoubles pitch; private TextFileOfDoubles energy; public PCMAudioFile getPcm() { return pcm; } public void setPcm(PCMAudioFile pcm) { this.pcm = pcm; } public TextFileOfDoubles getPitch() { return pitch; } public void setPitch(TextFileOfDoubles pitch) { this.pitch = pitch; } public TextFileOfDoubles getEnergy() { return energy; } public void setEnergy(TextFileOfDoubles energy) { this.energy = energy; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final AudioDatabase that = (AudioDatabase) o; if (energy != null ? !energy.equals(that.energy) : that.energy != null) return false; if (pcm != null ? !pcm.equals(that.pcm) : that.pcm != null) return false; if (pitch != null ? !pitch.equals(that.pitch) : that.pitch != null) return false; return true; } public int hashCode() { int result; result = (pcm != null ? pcm.hashCode() : 0); result = 29 * result + (pitch != null ? pitch.hashCode() : 0); result = 29 * result + (energy != null ? energy.hashCode() : 0); return result; } } <file_sep>/SphinxTrain/include/s2/magic.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* magic numbers defining types of HMM files. */ #define COUNT_F -1 #define PROB_F -2 #define OLD_FORMAT_F -3 #define COUNT3_F -4 #define PROB3_F -5 #define TIED_DIST -10 #define BIG_HMM -100 #define COUNT_P(_var) ((_var)==COUNT_F) #define OLD_P(_var) ((_var)==OLD_FORMAT_F) #define IS_MAGIC(_var) ((_var) < 0) /* tags for kinds of data user wants */ #define BOTH 0 #define PROBS 1 #define COUNTS 2 #define EITHER 3 #define TOPOLOGY_ONLY 4 <file_sep>/CLP/include/Makefile.am noinst_HEADERS = Cluster.h \ Clustering.h \ common.h \ common_lattice.h \ GetOpt.h \ Lattice.h \ LatticeInfo.h \ LineSplitter.h \ Link.h \ Node.h \ Prob.h \ Prons.h \ Similarities.h <file_sep>/SphinxTrain/src/programs/bldtree/main.c /* -*- c-basic-offset: 4 -*- */ /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: main.c * * Modified to build decision trees with continuous models * <NAME>, May 1998 * * Description: * Build senonic decision trees from discrete pdf's. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/dtree.h> #include <s3/model_def_io.h> #include <s3/s3mixw_io.h> #include <s3/pset_io.h> #include <s3/quest.h> #include <s3/dtree.h> #include <s3/metric.h> #include <s3/div.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <s3/vector.h> #include <s3/s3gau_io.h> #include <s3/gauden.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define N_DFEAT 4 static void mk_stwt(float32 *ostwt, float32 *stwt, uint32 t_s, uint32 n_stwt) { float32 tmp; int i, j; for (i = 0, tmp = 0; i < n_stwt; i++) { j = i - t_s; if (j < 0) j = -j; ostwt[i] = stwt[j]; tmp += ostwt[i]; } tmp = 1.0 / tmp; for (i = 0; i < n_stwt; i++) { ostwt[i] *= tmp; } E_INFO("nrm stwt: "); for (i = 0; i < n_stwt; i++) { E_INFOCONT("%5.3f ", ostwt[i]); } E_INFOCONT("\n"); } static int find_triphones(model_def_t *mdef, const char *phn, uint32 *p_s, uint32 *p_e) { uint32 targ_base, p, b; targ_base = acmod_set_name2id(mdef->acmod_set, phn); *p_s = *p_e = NO_ID; if (targ_base == NO_ACMOD) return -1; if (targ_base >= acmod_set_n_ci(mdef->acmod_set)) { *p_s = *p_e = targ_base; return 0; } /* Scan for first, p_s, and last phone, p_e, * which have the target base phone */ for (p = acmod_set_n_ci(mdef->acmod_set); p < acmod_set_n_acmod(mdef->acmod_set); p++) { b = acmod_set_base_phone(mdef->acmod_set, p); if ((b == targ_base) && (*p_s == NO_ID)) { *p_s = p; } else if ((b == targ_base) && (*p_s != NO_ID) && (*p_e != NO_ID)) { E_FATAL("n-phones with base phone %s occur non-consecutively in the mdef file\n", phn); } else if ((b != targ_base) && (*p_s != NO_ID) && (*p_e == NO_ID)) { *p_e = p-1; } } /* If we've reached the end of the list, * then the last phone in the list is the last * target phone */ if ((p == acmod_set_n_acmod(mdef->acmod_set)) && (*p_e == NO_ID)) { *p_e = p-1; } if (*p_s == NO_ID) { E_WARN("No triphones involving %s\n", phn); return -1; } return 0; } static int init(model_def_t **out_mdef, const char *phn, uint32 state, uint32 *out_mixw_s, float32 *****out_mixw, float32 *****out_mixw_occ, /* ADDITIONS FOR CONTINUOUS_TREES - 18 May 98 */ float32 *****out_mean, float32 *****out_var, uint32 **out_veclen, /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 *out_n_model, uint32 *out_n_state, uint32 *out_n_stream, uint32 *out_n_density, float32 **out_stwt, uint32 ***out_dfeat, pset_t **out_pset, uint32 *out_n_pset, quest_t **out_all_q, uint32 *out_n_all_q) { const char *moddeffn; const char *mixwfn; const char *psetfn; model_def_t *mdef; uint32 p, p_s = NO_ID, p_e = NO_ID, s, m; int allphones; uint32 mixw_s, mixw_e; uint32 **dfeat; pset_t *pset; uint32 n_pset; acmod_id_t b, l, r; word_posn_t pn; float32 ****mixw; float32 ****mixw_occ; float32 ***in_mixw; uint32 n_state, n_model, n_in_mixw, n_stream, n_density; uint32 i, j, k; float32 *stwt; float32 *istwt; const char **stwt_str; quest_t *all_q; /* MODIFICATION FOR CONTEXT CHECK */ uint32 n_l_q, n_r_q; /* END MODIFICATIONS FOR CONTEXT CHECK */ uint32 n_all_q; uint32 n_phone_q, n_wdbndry; float64 norm; float64 dnom; float32 mwfloor; float64 wt_ent; float64 s_wt_ent=0; /* ADDITION FOR CONTINUOUS_TREES, 18 May 98 */ char* type; uint32 continuous; const uint32 *l_veclen, *t_veclen; uint32 l_nstates, t_nstates; uint32 t_nfeat, t_ndensity; vector_t ***fullmean; vector_t ***fullvar = NULL; vector_t ****fullvar_full = NULL; float32 ****mean; float32 ****var; float32 varfloor; uint32 mm, kk,ll,n,nn,sumveclen; char *cntflag; float32 cntthreshold,stcnt; /* END ADDITION FOR CONTINUOUS_TREES */ moddeffn = cmd_ln_access("-moddeffn"); if (moddeffn == NULL) E_FATAL("Specify -moddeffn\n"); E_INFO("Reading: %s\n", moddeffn); if (model_def_read(&mdef, moddeffn) != S3_SUCCESS) return S3_ERROR; *out_mdef = mdef; allphones = cmd_ln_int32("-allphones"); if (allphones) { p_s = acmod_set_n_ci(mdef->acmod_set); p_e = acmod_set_n_acmod(mdef->acmod_set)-1; } else if (phn) { if (find_triphones(mdef, phn, &p_s, &p_e) == -1) return S3_ERROR; } else { E_FATAL("No -phone, -start_phone, or -end_phone specified!\n"); } E_INFO("Building trees for [%s]", acmod_set_id2name(mdef->acmod_set, p_s)); E_INFOCONT(" through [%s]\n", acmod_set_id2name(mdef->acmod_set, p_e)); for (p = p_s, i = mdef->defn[p_s].state[0]-1; p <= p_e; p++) { for (j = 0; j < mdef->defn[p].n_state; j++) { if (mdef->defn[p].state[j] != TYING_NON_EMITTING) { if (mdef->defn[p].state[j] != i+1) { E_ERROR("States in triphones for %s are not consecutive\n", phn); return S3_ERROR; } i = mdef->defn[p].state[j]; } } } /*ADDITION - CHECK FOR NUMBER OF OCCURANCES OF STATE */ cntflag = (char *)ckd_calloc(p_e-p_s+1,sizeof(char)); cntthreshold = *(float32 *)cmd_ln_access("-cntthresh"); /* END ADDITION - CHECK FOR NUMBER OF OCCURANCES OF STATE */ /* Find first and last mixing weight used for p_s through p_e */ mixw_s = mdef->defn[p_s].state[0]; mixw_e = mdef->defn[p_e].state[mdef->defn[p_e].n_state-2]; *out_mixw_s = mixw_s; E_INFO("Covering states |[%u %u]| == %u\n", mixw_s, mixw_e, mixw_e - mixw_s + 1); mixwfn = cmd_ln_access("-mixwfn"); if (mixwfn == NULL) E_FATAL("Specify -mixwfn\n"); E_INFO("Reading: %s\n", mixwfn); if (s3mixw_intv_read(mixwfn, mixw_s, mixw_e, &in_mixw, &n_in_mixw, &n_stream, &n_density) != S3_SUCCESS) return S3_ERROR; *out_n_stream = n_stream; *out_n_density = n_density; n_state = mdef->defn[p_s].n_state - 1; *out_n_state = n_state; for (i = p_s+1; i <= p_e; i++) { if ((mdef->defn[i].n_state - 1) != n_state) { E_FATAL("Models do not have uniform topology\n"); } } /*ADDITION FOR STATE COUNT CHECK */ for (i=p_s,j=0,mm=0; i<=p_e ;i++,j++) { cntflag[j] = 1; for (k=0; k < n_state; k++) { s = mdef->defn[i].state[k] - mixw_s; for (kk=0; kk<n_stream; kk++) { stcnt = 0; for (ll=0; ll<n_density; ll++) { stcnt += in_mixw[s][kk][ll]; } if (stcnt < cntthreshold) cntflag[j] = 0; } } if (cntflag[j]==1) mm++; } /* END ADDITION FOR STATE COUNT CHECK */ n_model = mm; *out_n_model = n_model; E_INFO("%d of %d models have observation count greater than %f\n",n_model,p_e-p_s+1,cntthreshold); /* Allocate the state weight array for weighting the * similarity of neighboring states */ istwt = ckd_calloc(n_state, sizeof(float32)); stwt = ckd_calloc(n_state, sizeof(float32)); *out_stwt = stwt; stwt_str = (const char **)cmd_ln_access("-stwt"); if (stwt_str == NULL) { E_FATAL("Specify state weights using -stwt\n"); } for (i = 0; i < n_state; i++) { if (stwt_str[i] == NULL) E_FATAL("Fewer state weights than states\n"); istwt[i] = atof(stwt_str[i]); } if (stwt_str[i] != NULL) { E_FATAL("More weights than states\n"); } /* Normalize the weights so they sum to 1.0 */ for (i = 0, norm = 0; i < n_state; i++) norm += istwt[i]; norm = 1.0 / norm; for (i = 0; i < n_state; i++) istwt[i] *= norm; mk_stwt(stwt, istwt, state, n_state); ckd_free((void *)istwt); /* * Build the 4D array: * * mixw[0..n_model-1][0..n_state-1][0..n_feat-1][0..n_density-1] * * out of the usual mixw[][][] array * */ mixw_occ = (float32 ****)ckd_calloc_2d(n_model, n_state, sizeof(float32 **)); mixw = (float32 ****)ckd_calloc_4d(n_model, n_state, n_stream, n_density, sizeof(float32)); *out_mixw_occ = mixw_occ; *out_mixw = mixw; /* MODIFICATION FOR STATE COUNT CHECK */ /* Re-index mixing weights by model and topological state position */ for (i = p_s, j = 0, mm = 0; i <= p_e; i++, mm++) { if (cntflag[mm]==1) { for (k = 0; k < n_state; k++) { s = mdef->defn[i].state[k] - mixw_s; mixw_occ[j][k] = in_mixw[s]; } j++; } } /* END MODIFICATION FOR STATE COUNT CHECK */ assert(j == n_model); mwfloor = *(float32 *)cmd_ln_access("-mwfloor"); /* ADDITIONS FOR CONTINUOUS_TREES 18 May 98. If DISCRETE HMM, GET PROBABILITIES, ELSE SIMPLY GET MEANS AND VARIANCES */ type = (char *)cmd_ln_access("-ts2cbfn"); if (strcmp(type,".semi.")!=0 && strcmp(type,".cont.") != 0) E_FATAL("Type %s unsupported; trees can only be built on types .semi. or .cont.\n",type); if (strcmp(type,".cont.") == 0) continuous = 1; else continuous = 0; #if 0 /* This is rather arbitrary (in actual fact we should treat all models as continuous) */ /* Additional check for meaningless input */ if (continuous == 0 && n_density < 256) { E_FATAL("Attempt to build trees on semi-continuous HMMs with %d < 256 gaussians!\n****A minimum of 256 gaussians are expected!\n",n_density); } #endif /* END ADDITIONS FOR CONTINUOUS_TREES */ /* MODIFICATIONS FOR CONTINUOUS_TREES: Added "if (continuous==0)" to lines relating to wt_ent */ for (s = 0, wt_ent = 0; s < n_state; s++) { if (continuous==0) s_wt_ent = 0; for (i = 0; i < n_model; i++) { for (j = 0; j < n_stream; j++) { /* The denominators for each stream should be nearly identical, but... */ for (k = 0, dnom = 0; k < n_density; k++) { dnom += mixw_occ[i][s][j][k]; } if (dnom != 0) { norm = 1.0 / dnom; for (k = 0; k < n_density; k++) { mixw[i][s][j][k] = mixw_occ[i][s][j][k] * norm; if (mixw[i][s][j][k] < mwfloor) { mixw[i][s][j][k] = mwfloor; } } if (continuous == 0) s_wt_ent += dnom * ent_d(mixw[i][s][j], n_density); } } } if (continuous == 0) wt_ent += stwt[s] * s_wt_ent; } if (continuous == 0) E_INFO("%u-class entropy: %e\n", n_model, wt_ent); /* END MODIFICATIONS FOR CONTINUOUS_TREES */ /* ADDITIONS FOR CONTINUOUS_TREES 18 May 98. If DISCRETE HMM, GET PROBABILITIES, ELSE SIMPLY GET MEANS AND VARIANCES */ if (continuous == 1) { int32 var_is_full = cmd_ln_int32("-fullvar"); /* Read Means and Variances; perform consistency checks */ if (s3gau_read(cmd_ln_access("-meanfn"), &fullmean, &l_nstates, &t_nfeat, &t_ndensity, &l_veclen) != S3_SUCCESS) E_FATAL("Error reading mean file %s\n",cmd_ln_access("-meanfn")); *out_veclen = (uint32 *)l_veclen; if (t_nfeat != n_stream && t_ndensity != n_density) E_FATAL("Mismatch between Mean and Mixture weight files\n"); if (var_is_full) { if (s3gau_read_full(cmd_ln_access("-varfn"), &fullvar_full, &t_nstates, &t_nfeat, &t_ndensity, &t_veclen) != S3_SUCCESS) E_FATAL("Error reading var file %s\n",cmd_ln_access("-varfn")); } else { if (s3gau_read(cmd_ln_access("-varfn"), &fullvar, &t_nstates, &t_nfeat, &t_ndensity, &t_veclen) != S3_SUCCESS) E_FATAL("Error reading var file %s\n",cmd_ln_access("-varfn")); } if (t_nfeat != n_stream && t_ndensity != n_density) E_FATAL("Mismatch between Variance and Mixture weight files\n"); for (i=0;i<n_stream;i++) if (t_veclen[i] != l_veclen[i]) E_FATAL("Feature length %d in var file != %d in mean file for feature %d\n",t_veclen[i],l_veclen[i],i); if (l_nstates != t_nstates) E_FATAL("Total no. of states %d in var file != %d in mean file\n",t_nstates,l_nstates); if (t_ndensity > 1) E_WARN("The state distributions given have %d gaussians per state;\n..*..shrinking them down to 1 gau per state..\n",t_ndensity); /* Allocate for out_mean and out_var. If input are multi_gaussian distributions convert to single gaussians. Copy appropriate states to out_mean and out_var */ for (i=0,sumveclen=0; i < n_stream; i++) sumveclen += t_veclen[i]; mean = (float32 ****)ckd_calloc_4d(n_model,n_state,n_stream,sumveclen,sizeof(float32)); /* Use only the diagonals regardless of whether -varfn is full. */ var = (float32 ****)ckd_calloc_4d(n_model,n_state,n_stream,sumveclen,sizeof(float32)); varfloor = *(float32 *)cmd_ln_access("-varfloor"); /* MODIFICATION FOR STATE COUNT CHECK */ for (i = p_s, j = 0, m = mixw_s, mm = 0; i <= p_e; i++, mm++) { if (cntflag[mm]==1) { for (k = 0; k < n_state; k++, m++) { for (ll = 0; ll < n_stream; ll++) { float32 *featmean,*featvar; featmean = mean[j][k][ll]; featvar = var[j][k][ll]; dnom = 0; for (n = 0; n < n_density; n++) { float32 mw = mixw_occ[j][k][ll][n]; dnom += mw; for (nn = 0; nn < l_veclen[ll]; nn++) { featmean[nn] += mw * fullmean[m][ll][n][nn]; if (var_is_full) featvar[nn] += mw *(fullmean[m][ll][n][nn]*fullmean[m][ll][n][nn] + fullvar_full[m][ll][n][nn][nn]); else featvar[nn] += mw *(fullmean[m][ll][n][nn]*fullmean[m][ll][n][nn] + fullvar[m][ll][n][nn]); } } if (dnom != 0) { for (nn = 0; nn < l_veclen[ll]; nn++) { featmean[nn] /= dnom; featvar[nn] = featvar[nn]/dnom - featmean[nn]*featmean[nn]; if (featvar[nn] < varfloor) featvar[nn] = varfloor; } } else { for (nn = 0; nn < l_veclen[ll]; nn++) { if (featmean[nn] != 0) E_FATAL("dnom = 0, but featmean[nn] != 0, = %f for ll = %d\n",featmean[nn],ll); } } /* Now on we need only have global counts for the mixws, so we store them all in mixw_occ[][][0] */ mixw_occ[j][k][ll][0] = dnom; } } j++; } else m += n_state; /* account for states of skipped model */ } /* END MODIFICATION FOR STATE COUNT CHECK */ assert(j == n_model); /* Now n_density = 1 */ n_density = 1; *out_n_density = n_density; *out_mean = mean; *out_var = var; ckd_free_4d((void ****)fullmean); if (fullvar) ckd_free_4d((void ****)fullvar); if (fullvar_full) gauden_free_param_full(fullvar_full); } /* END ADDITIONS FOR CONTINUOUS_TREES */ /* * Allocate a set of decision tree features * associated with each phone */ dfeat = (uint32 **)ckd_calloc_2d(n_model, N_DFEAT, sizeof(uint32)); *out_dfeat = dfeat; /* MODIFICATION FOR STATE COUNT CHECK */ for (p = p_s, j = 0, mm = 0; p <= p_e; p++, mm++) { if (cntflag[mm] == 1) { acmod_set_id2tri(mdef->acmod_set, &b, &l, &r, &pn, p); dfeat[j][0] = (uint32)l; dfeat[j][1] = (uint32)b; dfeat[j][2] = (uint32)r; dfeat[j][3] = (uint32)pn; j++; } } assert(j == n_model); ckd_free(cntflag); /* END MODIFICATION FOR STATE COUNT CHECK */ psetfn = (const char *)cmd_ln_access("-psetfn"); E_INFO("Reading: %s\n", psetfn); *out_pset = pset = read_pset_file(psetfn, mdef->acmod_set, &n_pset); *out_n_pset = n_pset; /* CONTEXT CHECK: MODIFY TO HANDLE LEFT AND RIGHT CONTEXT QUESTIONS SEPARATELY IF NEEDED */ /* Determine the # of phone sets and word boundary * questions there are */ /* MODIFICATION FOR CONTEXT CHECK: COUNT LEFT AND RIGHT SEPARATELY, IF SO MARKED; ELSE COUNT IT TWICE - IT GOES INTO BOTH LEFT AND RIGHT CONTEXTS */ n_l_q = n_r_q = 0; for (i = 0, n_phone_q = 0, n_wdbndry = 0; i < n_pset; i++) { if (pset[i].member){ if (strstr(pset[i].name,"_L") != NULL) { n_phone_q++; n_l_q++; } else if (strstr(pset[i].name,"_R") != NULL) { n_phone_q++; n_r_q++; } else if (allphones) n_phone_q += 3; else n_phone_q += 2; } else n_wdbndry++; } /* Compute the total number of simple questions */ if (allphones) /* Ask questions about the phone itself */ n_all_q = 2 * n_phone_q + 2 * n_wdbndry; else n_all_q = 2 * n_phone_q + 2 * n_wdbndry; *out_n_all_q = n_all_q; /* Allocate an array to hold all the simple questions */ all_q = ckd_calloc(n_all_q, sizeof(quest_t)); *out_all_q = all_q; E_INFO("%u total simple questions (%u phone; %u word bndry)\n", n_all_q, 2 * n_phone_q, 2 * n_wdbndry); E_INFO("%u Left Only questions, and %u Right Only questions\n", 2*n_l_q, 2*n_r_q); /* END MODIFICATION FOR CONTEXT CHECK */ /* MODIFICATION FOR CONTEXT CHECK : CREATE SEPARATE LEFT AND RIGHT QUESTIONS WHERE NECESSARY */ /* Generate all the L simple questions to be asked when generating * simple trees */ for (i = 0, l = 0; i < n_pset; i++) { if (pset[i].member) { /* Generate the phonetic questions */ if (strstr(pset[i].name,"_L") != NULL || (strstr(pset[i].name,"_L") == NULL && strstr(pset[i].name,"_R") == NULL)){ all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = FALSE; all_q[l].ctxt = -1; /* one phone to the left of base phone */ l++; } if (strstr(pset[i].name,"_R") != NULL || (strstr(pset[i].name,"_L") == NULL && strstr(pset[i].name,"_R") == NULL)){ all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = FALSE; all_q[l].ctxt = 1; /* one phone to the right of base phone */ l++; } if (allphones && strstr(pset[i].name,"_R") == NULL && strstr(pset[i].name,"_L") == NULL) { all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = FALSE; all_q[l].ctxt = 0; /* the base phone itself */ l++; } /* The negations of the above questions */ if (strstr(pset[i].name,"_L") != NULL || (strstr(pset[i].name,"_L") == NULL && strstr(pset[i].name,"_R") == NULL)){ all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = TRUE; all_q[l].ctxt = -1; l++; } if (strstr(pset[i].name,"_R") != NULL || (strstr(pset[i].name,"_L") == NULL && strstr(pset[i].name,"_R") == NULL)){ all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = TRUE; all_q[l].ctxt = 1; l++; } if (allphones && strstr(pset[i].name,"_R") == NULL && strstr(pset[i].name,"_L") == NULL) { all_q[l].pset = i; all_q[l].member = pset[i].member; all_q[l].neg = TRUE; all_q[l].ctxt = 0; l++; } } else if (pset[i].posn) { /* Word position question */ all_q[l].pset = i; all_q[l].posn = pset[i].posn; all_q[l].neg = FALSE; l++; /* Negation of the above question */ all_q[l].pset = i; all_q[l].posn = pset[i].posn; all_q[l].neg = TRUE; l++; } else E_ERROR("Invalid phoneme set %s\n", pset[i].name); } /* END MODIFICATION FOR CONTEXT CHECK */ return S3_SUCCESS; } int main(int argc, char *argv[]) { float32 ****mixw_occ = NULL; float32 ****mixw = NULL; /* ADDITIONS FOR CONTINUOUS_TREES: 18 May 98 */ float32 ****means = NULL; float32 ****vars = NULL; uint32 *veclen = NULL; /* END ADDITIONS FOR CONTINUOUS_TREES */ uint32 mixw_s; uint32 n_model = 0; uint32 n_state = 0; uint32 n_stream = 0; uint32 n_density = 0; model_def_t *mdef = NULL; const char *phn; pset_t *pset = NULL; uint32 n_pset; uint32 **dfeat = NULL; quest_t *all_q = NULL; uint32 n_all_q = 0; uint32 m; uint32 *id; float32 *stwt = NULL; uint32 state; dtree_t *tr; FILE *fp; float32 mwfloor; parse_cmd_ln(argc, argv); phn = cmd_ln_access("-phone"); state = *(uint32 *)cmd_ln_access("-state"); /* MODIFICATION FOR CONTINUOUS_TREES 18 May 98: PASSING &means, &vars and &veclen */ if (init(&mdef, phn, state, &mixw_s, &mixw, &mixw_occ, &means, &vars, &veclen, &n_model, &n_state, &n_stream, &n_density, &stwt, &dfeat, &pset, &n_pset, &all_q, &n_all_q) != S3_SUCCESS) { /* END MODIFICATION FOR CONTINUOUS_TREES */ E_FATAL("Initialization failed\n"); } mwfloor = *(float32 *)cmd_ln_access("-mwfloor"); id = (uint32 *)ckd_calloc(n_model, sizeof(uint32)); /* Initially, all states in the same class */ for (m = 0; m < n_model; m++) { id[m] = m; } /* Build the composite tree. Recursively generates * the composite decision tree. See dtree.c in libcommon */ /* MODIFICATION FOR CONTINUOUS_TREES - PASS THE MEAN, VAR etc. TOO */ tr = mk_tree_comp(mixw_occ, means, vars, veclen, n_model, n_state, n_stream, n_density, stwt, id, n_model, all_q, n_all_q, pset, acmod_set_n_ci(mdef->acmod_set), dfeat, N_DFEAT, *(uint32 *)cmd_ln_access("-ssplitmin"), *(uint32 *)cmd_ln_access("-ssplitmax"), *(float32 *)cmd_ln_access("-ssplitthr"), *(uint32 *)cmd_ln_access("-csplitmin"), *(uint32 *)cmd_ln_access("-csplitmax"), *(float32 *)cmd_ln_access("-csplitthr"), mwfloor); /* END MODIFICATION FOR CONTINUOUS_TREES */ /* Save it to a file */ fp = fopen(cmd_ln_access("-treefn"), "w"); if (fp == NULL) { E_FATAL_SYSTEM("Unable to open %s for writing", cmd_ln_access("-treefn")); } print_final_tree(fp, &tr->node[0], pset); fclose(fp); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2005/06/13 22:18:22 dhdfu * Add -allphones arguments to decision tree and state tying code. Allows senones to be shared across multiple base phones (though they are currently still restricted to the same state). This can improve implicit pronunciation modeling in some cases, such as grapheme-based models, though it usually has little effect. Building the big trees can take a very long time. * * Revision 1.5 2004/07/21 18:30:32 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:13 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/SphinxTrain/python/cmusphinx/s3model.py # Copyright (c) 2006 Carnegie Mellon University # # You may copy and modify this freely under the same terms as # Sphinx-III """Sphinx-III acoustic models. This module provides a class which wraps a set of acoustic models, as used by SphinxTrain, Sphinx-III, and PocketSphinx. It provides functions for computing Gaussian mixture densities for acoustic feature vectors. """ __author__ = "<NAME> <<EMAIL>>" __version__ = "$Revision$" import s3gau import s3mixw import s3tmat import s3mdef import s3file import sys import os import numpy WORSTSCORE = -100000 class S3Model(object): def __init__(self, path=None, topn=4): self.topn = topn self.mwfloor = 1e-5 self.varfloor = 1e-5 if path != None: self.read(path) def read(self, path): self.mdef = s3mdef.open(os.path.join(path, "mdef")) self.mean = s3gau.open(os.path.join(path, "means")) self.var = s3gau.open(os.path.join(path, "variances")) self.mixw = s3mixw.open(os.path.join(path, "mixture_weights")) self.tmat = s3tmat.open(os.path.join(path, "transition_matrices")) # Normalize transition matrices and mixture weights for t in range(0, len(self.tmat)): self.tmat[t] = (self.tmat[t].T / self.tmat[t].sum(1)).T for t in range(0, len(self.mixw)): self.mixw[t] = (self.mixw[t].T / self.mixw[t].sum(1)).T.clip(self.mwfloor, 1.0) # Floor variances and precompute normalizing and inverse variance terms self.norm = numpy.empty((len(self.var), len(self.var[0]), len(self.var[0][0])),'d') for m,mgau in enumerate(self.var): for f,feat in enumerate(mgau): fvar = feat.clip(self.varfloor, numpy.inf) # log of 1/sqrt(2*pi**N * det(var)) det = numpy.log(fvar).sum(1) lrd = -0.5 * (det + 2 * numpy.pi * feat.shape[1]) self.norm[m,f] = lrd # "Invert" variances feat[:] = (1 / (fvar * 2)) # Construct senone to codebook mapping if os.access(os.path.join(path, "senmgau"), os.F_OK): self.senmgau = s3file.S3File(os.path.join(path, "senmgau")).read1d() elif len(self.mean) == 1: self.senmgau = numpy.ones(len(self.mixw)) else: self.senmgau = numpy.arange(0, len(self.mixw)) self.senscr = numpy.ones(len(self.mixw)) * WORSTSCORE def cb_compute(self, mgau, feat, obs): "Compute codebook #mgau feature #feat for obs" mean = self.mean[mgau][feat] ivar = self.var[mgau][feat] norm = self.norm[mgau][feat] diff = obs - mean dist = (diff * ivar * diff).sum(1) return norm - dist def senone_compute(self, senones, *features): """Compute senone scores for given list of senones and a frame of acoustic features""" cbs = {} self.senscr[:] = WORSTSCORE for s in senones: m = self.senmgau[s] if not m in cbs: cbs[m] = [self.cb_compute(m, f, features[f]) for f in range(0,len(self.mean[m]))] score = 0 for f, vec in enumerate(features): # Compute densities and scale by mixture weights d = cbs[m][f] + numpy.log(self.mixw[s,f]) # Take top-N densities d = d.take(d.argsort()[-self.topn:]) # Multiply into output score score += numpy.log(numpy.exp(d).sum()) self.senscr[s] = score return numpy.exp(self.senscr - self.senscr.max()) <file_sep>/SphinxTrain/src/programs/delint/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Traceability: * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/common.h> #include <s3/s3.h> /* pick up defn of TRUE/FALSE */ #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: (copied from Rita's web page.) \n\ \n\ Deleted interpolation is the final step in creating semi-continuous \n\ models. The output of deleted interpolation are semi-continuous models \n\ in sphinx-3 format. These have to be further converted to sphinx-2 \n\ format, if you want to use the SPHINX-II decoder. \n\ \n\ Deleted interpolation is an iterative process to interpolate between \n\ CD and CI mixture-weights to reduce the effects of overfitting. The \n\ data are divided into two sets, and the data from one set are used to \n\ estimate the optimal interpolation factor between CI and CD models \n\ trained from the other set. Then the two data sets are switched and \n\ this procedure is repeated using the last estimated interpolation \n\ factor as an initialization for the current step. The switching is \n\ continued until the interpolation factor converges.\n\ \n\ To do this, we need *two* balanced data sets. Instead of the actual\n\ data, however, we use the Bauim-Welch buffers, since the related math\n\ is convenient. we therefore need an *even* number of buffers that can\n\ be grouped into two sets. DI cannot be performed if you train using\n\ only one buffer. At least in the final iteration of the training, you\n\ must perform the training in (at least) two parts. You could also do\n\ this serially as one final iteration of training AFTER BW has\n\ converged, on a non-lsf setup.\n\ \n\ Note here that the norm executable used at the end of every Baum-Welch \n\ iteration also computes models from the buffers, but it does not\n\ require an even number of buffers. BW returns numerator terms and\n\ denominator terms for the final estimation, and norm performs the\n\ actual division. The number of buffers is not important, but you would \n\ need to run norm at the end of EVERY iteration of BW, even if you did\n\ the training in only one part. When you have multiple parts norm sums\n\ up the numerator terms from the various buffers, and the denominator\n\ terms, and then does the division. "; const char examplestr[]= "delint -accumdirs accumdir -moddeffn mdef -mixwfn mixw -cilambda 0.9 -maxiter 4000"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The model definition file name"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The mixture weight parameter file name"}, { "-accumdirs", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A path where accumulated counts are to be read." }, { "-cilambda", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.9", "Weight of CI distributions with respect to uniform distribution"}, { "-maxiter", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "100", "max # of iterations if no lambda convergence"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { /* one or more command line arguments were deemed invalid */ exit(1); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.7 2005/06/13 20:18:55 arthchan2003 * Spelling "correspondance" to "correspondence" * * Revision 1.6 2004/11/29 01:43:45 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.5 2004/08/08 03:49:56 arthchan2003 * delint help and example string * * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.6 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.5 1996/03/25 15:40:25 eht * Added ability to set input feature vector length * * Revision 1.4 1996/01/26 18:07:00 eht * Add the "-feat" argument * * Revision 1.3 1995/09/07 20:01:05 eht * include defn of TRUE/FALSE for machines like HP's running HPUX * * Revision 1.2 1995/08/09 00:38:05 eht * Another development version * * Revision 1.1 1995/06/02 20:56:53 eht * Initial revision * * */ <file_sep>/archive_s3/s3/src/libfbs/lmcontext.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * lmcontext.c -- Surrounding LM context for each utterance. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 26-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ /* * This module deals with files that specify the utterance boundary context for * each utterance. An utterance need not begin with <s> and end with </s>. * Instead, one can use the context specified in a given file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #if (_SUN4) #include <unistd.h> #endif #include <math.h> #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "lmcontext.h" #include "dict.h" #include "lm.h" void lmcontext_load (corpus_t *corp, char *uttid, s3wid_t *pred, s3wid_t *succ) { char *str, wd[4096], *strp; s3wid_t w[3]; int32 i, n; dict_t *dict; s3lmwid_t lwid; if ((str = corpus_lookup (corp, uttid)) == NULL) E_FATAL("Couldn't find LM context for %s\n", uttid); dict = dict_getdict (); strp = str; for (i = 0; i < 4; i++) { if (sscanf (strp, "%s%n", wd, &n) != 1) { if (i < 3) E_FATAL("Bad LM context spec for %s: %s\n", uttid, str); else break; } strp += n; if (strcmp (wd, "-") == 0) w[i] = BAD_WID; else { w[i] = dict_wordid (wd); if (NOT_WID(w[i])) E_FATAL("LM context word (%s) for %s not in dictionary\n", wd, uttid); w[i] = dict_basewid(w[i]); switch (i) { case 0: if ((n = dict->word[w[0]].n_comp) > 0) w[0] = dict->word[w[0]].comp[n-1].wid; break; case 1: if ((n = dict->word[w[1]].n_comp) > 0) { w[0] = dict->word[w[1]].comp[n-2].wid; w[1] = dict->word[w[1]].comp[n-1].wid; } break; case 2: if (w[2] != dict_wordid(FINISH_WORD)) E_FATAL("Illegal successor LM context for %s: %s\n", uttid, str); break; default: assert (0); /* Should never get here */ break; } } } if (IS_WID(w[0]) && NOT_WID(w[1])) E_FATAL("Bad LM context spec for %s: %s\n", uttid, str); for (i = 0; i < 3; i++) { if (IS_WID(w[i])) { lwid = lm_lmwid (w[i]); if (NOT_LMWID(lwid)) E_FATAL("LM context word (%s) for %s not in LM\n", wd, uttid); } } pred[0] = w[0]; pred[1] = w[1]; *succ = w[2]; } <file_sep>/SphinxTrain/scripts_pl/Makefile # ==================================================================== # Copyright (c) 2000 <NAME>. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY <NAME>ON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # Perl scripts # # ==================================================================== TOP=.. DIRNAME=scripts_pl BUILD_DIRS= ALL_DIRS= FESTIVAL_SCRIPTS = make_dict.festival MODULES = lib/Queue/POSIX.pm \ lib/Queue/Job.pm \ lib/Queue/PBS.pm \ lib/SphinxTrain/Config.pm \ lib/SphinxTrain/Util.pm \ lib/Queue.pm SCRIPTS = 00.verify/verify_all.pl \ 03.force_align/force_align.pl \ 03.force_align/slave_align.pl \ 05.lda_train/lda_train.pl \ 10.vector_quantize/agg_seg.pl \ 10.vector_quantize/kmeans.pl \ 10.vector_quantize/slave.VQ.pl \ 20.ci_hmm/baum_welch.pl \ 20.ci_hmm/norm_and_launchbw.pl \ 20.ci_hmm/norm.pl \ 20.ci_hmm/slave_convg.pl \ 30.cd_hmm_untied/baum_welch.pl \ 30.cd_hmm_untied/norm_and_launchbw.pl \ 30.cd_hmm_untied/norm.pl \ 30.cd_hmm_untied/slave_convg.pl \ 40.buildtrees/buildtree.pl \ 40.buildtrees/make_questions.pl \ 40.buildtrees/prunetree.pl \ 40.buildtrees/slave.treebuilder.pl \ 40.buildtrees/tiestate.pl \ 50.cd_hmm_tied/baum_welch.pl \ 50.cd_hmm_tied/norm_and_launchbw.pl \ 50.cd_hmm_tied/norm.pl \ 50.cd_hmm_tied/slave_convg.pl \ 50.cd_hmm_tied/split_gaussians.pl \ 90.deleted_interpolation/deleted_interpolation.pl \ decode/slave.pl \ copy_setup.pl \ make_feats.pl \ maketopology.pl \ RunAll.pl \ setup_SphinxTrain.pl \ setup_tutorial.pl \ texFormat.pl FILES = Makefile RunAll.pl $(TMPSCRIPTS) \ $(FESTIVAL_SCRIPTS) $(MODULES) \ $(SCRIPTS) ALL = make_dict include $(TOP)/config/common_make_rules LOCAL_CLEAN = make_dict make_dict: make_dict.festival @ echo "#!/bin/sh" > $@ @ echo "\"true\"; exec "$(FESTIVAL)' --script $$0 $$*' >>$@ @ cat $< >>$@ @ chmod +x $@ <file_sep>/archive_s3/s3.0/src/libmain/am.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * am.c -- Acoustic model evaluation * * * HISTORY * * 22-Aug-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "am.h" acoustic_t *acoustic_init (feat_t *f, gauden_t *g, senone_t *s, float64 beam, int32 maxfr) { acoustic_t *am; int32 i; if (senone_n_mgau(s) != gauden_n_mgau(g)) { E_ERROR("#Parent mixture Gaussians mismatch: senone(%d), gauden(%d)\n", senone_n_mgau(s), gauden_n_mgau(g)); } if (feat_n_stream(f) != senone_n_stream(s)) { E_ERROR("#Feature-streams mismatch: feat(%d), senone(%d)\n", feat_n_stream(f), senone_n_stream(s)); } if (feat_n_stream(f) != gauden_n_stream(g)) { E_ERROR("#Feature-streams mismatch: feat(%d), gauden(%d)\n", feat_n_stream(f), gauden_n_stream(g)); return NULL; } for (i = 0; i < feat_n_stream(f); i++) { if (feat_stream_len(f, i) != gauden_stream_len(g, i)) { E_ERROR("Feature stream(%d) length mismatch: feat(%d), gauden(%d)\n", feat_stream_len(f, i), gauden_stream_len(g, i)); return NULL; } } if (beam > 1.0) { E_ERROR("mgaubeam > 1.0 (%e)\n", beam); return NULL; } am = (acoustic_t *) ckd_calloc (1, sizeof(acoustic_t)); am->fcb = f; am->gau = g; am->sen = s; am->mgaubeam = (beam == 0.0) ? LOGPROB_ZERO : logs3(beam); if (am->mgaubeam > 0) am->mgaubeam = 0; am->tot_mgau_eval = 0; am->tot_dist_valid = 0.0; am->dist_valid = (am->mgaubeam <= LOGPROB_ZERO) ? NULL : (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); if (f->compute_feat) { /* Input is MFC cepstra; feature vectors computed from that */ am->mfc = (float32 **) ckd_calloc_2d (maxfr, feat_cepsize(am->fcb), sizeof(float32)); am->feat = feat_array_alloc (f, 1); } else { /* Input is directly feature vectors */ am->mfc = NULL; am->feat = feat_array_alloc (f, maxfr); } am->dist = (int32 *) ckd_calloc (g->max_n_mean, sizeof(int32)); am->gauden_active = bitvec_alloc (g->n_mgau); am->senscr = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); am->senscale = (int32 *) ckd_calloc (maxfr, sizeof(int32)); am->sen_active = bitvec_alloc (s->n_sen); return am; } static int32 senactive_to_mgauactive (acoustic_t *am) { int32 n, s; gauden_t *gau; senone_t *sen; sen = am->sen; gau = am->gau; bitvec_clear_all(am->gauden_active, gau->n_mgau); n = 0; for (s = 0; s < sen->n_sen; s++) { if (bitvec_is_set (am->sen_active, s)) { bitvec_set (am->gauden_active, sen->sen2mgau[s]); n++; } } return n; } int32 acoustic_eval (acoustic_t *am, int32 frm) { senone_t *sen; gauden_t *gau; int32 m, f, s, best, bestgau; int32 i, j, k; float32 **fv; float32 **mfc; sen = am->sen; gau = am->gau; if (am->mfc) { mfc = am->mfc + frm; am->fcb->compute_feat(am->fcb, mfc, am->feat[0]); fv = am->feat[0]; } else { fv = am->feat[frm]; } /* Identify the active mixture Gaussians */ if (senactive_to_mgauactive(am) == 0) E_FATAL("No states active\n"); /* Since we're going to accumulate into senscr for each feature stream */ memset (am->senscr, 0, sen->n_sen * sizeof(int32)); /* Evaluate all senones; FOR NOW NOT YET OPTIMIZED TO JUST THE ACTIVE ONES */ best = MAX_NEG_INT32; for (m = 0; m < gau->n_mgau; m++) { if (bitvec_is_set (am->gauden_active, m)) { for (f = 0; f < gau->n_feat; f++) { k = gauden_dist (gau, m, f, fv[f], am->dist); if (am->dist_valid) { /* Determine set of active mgau components based on pruning beam */ bestgau = MAX_NEG_INT32; for (i = 0; i < k; i++) if (am->dist[i] > bestgau) bestgau = am->dist[i]; j = 0; for (i = 0; i < k; i++) { if (am->dist[i] >= bestgau + am->mgaubeam) { am->dist_valid[j++] = i; } } am->n_dist_valid = j; k = j; am->tot_dist_valid += j; am->tot_mgau_eval += 1; } #if 1 for (i = 0; i < sen->mgau2sen[m].n_sen; i++) { s = sen->mgau2sen[m].sen[i]; if (bitvec_is_set (am->sen_active, s)) am->senscr[s] += senone_eval (sen, s, f, am->dist, am->dist_valid, k); } #else senone_eval_all (sen, m, f, am->dist, am->dist_valid, k, am->senscr); #endif } /* Find the best senone score so far */ for (i = 0; i < sen->mgau2sen[m].n_sen; i++) { s = sen->mgau2sen[m].sen[i]; if (bitvec_is_set (am->sen_active, s) && (am->senscr[s] > best)) best = am->senscr[s]; } } } /* CD-CI likelihood-interpolation (later) */ /* Normalize senone score by subtracting the best */ for (s = 0; s < sen->n_sen; s++) if (bitvec_is_set (am->sen_active, s)) am->senscr[s] -= best; return best; } <file_sep>/archive_s3/s3/src/tests/hub4/Makefile # ==================================================================== # # Sphinx III # # ==================================================================== TOP=`(cd ../../..; pwd)` DIRNAME=src/tests BUILD_DIRS = ALL_DIRS= $(BUILD_DIRS) # H = # LIVEDECSRCS = # MAINSRCS = # OTHERSRCS = main.c # LIVEDECOBJS = $(LIVEDECSRCS:.c=.o) $(BASESRCS:.c=.o) FILES = Makefile LIBNAME= tests BINDIR = $(TOP)/bin/$(MACHINE) hub4_flatunigram: rm -f gmake-hub4_flatunigram.results /bin/cp ARGS.hub4 ARGS.hub4_flatunigram echo "-lmfn /lab/speech/sphinx4/data/hub4_model/hub4.flat_unigram.lm.DMP" >> ARGS.hub4_flatunigram echo "-matchfn hub4_flatunigram.match" >> ARGS.hub4_flatunigram $(BINDIR)/s3decode-anytopo ARGS.hub4_flatunigram > gmake-hub4_flatunigram.results $(BINDIR)/align -ref hub4.ref -hyp hub4_flatunigram.match > hub4_flatunigram.align hub4_trigram: rm -f gmake-hub4_trigram.results /bin/cp ARGS.hub4 ARGS.hub4_trigram echo "-lmfn /lab/speech/sphinx4/data/hub4_model/language_model.arpaformat.DMP.Z" >> ARGS.hub4_trigram echo "-matchfn hub4_trigram.match" >> ARGS.hub4_trigram $(BINDIR)/s3decode-anytopo ARGS.hub4_trigram > gmake-hub4_trigram.results $(BINDIR)/align -ref hub4.ref -hyp hub4_trigram.match > hub4_trigram.align <file_sep>/archive_s3/s3.0/exp/gauden/Makefile # # Makefile # # HISTORY # # 05-Mar-99 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # VPATH = .:.. include ../../Makefile.defines gausubvq: gausubvq.c $(CC) $(CFLAGS) -o gausubvq.beta gausubvq.c $(OBJS) -lmain -lmisc -lfeat -lio -lutil -lm gautest: gautest.c subvq.c $(CC) $(CFLAGS) -o gautest.beta gautest.c subvq.c $(OBJS) -lmain -lmisc -lfeat -lio -lutil -lm clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/archive_s3/s3/src/libs3decoder/wid.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * wid.c -- Mapping word-IDs between LM and dictionary. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "wid.h" s3lmwid_t *wid_dict_lm_map (dict_t *dict, lm_t *lm) { int32 u, n; s3wid_t w; s3lmwid_t *map; assert (dict_size(dict) > 0); map = (s3lmwid_t *) ckd_calloc (dict_size(dict), sizeof(s3lmwid_t)); for (n = 0; n < dict_size(dict); n++) map[n] = BAD_S3LMWID; n = 0; for (u = 0; u < lm_n_ug(lm); u++) { w = dict_wordid (dict, lm_wordstr(lm, u)); lm_lmwid2dictwid(lm, u) = w; if (NOT_S3WID(w)) { n++; } else { if (dict_filler_word (dict, w)) E_ERROR("Filler dictionary word '%s' found in LM\n", lm_wordstr(lm, u)); if (w != dict_basewid (dict, w)) { E_ERROR("LM word '%s' is an alternative pronunciation in dictionary\n", lm_wordstr(lm, u)); w = dict_basewid (dict, w); lm_lmwid2dictwid(lm, u) = w; } for (; IS_S3WID(w); w = dict_nextalt(dict, w)) map[w] = (s3lmwid_t) u; } } if (n > 0) E_INFO("%d LM words not in dictionary; ignored\n", n); return map; } int32 wid_wordprob2alt (dict_t *dict, wordprob_t *wp, int32 n) { int32 i, j; s3wid_t w; for (i = 0, j = n; i < n; i++) { w = wp[i].wid; for (w = dict_nextalt (dict, w); IS_S3WID(w); w = dict_nextalt (dict, w)) { wp[j].wid = w; wp[j].prob = wp[i].prob; j++; } } return j; } <file_sep>/archive_s3/s3.0/pgm/timealign/align.h /* * align.h -- Time alignment module. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 11-Nov-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _TIMEALIGN_H_ #define _TIMEALIGN_H_ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include <libfeat/feat.h> #include <libmain/mdef.h> #include <libmain/dict.h> #include <libmain/tmat.h> #include <libmain/am.h> #include <libmain/wnet2pnet.h> /* Collection of knowledge sources and working data structures for the alignment */ typedef struct { mdef_t *mdef; /* HMM model definition */ dict_t *dict; /* Pronunciation dictionary */ acoustic_t *am; /* Acoustic models; gaussian density codebooks/senones */ tmat_t *tmat; /* HMM transition matrices */ glist_t pnet; /* The phone net being searched */ pnode_t *pstart; /* Dummy initial pnode in pnet */ pnode_t *pend; /* Dummy final pnode in pnet */ glist_t pactive; /* List of active pnodes in any frame (subset of pnodes in pnet); updated at the end of each frame to reflect the active set in the next frame */ glist_t hist; /* Viterbi history accumulated during the search */ corpus_t *insent; /* Input transcript corpus file */ FILE *outsentfp; /* Output transcript file */ } kb_t; /* * Start an alignment with the given phone net. The process starts with the successors * of the dummy pnode pstart. These are the initial set of active pnodes. Further, the * set of active senones is flagged in kb->am->sen_active. * Return value: 0 if successful, -1 otherwise. */ int32 align_start (kb_t *kb, /* In/Out: (See structure above.) */ char *uttid); /* * Step the phone net through one frame of Viterbi evaluation. The given list of active * pnodes are evaluated, pruned according to the given beamwidth, and cross-pnode * transitions performed. * Return value: 0 if successful, -1 if any error occurred. */ int32 align_frame (kb_t *kb, /* In/Out: kb->am->senscr should contain senone scores for this frame before calling this function. Upon return, kb->am->sen_active is updated to reflect the active senones for the next frame. */ int32 beam, /* In: Pruning beamwidth for determining active pnodes at the end of this frame, and also to determine which states are entered in the Viterbi history */ int32 frm, /* In: The current frame no. */ char *uttid); /* * End of the alignment. Cleanup as necessary. Backtrace through the Viterbi history to * find the best alignment. * Return value: State/frame alignment. This is a list of hyp_t nodes with word, phone * position, and state position encoded in the id field. Use other functions listed here * to interpret the results. Use align_hypfree to free the structure. * */ glist_t align_end (kb_t *kb, /* In/Out: Working data structures (pactive and hist) cleaned up */ int32 frm, /* In: Total number of frames searched */ char *uttid); /* In: Utterance ID */ /* * Generate and return a word-level segmentation from the state-level segmentation * returned by align_end(). This is a list of hyp_t nodes with dictionary word-id in the * id field. Use align_hypfree to free the returned information. */ glist_t align_st2wdseg (kb_t *kb, /* In: The usual */ glist_t stseg); /* In: State segmentation from which the word segmentation is built up */ /* * Write state segmentation in Sphinx-II format (always BIG-ENDIAN): * Format: * (int32)(No. of frames) * (int16)State information for each frame, consisting of: * (CIphone ID) * (kb->mdef->n_emit_state) + (state-ID within phone); with * the MSB (bit-15) turned on if this is the first frame of each new phone. */ void align_write_s2stseg (kb_t *kb, /* In: Reference databases */ glist_t stseg,/* In: State-level Viterbi hypothesis returned by align_end */ char *file, /* In: Output filename */ char *uttid); /* In: For logging purposes */ /* * Write word level segmentation; arguments similar to align_write_s2stseg(), but * with a word segmentation input. */ void align_write_wdseg (kb_t *kb, glist_t wdseg, char *file, char *uttid); /* Write word level sentence transcript; arguments similar to align_write_wdseg() */ void align_write_outsent (kb_t *kb, glist_t wdseg, FILE *fp, char *uttid); /* * Free the segmentation hyp list returned by align_end() or align_st2wdseg(). */ void align_hypfree (glist_t hyp); #endif <file_sep>/pocketsphinx/src/libpocketsphinx/tokentree.h /* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @name tokentree.h * @brief Token-passing search algorithm * @author <NAME> <<EMAIL>> */ #ifndef __TOKENTREE_H__ #define __TOKENTREE_H__ /* System includes. */ /* SphinxBase includes. */ #include <listelem_alloc.h> #include <heap.h> /* Local includes. */ /** * Token, which represents a particular path through the decoding graph. */ typedef struct token_s token_t; struct token_s { int32 pathcost ; /**< Cost (-score) of the path ending with this token. */ int32 arcid; /**< Head arc (or word) represented by this token. */ int16 frame; /**< Last frame in which this token was active. */ int16 misc; /**< Miscellaneous data. */ token_t *prev; /**< Previous token in this path. */ }; /** * Tree (lattice) of tokens, representing all paths explored so far. */ typedef struct tokentree_s tokentree_t; struct tokentree_s { int refcount; heap_t *leaves; /**< Leaves (active tokens). */ listelem_alloc_t *token_alloc; /**< Allocator for tokens. */ }; /** * Create a new token tree. */ tokentree_t *tokentree_init(void); /** * Retain a pointer to a token tree. */ tokentree_t *tokentree_retain(tokentree_t *tree); /** * Release a pointer to a token tree. */ int tokentree_free(tokentree_t *tree); /** * Create a new token and add it to the tree as a leaf. * * This has the side effect of removing prev from the set of leaves. */ token_t *tokentree_add(tokentree_t *tree, int32 pathcost, int32 arcid, token_t *prev); /** * Prune leaves from the tree with costs greather than maximum. */ int tokentree_prune(tokentree_t *tree, int32 maxcost); /** * Prune leaves from the tree leaving only the top N. */ int tokentree_prune_topn(tokentree_t *tree, int32 n); /** * Reset tokentree, removing all history. */ int tokentree_clear(tokentree_t *tree); #endif /* __TOKENTREE_H__ */ <file_sep>/misc_scripts/trans_select.sh #!/bin/sh if [ $# != 1 ]; then echo "Usage: $0 MEETING" exit 1 fi meeting=$1 ./trans_select/selectICSI_trans.pl -removemixture y \ -removenoise y -removeoverlap n \ -incontrolfile transcripts.corr/$meeting.mrt.am.ctl \ -intranswosil transcripts.corr/$meeting.mrt.am.wosil.trans \ -outcontrolfile $meeting/$meeting.mrt.ctl.out \ -outtranswosil $meeting/$meeting.mrt.am.wosil.trans.out \ -outtranswsil $meeting/$meeting.mrt.am.wsil.trans.out \ -outtransremoved $meeting/$meeting.mrt.am.wosil.trans.removed ./icsi-partition.pl $meeting/$meeting.mrt.ctl.out \ $meeting/$meeting.mrt.am.wsil.trans.out $meeting <file_sep>/CLP/src/Clustering_print.cc //-------------------------------------------- // Clustering.cc // Implementation of the clustering procedure //-------------------------------------------- // Copyright (c) sept 1999 <NAME> <EMAIL> All rights reserved. //-------------------------------------------------------------------------------------------------------- #include <cstdlib> #include <iomanip> #include <cstdio> #include <cassert> #include <iostream> #include <algorithm> #include <list> using namespace std; #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include "common_lattice.h" #include "Link.h" #include "Clustering.h" #include "Prons.h" #include "Similarities.h" inline double maximf(double a, double b){ if (a>b) return a; else return b; } inline double averagef(double a, double b, int m, int n){ return (m*a + b*n)/(m+n); } Clustering::Clustering(): lat_ptr((Lattice *)0) {} Clustering::Clustering(const Lattice* from_lattice, const Prons& P): lat_ptr(from_lattice){ IntIntIntMap removed; assert(removed.empty()); assert(C.empty()); unsigned E = ((Lattice* )lat_ptr)->no_links(); // MOD 7/3/2000 - cast added unsigned N = ((Lattice* )lat_ptr)->no_nodes(); // MOD 7/3/2000 - cast added bool use_time_info = ((Lattice* )lat_ptr)->has_time_info(); // MOD 7/3/2000 - cast added int EPS_idx = ((Prons&) P).get_idx(EPS); // MOD 6/30/2000 - cast added int START_WD_idx = ((Prons&) P).get_idx(START_WD); // MOD 6/30/2000 - cast added int END_WD_idx = ((Prons&) P).get_idx(END_WD); // MOD 6/30/2000 - cast added ClusterListIt before_end; int count_links_kept = 0; for (unsigned i = 0; i < E; i++){ Link& curr_link = (Link &)lat_ptr->link(i); // MOD 6/30/2000 - cast added if (curr_link.is_pruned() == 0){ count_links_kept++; bool found = false; int widx = curr_link.Word_idx(); if (widx != END_WD_idx && widx != EPS_idx && widx != START_WD_idx){ // don't form clusters for !SENT_START, !SENT_END and !NULL if (C.begin() != C.end()){ before_end = C.end(); before_end--; if (use_time_info){ float starttime = curr_link.start_time(); float endtime = curr_link.end_time(); assert (starttime >=0 && endtime >=0); if (before_end == C.begin()){ if (endtime == (*before_end).end_time() && (*before_end).match_start_word(starttime,widx)){ (*before_end).add_link(curr_link); found = true; } } else { for (ClusterListIt it = before_end; it != C.begin(); --it){ if (endtime == (*it).end_time()){ if ((*it).match_start_word(starttime,widx)){ (*it).add_link(curr_link); found = true; break; } } else break; } } } else{ int approx_start_time = curr_link.start_node().Max_dist(); int approx_end_time = curr_link.end_node().Max_dist(); for (ClusterListIt it = C.begin(); it != C.end(); it++){ if (widx == (*it).wordidx() && approx_start_time == (*it).approx_start_time() && approx_end_time == (*it).approx_end_time()){ (*it).add_link(curr_link); found = true; break; } } } } if (found == false){ Cluster c(C.size(),lat_ptr); c.add_link(curr_link); C.insert(C.end(),c); } } else if (widx == EPS_idx) removed[pair<int,int>(curr_link.Start_node_id(), curr_link.End_node_id())] = 1; } else removed[pair<int,int>(curr_link.Start_node_id(), curr_link.End_node_id())] = 1; } no_links = count_links_kept; unsigned no_clusters = C.size(); IdsMatrix ordered; ordered.resize(no_clusters); for (int i = 0; i < no_clusters; i++) ordered[i].resize(no_clusters); for (int i = 0; i < no_clusters; i++) for (int j = 0; j < no_clusters; j++) assert(ordered[i][j] == 0); // record the partial constrains if (use_time_info){ for (ClusterListConstIt it1 = C.begin(); it1 != C.end(); it1++){ unsigned id1 = (*it1).Id(); ClusterListConstIt it2 = it1; it2++; while(it2 != C.end()){ unsigned id2 = (*it2).Id(); assert(id1 < id2); if ( ((Cluster& )(*it1)).end_time() <= ((Cluster& )(*it2)).start_time()){ // MOD 7/3/2000 - cast added int answer = ((Cluster& )(*it1)).is_less(*it2, removed); // MOD 7/3/2000 - cast added if (answer >=1) { // MOD 7/3/2000 - added "{" //cout << id1 << " and " << id2 << "->" << answer << endl; ordered[id1][id2] = 1; } // MOD 7/3/2000 - added "}" } it2++; } } } else{ for (ClusterListConstIt it1 = C.begin(); it1 != C.end(); it1++){ unsigned id1 = (*it1).Id(); ClusterListConstIt it2 = C.begin(); while(it2 != C.end()){ unsigned id2 = (*it2).Id(); if (id1 != id2){ int answer = ((Cluster& )(*it1)).is_less(*it2, removed); // MOD 7/3/2000 - cast added if (answer>=1){ cout << id1 << " and " << id2 << "->" << answer << endl; ordered[id1][id2] = 1; } } it2++; } } } // do the transitive closure if (use_time_info){ for (int i = 0; i < no_clusters; i++) for (int j = i+1; j < no_clusters; j++) for (int k = i+1; k < j; k++) if (ordered[i][k] == 1 && ordered[k][j] == 1) ordered[i][j] = 1; } else{ for (int i = 0; i < no_clusters; i++) for (int j = 0; j < no_clusters; j++) for (int k = 0; k < no_clusters; k++) if (ordered[i][k] == 1 && ordered[k][j] == 1) ordered[i][j] = 1; } assert(constraints.empty()); // record the partial order for (int i = 0; i < no_clusters; i++) for (int j = 0; j < no_clusters; j++) if (ordered[i][j]){ constraints[pair<int,int>(i,j)]=1; } } // //////////////////////////////////////////////////////////////////////////////// void Clustering::print(const Prons& P, bool print_links, bool print_words){ for (ClusterListIt it = C.begin(); it != C.end(); it++){ (*it).print(P, print_links, print_words); cout << endl; } } // //////////////////////////////////////////////////////////////////////////////// void Clustering::fill_words(){ for (ClusterListConstIt it = C.begin(); it != C.end(); it++) ((Cluster& )(*it)).fill_cwords(); // MOD 7/3/2000 - cast added return; // MOD 6/30/2000 - 1 removed } // ////////////////////////////////////////////////////////////////////////////////// void Clustering::go_cluster(const Prons& P, const int stage, const int mode, const bool constrained) { static IntIntDblMap linkTimeSim; assert(linkTimeSim.empty()); static IntIntDblMap wordPhSim; static IntIntIntMap are_less; unsigned no_clusters = C.size(); vector<ClusterListIt> most_similar(no_clusters); // for each cluster keeps a pointer to the most_similar cluster to it // the actual similarity values are to be found in 'ordered' for (int i = 0; i<no_clusters; i++) most_similar[i] = C.end(); DblMatrix SIM; SIM.resize(no_clusters); for (int i = 0; i < no_clusters; i++) SIM[i].resize(no_clusters); for (int i = 0; i < no_clusters; i++) for (int j = 0; j < no_clusters; j++) assert(SIM[i][j] == 0); for (IntIntIntMapIt it = constraints.begin(); it!= constraints.end(); ++it){ unsigned firstnode = (*it).first.first; unsigned secondnode = (*it).first.second; assert(firstnode < no_clusters && secondnode < no_clusters); SIM[firstnode][secondnode] = -1; } for (int i = 0; i < no_clusters; i++) SIM[i][i] = -1; // add in SIM the similarity values between the compatible clusters for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ unsigned id1 = (*it1).Id(); double max_sim_row = 0; ClusterListIt itmax_row=C.end(); for (ClusterListIt it2 = C.begin(); it2 != C.end(); it2++){ unsigned id2 = (*it2).Id(); double sim = 0; if (id1 < id2){ if (stage == 1){ if (SIM[id1][id2] == 0 && SIM[id2][id1] == 0) if ((*it1).wordidx() == (*it2).wordidx()) sim = compute_TIME_sim(it1,it2,linkTimeSim,mode,constrained); } else if (stage == 2){ // inter-word clustering w/ phonetic similarity if (SIM[id1][id2] == 0 && SIM[id2][id1] == 0){ sim = compute_PHON_sim(it1,it2, (Prons&) P,wordPhSim,mode,1, constrained); // MOD 7/3/2000 - cast added } } else if (stage == 3){ // inter-word clustering w/o phonetic similarity if (SIM[id1][id2] == 0 && SIM[id2][id1] == 0){ sim = compute_PHON_sim(it1,it2, (Prons&) P,wordPhSim,mode,0, constrained); // MOD 7/3/2000 - cast added } } else if (stage == 4){ // the last clustering stage if (SIM[id1][id2] == 0 && SIM[id2][id1] == 0){ if ((*it1).Max_time() < (*it2).Min_time()){ if( ((Lattice* )lat_ptr)->has_time_info() && ((*it2).Min_time() - (*it1).Max_time() > 0.5)){ // MOD 7/3/2000 - cast added SIM[id1][id2] = -1; sim = -1; } else if ( ((Lattice* )lat_ptr)->has_time_info() == 0 && ((*it2).Min_time() - (*it1).Max_time() > 20)){ // MOD 7/3/2000 - cast added SIM[id1][id2] = -1; sim = -1; } else{ unsigned order = (*it1).compare_less(*it2,are_less,10); if (order == 1){ SIM[id1][id2] = -1; sim = -1; } else{ sim = compute_PHON_sim(it1,it2, (Prons&)P,wordPhSim,mode,0, constrained); // MOD 7/3/2000 - cast added } } } else{ if( ((Lattice* )lat_ptr)->has_time_info() && ((*it1).Min_time() - (*it2).Max_time() > 0.5)){ // MOD 7/3/2000 - cast added SIM[id2][id1] = -1; sim = -1; } else if (((Lattice* )lat_ptr)->has_time_info() == 0 && ((*it1).Min_time() - (*it2).Max_time() > 20)){ // MOD 7/3/2000 - cast added SIM[id2][id1] = -1; sim = -1; } else{ unsigned order = (*it2).compare_less(*it1, are_less, 10); if (order == 1){ SIM[id2][id1] = -1; sim = -1; } else{ sim = compute_PHON_sim(it1,it2, (Prons&)P,wordPhSim,mode,0, constrained); // MOD 7/3/2000 - cast added } } } } } else cerr << "ERROR in go_cluster::stage " << stage << " is not supported\n"; } else if (id1 > id2) if (SIM[id2][id1] > 0) sim = SIM[id2][id1]; if (sim > 0){ SIM[id1][id2] = sim; if (sim > max_sim_row){ max_sim_row = sim; itmax_row = it2; } } } if (itmax_row != C.end()) most_similar[id1] = itmax_row; } // Explanation for the values to be found in "SIM": // SIM[i][j] is 0 if there is no partial constraint between cluster i and cluster j, // but also there is no reason to compute the similarity value because they don't correspond to the same word // SIM[i][j] is -1 if there is a partial constraint between cluster i and cluster j; it can also be 0 if the similarity is 0 // SIM[i][j] has a value between 0 and 1 if the two clusters are potential candidates for merging; the value is the similarity vector<unsigned> eliminated(no_clusters); // keeps track of the clusters that were eliminated due to merging for (int i = 0; i<no_clusters; i++) eliminated[i] = 0; bool merge = 1; int count_steps = 0; bool print_links = 1; bool print_words = 1; if (stage == 1) print_words = 0; while(merge){ double max_sim = 0; ClusterListIt itmax1, itmax2; for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ unsigned id1 = (*it1).Id(); if (most_similar[id1] != C.end()){ ClusterListIt it2 = most_similar[id1]; unsigned id2 = (*it2).Id(); if (SIM[id1][id2] > max_sim){ max_sim = SIM[id1][id2]; itmax1 = it1; itmax2 = it2; } } } if (max_sim == 0) merge = 0; else{ count_steps++; unsigned id1 = (*itmax1).Id(); unsigned id2 = (*itmax2).Id(); // id1, id2 are the ids of the clusters to be merged if (id2 < id1){ unsigned tmp = id1; id1 = id2; id2 = tmp; ClusterListIt ittmp = itmax1; itmax1 = itmax2; itmax2 = ittmp; } cout << "==========================================\n"; cout << "STEP " << count_steps << endl; cout << "==========================================\n"; cout << endl; (*itmax1).print(P,print_links,print_words); cout << endl; (*itmax2).print(P,print_links,print_words); cout << endl; (*itmax1).merge_with(*itmax2, stage); IdsList Liv, Ljv, Lio, Ljo; eliminated[id2] = 1; for (int i = 0; i< no_clusters; i++){ if (eliminated[i] || i == id1 || i == id2) continue; // update the similarities if (SIM[i][id1]>0 && SIM[id1][i]>0 && SIM[i][id2]>0 && SIM[id2][i]>0){ if (mode == 0) SIM[i][id1] = maximf(SIM[i][id1], SIM[i][id2]); else if (mode == 1){ unsigned no_links1 = (*itmax1).no_links(); unsigned no_links2 = (*itmax2).no_links(); SIM[i][id1] = averagef(SIM[i][id1], SIM[i][id2], no_links1, no_links2); } else cerr << "ERROR in go_cluster::mode " << mode << " is not supported\n"; SIM[id1][i] = SIM[i][id1]; } // update the partial order if (SIM[i][id1] == -1) Liv.push_front(i); if (SIM[i][id2] == -1) Ljv.push_front(i); if (SIM[id1][i] == -1) Lio.push_front(i); if (SIM[id2][i] == -1) Ljo.push_front(i); if (SIM[i][id2] == -1) SIM[i][id1] = -1; if (SIM[id2][i] == -1) SIM[id1][i] = -1; } for (IdsListConstIt i = Liv.begin(); i!= Liv.end(); ++i) for (IdsListConstIt j = Ljo.begin(); j!= Ljo.end(); ++j) SIM[*i][*j] = -1; for (IdsListConstIt i = Lio.begin(); i!= Lio.end(); ++i) for (IdsListConstIt j = Ljv.begin(); j!= Ljv.end(); ++j) SIM[*j][*i] = -1; // update "most_similar" if (constrained){ for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ if (it1 != itmax2){ unsigned id_source = (*it1).Id(); if ((SIM[id_source][id1] == 0 && SIM[id1][id_source] > -1 && SIM[id_source][id2] > 0 && SIM[id2][id_source] > -1) || (SIM[id_source][id2] == 0 && SIM[id2][id_source] > -1 && SIM[id_source][id1] > 0 && SIM[id1][id_source] > -1)){ if (stage == 1) SIM[id_source][id1]= compute_TIME_sim(it1,itmax1,linkTimeSim,mode,constrained); else if (stage== 2 || stage ==4) SIM[id_source][id1]= compute_PHON_sim(it1,itmax1, (Prons&)P,wordPhSim,mode,1, constrained); // MOD 7/3/2000 - cast added else if (stage == 3) SIM[id_source][id1]= compute_PHON_sim(it1,itmax1, (Prons&)P,wordPhSim,mode,0, constrained); // MOD 7/3/2000 - cast added if (SIM[id_source][id1] > 0 && SIM[id1][id_source] > -1){ SIM[id1][id_source] = SIM[id_source][id1]; } } } } } for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ if (it1 != itmax2){ unsigned id_source = (*it1).Id(); if (most_similar[id_source] != C.end()){ unsigned id_closest = (*most_similar[id_source]).Id(); if (SIM[id_source][id_closest] == -1 || SIM[id_closest][id_source] == -1 || id_source == id1 || id_closest == id1 || id_closest == id2){ // if they became ordered after merging, recompute the most similar candidate for it1 double max_sim_row = 0; ClusterListIt itmax_row; for (ClusterListIt i = C.begin(); i != C.end(); i++){ if (i != itmax2){ unsigned id = (*i).Id(); double new_val = SIM[id_source][id]; if (new_val >= 0 && SIM[id][id_source] >=0 && new_val > max_sim_row){ max_sim_row = new_val; itmax_row = i; } } } if (max_sim_row > 0){ most_similar[id_source] = itmax_row; } else{ most_similar[id_source] = C.end(); } } else { if (SIM[id_source][id_closest] < SIM[id_source][id1] && SIM[id1][id_source] > -1) most_similar[id_source] = itmax1; } } else{ if (constrained && SIM[id_source][id1] > 0 && SIM[id1][id_source] > -1) most_similar[id_source] = itmax1; } } } C.erase(itmax2); } } IntIntIntMapIt b = constraints.begin(); IntIntIntMapIt e = constraints.end(); constraints.erase(b,e); IntIntDblMapIt bd = linkTimeSim.begin(); IntIntDblMapIt ed = linkTimeSim.end(); linkTimeSim.erase(bd,ed); unsigned count_row = 0; for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ unsigned count_col = 0; unsigned id1 = (*it1).Id(); for (ClusterListIt it2 = C.begin(); it2 != C.end(); it2++){ if (it2 != it1){ unsigned id2 = (*it2).Id(); if (SIM[id1][id2] == -1){ constraints[pair<int,int>(count_row,count_col)]=1; } } count_col++; } count_row++; } count_row = 0; for (ClusterListIt it1 = C.begin(); it1 != C.end(); it1++){ (*it1).setId(count_row); count_row++; } return; // MOD 7/3/2000 - 1 removed } // //////////////////////////////////////////////////////////////////////////////// double Clustering::compute_TIME_sim(ClusterListConstIt itc1, ClusterListConstIt itc2, IntIntDblMap& linkTimeSim, const int mode, const bool constrained) { double sum = 0; double max = 0; LnProb total_prob = ((Lattice* )lat_ptr)->Total_prob(); // MOD 7/3/2000 - cast added bool has_time_info = ((Lattice* )lat_ptr)->has_time_info(); // MOD 7/3/2000 - cast added Cluster& c1 = (Cluster&) *itc1; // MOD 7/3/2000 - cast added Cluster& c2 = (Cluster&) *itc2; // MOD 7/3/2000 - cast added if (constrained){ int best_link_1 = c1.Best_link(); int best_link_2 = c2.Best_link(); if (has_time_info){ if (compute_time_overlap(lat_ptr->link(best_link_1).start_time(),lat_ptr->link(best_link_1).end_time(),lat_ptr->link(best_link_2).start_time(),lat_ptr->link(best_link_2).end_time()) == 0) return 0; } else{ if (compute_time_overlap_ph(lat_ptr->link(best_link_1).start_node().Max_dist(),lat_ptr->link(best_link_1).end_node().Max_dist(),lat_ptr->link(best_link_2).start_node().Max_dist(),lat_ptr->link(best_link_2).end_node().Max_dist()) <= 0) return 0; } } for (IdsListConstIt it1 = c1.clinks.begin(); it1!= c1.clinks.end(); ++it1){ double diff = lat_ptr->link(*it1).Pscore() - total_prob; if (fabs(diff) < exp(-20)) diff = -0.0001; double p1 = exp(diff); for (IdsListConstIt it2 = c2.clinks.begin(); it2!= c2.clinks.end(); ++it2){ double sim = 1; if (has_time_info){ IntInt N; N.first = *it1; N.second = *it2; IntIntDblMapIt it = linkTimeSim.find(N); if (it == linkTimeSim.end()){ // the time overlap between these two links has not been computed before sim = compute_time_overlap(lat_ptr->link(*it1).start_time(),lat_ptr->link(*it1).end_time(),lat_ptr->link(*it2).start_time(),lat_ptr->link(*it2).end_time()); linkTimeSim[N] = sim; linkTimeSim[pair<int,int>(*it2,*it1)]=sim; } else sim = linkTimeSim[N]; } diff = lat_ptr->link(*it2).Pscore() - total_prob; if (fabs(diff) < exp(-20)) diff = -0.0001; double p2 = exp(diff); sim *= p1*p2; if (mode == 0){ if (sim > max) max = sim; } else if (mode == 1){ sum += sim; } else cerr << "ERROR in compute_TIME_sim_with():" << mode << " is not supported \n"; } } if (mode == 0) return max; else { int total = c1.clinks.size() * c2.clinks.size(); return sum/total; } } // /////////////////////////////////////////////////////////////////////////////////// double Clustering::compute_PHON_sim(ClusterListConstIt cit1, ClusterListConstIt cit2, Prons& P, IntIntDblMap& wordPhSim, const int mode, bool use_phon_info, bool constrained) { bool print = false; double max = 0; double sum = 0; LnProb total_prob = ((Lattice* )lat_ptr)->Total_prob(); // MOD 7/3/2000 - cast added Cluster& c1 = (Cluster&) *cit1; // MOD 7/3/2000 - cast added Cluster& c2 = (Cluster&) *cit2; // MOD 7/3/2000 - cast added if (constrained) if (compute_time_overlap_ph(c1.Min_time(),c1.Max_time(),c2.Min_time(),c2.Max_time()) < 0) return 0; for (IntDblMapConstIt it1 = c1.cwords.begin(); it1 != c1.cwords.end(); ++it1){ double diff = (*it1).second - total_prob; if (fabs(diff) < exp(-20)) diff = -0.0001; double p1 = exp(diff); for (IntDblMapConstIt it2 = c2.cwords.begin(); it2 != c2.cwords.end(); ++it2){ double diff = (*it2).second - total_prob; if (fabs(diff) < exp(-20)) diff = -0.0001; double p2 = exp(diff); IntInt N; N.first = (*it1).first; N.second = (*it2).first; double sim =1; if (use_phon_info){ IntIntDblMapIt it = wordPhSim.find(N); if (it == wordPhSim.end()){ // the phonetic similarity between these two words has not been computed before const string& pron1 = P.get_pron((*it1).first); // MOD 6/30/2000 - const added const string& pron2 = P.get_pron((*it2).first); // MOD 6/30/2000 - const added if (pron1 == "" || pron2 == "" ) sim = compute_word_similarity(P.get_word((*it1).first),P.get_word((*it2).first)); else sim = compute_phonetic_similarity(pron1,pron2); wordPhSim[N] = sim; wordPhSim[pair<int,int>((*it2).first,(*it1).first)] = sim; } else sim = wordPhSim[N]; } sim *= p1*p2; if (mode == 0){ if (sim > max) max = sim; } else if (mode == 1){ sum += sim; } else cerr << "ERROR in compute_PHON_sim_with():" << mode << " is not supported \n"; } } if (mode == 0){ return max; } else { int total = c1.cwords.size()*c2.cwords.size(); return sum/total; } } // ////////////////////////////////////////////////////////////////////////////////////////////// int Clustering::no_words() { IntIntMap words; for (ClusterListIt it = C.begin(); it != C.end(); ++it){ Cluster& c = (*it); for (IdsListConstIt itl = c.clinks.begin(); itl!= c.clinks.end(); ++itl){ int idx = lat_ptr->link(*itl).Word_idx(); words[idx] = 1; } } return words.size(); } // ///////////////////////////////////////////////////////////////////////////////////////////// void Clustering::add_EPS(float DELweight) { LnProb total_prob = ((Lattice* )lat_ptr)->Total_prob(); // MOD 7/3/2000 - cast added cout << "TOTAL PROB : " << total_prob << endl; for (ClusterListIt it = C.begin(); it != C.end(); ++it){ Cluster& c = (*it); LnProb eps_prob; LnProb total_prob_cluster = 0; for (IntDblMapIt itw = c.cwords.begin(); itw != c.cwords.end(); itw++){ LnProb score = (*itw).second; assert(fabs(score -total_prob)< exp(-20) || (score < total_prob)); if (score > total_prob) cout << score << " ** " << total_prob << endl; score = exp(score - total_prob); (*itw).second = score; total_prob_cluster += score; } // put the remaining mass on EPS if (total_prob_cluster > 1 && fabs(total_prob_cluster - 1) < exp(-20)){ eps_prob = 0; } else if (total_prob_cluster < 1){ eps_prob = 1 - total_prob_cluster; eps_prob *= DELweight; c.cwords.insert(pair<int,double>(-1,eps_prob)); } } } // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Clustering::print_sausages_FSMformat(const string& outdir, const string& outfile, const string& infile, float lowEpsT, float highEpsT, float lowWordT, float highWordT, const Prons& P, bool output_fullpath) { bool std_out = false; string label; if (output_fullpath) label = infile; else { LineSplitter ls1("/"); ls1.Split(infile); label = ls1[ls1.NoWords()-1]; } LineSplitter ls("."); ls.Split(label); label = ls[0]; ostream* outCons; if (outfile == ""){ std_out = true; outCons = &cout; } else outCons = new ofstream (outfile.c_str(),ios::app); ofstream fout; if (outdir != ""){ string outfile = outdir + "/" + label + ".saus"; fout.open(outfile.c_str()); assert(fout); fout.setf(ios::left, ios::adjustfield); } // add SENT_START as the first cluster fout << setw(6) << 0 << setw(6) << 1 << setw(20) << START_WD.c_str() << setw(10) << 1 << endl; unsigned count = 1; string consensus(""); for (ClusterListConstIt it = C.begin(); it != C.end(); ++it){ Cluster& c = (Cluster&) (*it); // MOD 7/3/2000 - cast added LnProb score; // sort the words in decreasing order on their posterior probability IntDblVector v(c.cwords.size()); copy(c.cwords.begin(),c.cwords.end(),v.begin()); compW comp_words; sort (v.begin(), v.end(), comp_words); int wordidx_best = v[0].first; LnProb score_best = v[0].second; if (wordidx_best == -1){ // eps has the highest score; if (outdir != ""){ if (score_best > highEpsT) count--; else { int i; // MOD 7/3/2000 - declaration added (otherwise invalid outside "for") for (int i = 1; i< v.size(); ++i) if (v[i].second > lowWordT) break; if (i != v.size()){ fout << setw(6) << count << setw(6) << count+1 << setw(20) << "eps" << setw(10) << score_best << endl; for (int i = 1; i< v.size(); ++i) if (v[i].second > lowWordT){ const Word& w = P.get_word(v[i].first); // MOD 7/3/2000 - const added fout << setw(6) << count << setw(6) << count+1 << setw(20) << w.c_str() << setw(10) << v[i].second << endl; } } } } } else{ // a real word has the highest score const Word& w = P.get_word(wordidx_best); // MOD 7/3/2000 - const added consensus += w + " "; if (outdir != ""){ fout << setw(6) << count << setw(6) << count+1 << setw(20) << w.c_str() << setw(10) << score_best << endl; if (score_best <= highWordT){ for (int i = 1; i< v.size(); ++i) if (v[i].first >=0){ if (v[i].second > lowWordT){ const Word& w = P.get_word(v[i].first); // MOD 7/3/2000 - const added fout << setw(6) << count << setw(6) << count+1 << setw(20) << w.c_str() << setw(10) << v[i].second << endl; } } else{ if (v[i].second > lowEpsT) fout << setw(6) << count << setw(6) << count+1 << setw(20) << "eps" << setw(10) << v[i].second << endl; } } } } count++; } // add SENT_END and EPS fout << setw(6) << count << setw(6) << count+1 << setw(20) << END_WD.c_str() << setw(10) << 1 << endl; fout << setw(6) << count+1 << setw(6) << count+2 << setw(20) << EPS.c_str() << setw(10) << 1 << endl; // add an end state fout << count+2 << endl; *outCons << consensus << "\t(" << label << ")" << endl; if (outdir != ""){ fout.close(); } if (!std_out){ ((ofstream *)outCons)->close(); delete outCons; } return; // MOD 7/3/2000 - 1 removed } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Clustering::TopSort() { unsigned no_clusters = C.size(); IdsMatrix order; order.resize(no_clusters); for (int i = 0; i < no_clusters; i++) order[i].resize(no_clusters); for (IntIntIntMapIt it = constraints.begin(); it!= constraints.end(); ++it){ unsigned firstclust = (*it).first.first; unsigned secondclust = (*it).first.second; assert(firstclust < no_clusters && secondclust < no_clusters); order[firstclust][secondclust] = 1; } IdsList l; IdsVector color(no_clusters); for (int i=0; i<no_clusters; i++) color[i]=0; for (int i = 0; i < no_clusters; i++) if (color[i] == 0) DFS_visit(i,order,l,color); ClusterList C1; for (IdsListConstIt it = l.begin(); it!= l.end(); ++it) for (ClusterListIt cit = C.begin(); cit != C.end(); ++cit) if ((*cit).Id() == (*it)){ Cluster c1 = *cit; C1.push_back(c1); C.erase(cit); break; } swap(C,C1); unsigned count = 0; for (ClusterListIt cit = C.begin(); cit != C.end(); ++cit){ (*cit).setId(count); count++; } return; // MOD 7/3/2000 - 1 removed } // ///////////////////////////////////////////////////////////////////////////////////////////////////// void Clustering::DFS_visit(const unsigned startid, IdsMatrix& order, IdsList& l, IdsVector& color) { color[startid] = 1; IdsVector& v = order[startid]; for (unsigned i = 0; i< v.size(); i++) if (v[i] == 1 && color[i] == 0) DFS_visit(i, order, l, color); color[startid] = 2; l.push_front(startid); return; } <file_sep>/SphinxTrain/src/libs/liblapack_lite/config.c #include "dlamch.c" /* ======================================================================= */ /* The pow_di function was copied from f2c_lite.c */ #ifdef KR_headers double pow_di(ap, bp) doublereal *ap; integer *bp; #else double pow_di(doublereal *ap, integer *bp) #endif { double pow, x; integer n; unsigned long u; pow = 1; x = *ap; n = *bp; if(n != 0) { if(n < 0) { n = -n; x = 1/x; } for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return(pow); } /* ======================================================================= */ /* The lsame function was copied from blas_lite.c */ logical lsame_(char *ca, char *cb) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= LSAME returns .TRUE. if CA is the same letter as CB regardless of case. Arguments ========= CA (input) CHARACTER*1 CB (input) CHARACTER*1 CA and CB specify the single characters to be compared. ===================================================================== Test if the characters are equal */ /* System generated locals */ logical ret_val; /* Local variables */ static integer inta, intb, zcode; ret_val = *(unsigned char *)ca == *(unsigned char *)cb; if (ret_val) { return ret_val; } /* Now test for equivalence if both characters are alphabetic. */ zcode = 'Z'; /* Use 'Z' rather than 'A' so that ASCII can be detected on Prime machines, on which ICHAR returns a value with bit 8 set. ICHAR('A') on Prime machines returns 193 which is the same as ICHAR('A') on an EBCDIC machine. */ inta = *(unsigned char *)ca; intb = *(unsigned char *)cb; if (zcode == 90 || zcode == 122) { /* ASCII is assumed - ZCODE is the ASCII code of either lower o r upper case 'Z'. */ if (inta >= 97 && inta <= 122) { inta += -32; } if (intb >= 97 && intb <= 122) { intb += -32; } } else if (zcode == 233 || zcode == 169) { /* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or upper case 'Z'. */ if (inta >= 129 && inta <= 137 || inta >= 145 && inta <= 153 || inta >= 162 && inta <= 169) { inta += 64; } if (intb >= 129 && intb <= 137 || intb >= 145 && intb <= 153 || intb >= 162 && intb <= 169) { intb += 64; } } else if (zcode == 218 || zcode == 250) { /* ASCII is assumed, on Prime machines - ZCODE is the ASCII cod e plus 128 of either lower or upper case 'Z'. */ if (inta >= 225 && inta <= 250) { inta += -32; } if (intb >= 225 && intb <= 250) { intb += -32; } } ret_val = inta == intb; /* RETURN End of LSAME */ return ret_val; } /* lsame_ */ /* ======================================================================= */ int main(void) { double x; FILE* outputfile = fopen("lapack_config.h","w"); x = dlamch_("E"); fprintf(outputfile,"#define EPSILON %17.14g\n", x); x = dlamch_("S"); fprintf(outputfile,"#define SAFEMINIMUM %17.14g\n", x); x = dlamch_("P"); fprintf(outputfile,"#define PRECISION %17.14g\n", x); x = dlamch_("B"); fprintf(outputfile,"#define BASE %f\n", x); fclose(outputfile); return 0; } <file_sep>/scons/common.py import platform import os import fnmatch Import('javapath') Import('sphinx4') srcDir = os.path.normpath('../tools/common/src/java:../../') classDir = os.path.normpath('../../scons_build/classes/common') libpath = '..' + os.sep + 'tools' + os.sep + 'common' + os.sep + 'lib' + os.sep classpath = libpath + 'batch.jar' + os.pathsep classpath += libpath + 'dom4j-1.6.1.jar' + os.pathsep classpath += libpath + 'forms_rt_license.jar' + os.pathsep classpath += libpath + 'forms_rt.jar' + os.pathsep classpath += libpath + 'javolution.jar' + os.pathsep classpath += str(sphinx4[0]) env = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS = '-source 1.5 -classpath "' + classpath + '"', JARCHDIR = classDir) classes = env.Java(target = classDir, source = srcDir) Depends(classes, sphinx4) jarFile = os.path.normpath('../../scons_build/jars/common.jar') common = env.Jar(target = jarFile, source = classDir) Export('common') <file_sep>/archive_s3/s3.2/src/libutil/libutil.h /* * libutil.h -- Collection of all other .h files in this directory; for brevity * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 08-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon * Added SLEEP_SEC macro. * * 08-31-95 <NAME> (<EMAIL>) at Carnegie Mellon * Created. */ #ifndef _LIBUTIL_LIBUTIL_H_ #define _LIBUTIL_LIBUTIL_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <math.h> #include "prim_type.h" #include "bitvec.h" #include "case.h" #include "ckd_alloc.h" #include "cmd_ln.h" #include "err.h" #include "filename.h" #include "glist.h" #include "hash.h" #include "heap.h" #include "io.h" #include "profile.h" #include "str2words.h" #include "unlimit.h" #if (WIN32) #define SLEEP_SEC(sec) (0) /* Why doesn't Sleep((sec)*1000) work? */ #else #define SLEEP_SEC(sec) sleep(sec) /* sec must be integer */ #endif #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifndef M_PI #define M_PI 3.1415926535897932385 /* For the pain-in-the-neck Win32 */ #endif #define PI M_PI #endif <file_sep>/archive_s3/s3.2/src/lmtest.c /* * lmtest.c -- Interactive tests on an LM file * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 17-Sep-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include "lm.h" #include "logs3.h" static arg_t arg[] = { { "-lm", REQARG_STRING, NULL, "LM dump file" }, { "-lw", ARG_FLOAT64, "9.0", "Language weight" }, { "-wip", ARG_FLOAT64, "0.2", "Word insertion penalty" }, { "-uw", ARG_FLOAT64, "0.7", "Unigram weight" }, { NULL, ARG_INT32, NULL, NULL } }; int32 main (int32 argc, char *argv[]) { lm_t *lm; char line[8192], wd[1024], *lp; s3lmwid_t wid[3], unkwid; int32 lscr, sum; int32 n; cmd_ln_parse (arg, argc, argv); logs3_init (1.0003); lm = lm_read (cmd_ln_str("-lm"), cmd_ln_float64("-lw"), cmd_ln_float64("-wip"), cmd_ln_float64("-uw")); unkwid = lm_wid (lm, S3_UNKNOWN_WORD); for (;;) { fprintf (stderr, "\nUtt: "); if (fgets (line, sizeof(line), stdin) == NULL) break; wid[0] = BAD_S3LMWID; wid[1] = BAD_S3LMWID; lp = line; sum = 0; while (sscanf (lp, "%s%n", wd, &n) == 1) { lp += n; wid[2] = lm_wid (lm, wd); if (NOT_S3LMWID(wid[2])) { if (NOT_S3LMWID(unkwid)) { E_ERROR("Unknown word: '%s'\n", wd); break; } E_ERROR("Unknown word: '%s', using %s\n", wd, S3_UNKNOWN_WORD); wid[2] = unkwid; } lscr = lm_tg_score (lm, wid[0], wid[1], wid[2]); sum += lscr; E_INFO("\t%8d (lscr); %10d (sum); %d (access-type)\t%s\n", lscr, sum, lm_access_type (lm), wd); wid[0] = wid[1]; wid[1] = wid[2]; } } exit(0); } <file_sep>/archive_s3/s3.2/src/dict2pidtest.c /* * dict2pidtest.c * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 05-May-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include "dict2pid.h" #include "logs3.h" static void usage (char *pgm) { E_INFO("Usage: %s mdeffile dictfile fillerfile\n", pgm); exit(0); } main (int32 argc, char *argv[]) { mdef_t *mdef; dict_t *dict; dict2pid_t *d2p; if (argc != 4) usage(argv[0]); logs3_init (1.0003); mdef = mdef_init (argv[1]); dict = dict_init (mdef, argv[2], argv[3], 0); d2p = dict2pid_build (mdef, dict); dict2pid_dump (stdout, d2p, mdef, dict); } <file_sep>/archive_s3/s3.0/src/libmain/hmm.c /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * <EMAIL>. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact <EMAIL>. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * hmm.c -- HMM Viterbi search. * * * HISTORY * * 24-Feb-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added hmm_vit_trans_comp(). * * 16-Jul-1997 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started. */ #include <libutil/libutil.h> #include <libmisc/libmisc.h> #include "hmm.h" void hmm_clear (mdef_t *m, hmm_t *h) { int32 i; h->in.score = LOGPROB_ZERO; h->in.hist = NULL; for (i = 0; i < m->n_emit_state; i++) { h->state[i].score = LOGPROB_ZERO; h->state[i].hist = NULL; } h->out.score = LOGPROB_ZERO; h->out.hist = NULL; h->bestscore = LOGPROB_ZERO; h->active = -1; } void hmm_enter (hmm_t *h, int32 score, int32 data, vithist_t *hist, int16 f) { h->in.score = score; h->in.data = data; h->in.hist = hist; h->active = f; } int32 hmm_vit_trans (hmm_t *src, hmm_t *dst, int32 frm) { if (dst->in.score < src->out.score) { dst->in.score = src->out.score; dst->in.data = src->out.data; dst->in.hist = src->out.hist; if (dst->active < frm) { dst->active = frm; return 1; } else { assert (dst->active == frm); return 0; } } else return 0; } int32 hmm_vit_trans_comp (int32 score, vithist_t *hist, int32 data, hmm_t *dst, int32 frm) { if (dst->in.score < score) { dst->in.score = score; dst->in.data = data; dst->in.hist = hist; if (dst->active < frm) { dst->active = frm; return 1; } else { assert (dst->active == frm); return 0; } } else return 0; } /* * State score updated by taking the best incoming score and then accumulating the * senone score for that state. (I.e., the same as in the S3 trainer.) The HMM topology * is assumed to be left-to-right, so that the states can be updated right-to-left. * NOTE: The exit state is updated separately. In the Viterbi DP diagram, transitions to * the exit state occur from the current time (are vertical). Hence they should be made * only after the history has been logged for the emitting states. */ int32 hmm_vit_eval (mdef_t *m, tmat_t *tmat, hmm_t *h, int32 *senscore) { int32 d, s, src, score, hmmscore; hmm_state_t *st; s3senid_t *sen; int32 **tp; sen = m->phone[h->pid].state; tp = tmat->tp[m->phone[h->pid].tmat]; /* Update states [m->n_emit_state-1 .. 1], right-to-left. State 0 handled below */ st = h->state; hmmscore = MAX_NEG_INT32; for (d = m->n_emit_state-1; d > 0; d--) { /* For each destination state */ score = LOGPROB_ZERO; src = -1; for (s = 0; s <= d; s++) { /* From each source state */ if ((tp[s][d] > LOGPROB_ZERO) && ((st[s].score + tp[s][d]) >= score)) { score = st[s].score + tp[s][d]; /* P[i,t-1] * a[i,j] (i=s, j=d) */ src = s; } } if (src >= 0) { st[d].score = score; st[d].data = st[src].data; st[d].hist = st[src].hist; } else st[d].score = LOGPROB_ZERO; st[d].score += senscore[sen[d]]; /* Include b[j] */ if (hmmscore < st[d].score) hmmscore = st[d].score; } /* State 0, handled separately to include the initial or entry state */ if ((tp[0][0] > LOGPROB_ZERO) && ((st[0].score + tp[0][0]) >= h->in.score)) { st[0].score += tp[0][0] + senscore[sen[0]]; } else { st[0].score = h->in.score + senscore[sen[0]]; st[0].data = h->in.data; st[0].hist = h->in.hist; } if (hmmscore < st[0].score) hmmscore = st[0].score; /* "Consume" the incoming state score, so it isn't used again in the next frame */ h->in.score = LOGPROB_ZERO; h->bestscore = hmmscore; return hmmscore; } /* * Update the exit state score for the given HMM. */ void hmm_vit_eval_exit (mdef_t *m, tmat_t *tmat, hmm_t *h) { int32 score, src, s, d; int32 **tp; hmm_state_t *st; tp = tmat->tp[m->phone[h->pid].tmat]; st = h->state; src = -1; score = LOGPROB_ZERO; d = m->n_emit_state; for (s = 0; s < d; s++) { if ((tp[s][d] > LOGPROB_ZERO) && ((st[s].score + tp[s][d]) >= score)) { score = st[s].score + tp[s][d]; src = s; } } if (src >= 0) { h->out.score = score; h->out.data = st[src].data; h->out.hist = st[src].hist; } else h->out.score = LOGPROB_ZERO; } void hmm_dump (FILE *fp, mdef_t *m, hmm_t *h) { int32 i; fprintf (fp, "\t%5d\t", h->active); fprintf (fp, "% 12d", h->in.score); for (i = 0; i < m->n_emit_state; i++) fprintf (fp, " %12d", h->state[i].score); fprintf (fp, "% 12d", h->out.score); fprintf (fp, "\n"); fprintf (fp, "\t\t"); if (h->in.hist) fprintf (fp, " %12d", h->in.hist->id); else fprintf (fp, " %12d", -1); for (i = 0; i < m->n_emit_state; i++) { if (h->state[i].hist) fprintf (fp, " %12d", h->state[i].hist->id); else fprintf (fp, " %12d", -1); } if (h->out.hist) fprintf (fp, " %12d", h->out.hist->id); else fprintf (fp, " %12d", -1); fprintf (fp, "\n"); fflush (fp); } <file_sep>/SphinxTrain/src/programs/wave2feat/fe.h /* ==================================================================== * Copyright (c) 1996-2004 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef _FE_H_ #define _FE_H_ #include <s3/prim_type.h> #ifdef __cplusplus extern "C" { #endif #if defined(WIN32) #define srand48(x) srand(x) #define lrand48() rand() #endif typedef struct{ float32 SAMPLING_RATE; int32 FRAME_RATE; float32 WINDOW_LENGTH; int32 FB_TYPE; int32 NUM_CEPSTRA; int32 NUM_FILTERS; int32 FFT_SIZE; float32 LOWER_FILT_FREQ; float32 UPPER_FILT_FREQ; float32 PRE_EMPHASIS_ALPHA; char *warp_type; char *warp_params; char *wavfile; char *cepfile; char *ctlfile; int32 nskip; int32 runlen; char *wavdir; char *cepdir; char *wavext; char *cepext; int32 input_format; int32 is_batch; int32 is_single; int32 blocksize; int32 verbose; int32 machine_endian; int32 input_endian; int32 output_endian; int32 dither; int32 seed; int32 logspec; int32 doublebw; int32 nchans; int32 whichchan; int32 splen; int32 nframes; int16* spdata; } param_t; typedef struct{ float32 sampling_rate; int32 num_cepstra; int32 num_filters; int32 fft_size; float32 lower_filt_freq; float32 upper_filt_freq; float32 **filter_coeffs; float32 **mel_cosine; float32 *left_apex; int32 *width; int32 doublewide; char *warp_type; char *warp_params; } melfb_t; typedef struct{ float32 SAMPLING_RATE; int32 FRAME_RATE; int32 FRAME_SHIFT; float32 WINDOW_LENGTH; int32 FRAME_SIZE; int32 FFT_SIZE; int32 FB_TYPE; int32 LOG_SPEC; int32 NUM_CEPSTRA; int32 FEATURE_DIMENSION; int32 dither; int32 seed; float32 PRE_EMPHASIS_ALPHA; int16 *OVERFLOW_SAMPS; int32 NUM_OVERFLOW_SAMPS; melfb_t *MEL_FB; int32 START_FLAG; int16 PRIOR; float64 *HAMMING_WINDOW; int32 FRAME_COUNTER; } fe_t; /* Struct to hold the front-end parameters */ typedef struct{ param_t *P; fe_t *FE; int16 *fr_data; float32 *fr_cep; } fewrap_t; #define MEL_SCALE 1 #define LOG_LINEAR 2 /* Default values */ #define DEFAULT_SAMPLING_RATE "16000.0" #define DEFAULT_FRAME_RATE "100" #define DEFAULT_FRAME_SHIFT "160" /* The default below is set so that we have an integral number of * samples in a frame. */ #define DEFAULT_WINDOW_LENGTH "0.025625" /* Since the default sampling rate is 16000, let's make the default * fft size consistent with it. */ #define DEFAULT_FFT_SIZE "512" #define DEFAULT_FB_TYPE MEL_SCALE #define DEFAULT_NUM_CEPSTRA "13" #define DEFAULT_NUM_FILTERS "40" #define DEFAULT_LOWER_FILT_FREQ "133.33334" #define DEFAULT_UPPER_FILT_FREQ "6855.4976" #define DEFAULT_PRE_EMPHASIS_ALPHA "0.97" #define DEFAULT_START_FLAG 0 #define DEFAULT_WARP_TYPE "inverse_linear" #define BB_SAMPLING_RATE 16000 #define DEFAULT_BB_FFT_SIZE 512 #define DEFAULT_BB_FRAME_SHIFT 160 #define DEFAULT_BB_NUM_FILTERS 40 #define DEFAULT_BB_LOWER_FILT_FREQ 133.33334 #define DEFAULT_BB_UPPER_FILT_FREQ 6855.4976 #define NB_SAMPLING_RATE 8000 #define DEFAULT_NB_FFT_SIZE 256 /*512*/ #define DEFAULT_NB_FRAME_SHIFT 80 #define DEFAULT_NB_NUM_FILTERS 31 #define DEFAULT_NB_LOWER_FILT_FREQ 200 #define DEFAULT_NB_UPPER_FILT_FREQ 3500 #define DEFAULT_BLOCKSIZE "200000" #define SEED "-1" /* The following only use in the application level */ #define ON 1 #define OFF 0 #define NULL_CHAR '\0' #define MAXCHARS 2048 #define WAV 1 #define RAW 2 #define NIST 3 #define MSWAV 4 #define ONE_CHAN "1" #define LITTLE 1 #define BIG 2 #define FE_SUCCESS 0 #define FE_OUTPUT_FILE_SUCCESS 0 #define FE_CONTROL_FILE_ERROR 1 #define FE_START_ERROR 2 #define FE_UNKNOWN_SINGLE_OR_BATCH 3 #define FE_INPUT_FILE_OPEN_ERROR 4 #define FE_INPUT_FILE_READ_ERROR 5 #define FE_MEM_ALLOC_ERROR 6 #define FE_OUTPUT_FILE_WRITE_ERROR 7 #define FE_OUTPUT_FILE_OPEN_ERROR 8 #define FE_ZERO_ENERGY_ERROR 9 #define COUNT_PARTIAL 1 #define COUNT_WHOLE 0 #define HEADER_BYTES 1024 /* #if defined(ALPHA) || defined(ALPHA_OSF1) || defined(alpha_osf1) || defined(__alpha) || defined(mips) */ /*#define SWAPBYTES*/ #define SWAPW(x) *(x) = ((0xff & (*(x))>>8) | (0xff00 & (*(x))<<8)) #define SWAPL(x) *(x) = ((0xff & (*(x))>>24) | (0xff00 & (*(x))>>8) | \ (0xff0000 & (*(x))<<8) | (0xff000000 & (*(x))<<24)) #define SWAPF(x) SWAPL((int *) x) /* Some defines for MS Wav Files */ /* The MS Wav file is a RIFF file, and has the following 44 byte header */ typedef struct RIFFHeader{ char rifftag[4]; /* "RIFF" string */ int32 TotalLength; /* Total length */ char wavefmttag[8]; /* "WAVEfmt " string (note space after 't') */ int32 RemainingLength; /* Remaining length */ int16 data_format; /* data format tag, 1 = PCM */ int16 numchannels; /* Number of channels in file */ int32 SamplingFreq; /* Sampling frequency */ int32 BytesPerSec; /* Average bytes/sec */ int16 BlockAlign; /* Block align */ int16 BitsPerSample; /* 8 or 16 bit */ char datatag[4]; /* "data" string */ int32 datalength; /* Raw data length */ } MSWAV_hdr; /* Functions */ fe_t *fe_init(param_t const *P); int32 fe_start_utt(fe_t *FE); int32 fe_end_utt(fe_t *FE, float32 *cepvector, int32 *nframes); int32 fe_close(fe_t *FE); int32 fe_process_frame(fe_t *FE, int16 *spch, int32 nsamps,float32 *fr_cep); int32 fe_process_utt(fe_t *FE, int16 *spch, int32 nsamps, float32 ***cep_block, int32 *nframes); /* Functions that wrap up the front-end operations on the front-end wrapper operations. */ fewrap_t * few_initialize(); param_t *fe_parse_options(); void fe_init_params(param_t *P); int32 fe_convert_files(param_t *P); int16 * fe_convert_files_to_spdata(param_t *P, fe_t *FE, int32 *splenp, int32 *nframesp); int32 fe_build_filenames(param_t *P, char *fileroot, char **infilename, char **outfilename); char *fe_copystr(char *dest_str, char *src_str); int32 fe_count_frames(fe_t *FE, int32 nsamps, int32 count_partial_frames); int32 fe_readspch(param_t *P, char *infile, int16 **spdata, int32 *splen); int32 fe_writefeat(fe_t *FE, char *outfile, int32 nframes, float32 **feat); int32 fe_free_param(param_t *P); int32 fe_openfiles(param_t *P, fe_t *FE, char *infile, int32 *fp_in, int32 *nsamps, int32 *nframes, int32 *nblocks, char *outfile, int32 *fp_out); int32 fe_readblock_spch(param_t *P, int32 fp, int32 nsamps, int16 *buf); int32 fe_writeblock_feat(param_t *P, fe_t *FE, int32 fp, int32 nframes, float32 **feat); int32 fe_closefiles(int32 fp_in, int32 fp_out); #ifdef __cplusplus } #endif #endif /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.19 2006/02/25 00:53:48 egouvea * Added the flag "-seed". If dither is being used and the seed is less * than zero, the random number generator is initialized with time(). If * it is at least zero, it's initialized with the provided seed. This way * we have the benefit of having dither, and the benefit of being * repeatable. * * This is consistent with what sphinx3 does. Well, almost. The random * number generator is still what the compiler provides. * * Also, moved fe_init_params to fe_interface.c, so one can initialize a * variable of type param_t with meaningful values. * * Revision 1.18 2006/02/20 23:55:51 egouvea * Moved fe_dither() to the "library" side rather than the app side, so * the function can be code when using the front end as a library. * * Revision 1.17 2006/02/17 00:31:34 egouvea * Removed switch -melwarp. Changed the default for window length to * 0.025625 from 0.256 (so that a window at 16kHz sampling rate has * exactly 410 samples). Cleaned up include's. Replaced some E_FATAL() * with E_WARN() and return. * * Revision 1.16 2006/02/16 00:18:26 egouvea * Implemented flexible warping function. The user can specify at run * time which of several shapes they want to use. Currently implemented * are an affine function (y = ax + b), an inverse linear (y = a/x) and a * piecewise linear (y = ax, up to a frequency F, and then it "breaks" so * Nyquist frequency matches in both scales. * * Added two switches, -warp_type and -warp_params. The first specifies * the type, which valid values: * * -inverse or inverse_linear * -linear or affine * -piecewise or piecewise_linear * * The inverse_linear is the same as implemented by EHT. The -mel_warp * switch was kept for compatibility (maybe remove it in the * future?). The code is compatible with EHT's changes: cepstra created * from code after his changes should be the same as now. Scripts that * worked with his changes should work now without changes. Tested a few * cases, same results. * */ <file_sep>/SphinxTrain/src/libs/libcep_feat/v8_feat.c /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3_feat_0.c * * Description: * Compute a unified feature stream (Ver 0) * * f(t) = < s2_cep(t) s2_dcep(t, 2) s2_ddcep(t, 2) > * * Optionally does the following transformations on MFCC before computing the * derived features above: * * 1. Cepstral mean normalization (based on current utt or prior * utterances). * 2. Automatic gain control: * - subtract utter max c[0] from all c[0] * - subtract estimated utter max (based on prior utterances) * from all c[0] of current utterances. * 3. Silence deletion * - based on c[0] histogram of current utterance * - based on c[0] histogram of prior utterance * * Author: * <NAME> (<EMAIL>) *********************************************************************/ /* static char rcsid[] = "@(#)$Id$"; */ #include "v8_feat.h" #include <s3/feat.h> #include <s3/agc.h> #include <s3/cmn.h> #include <s3/silcomp.h> #include <s3/ckd_alloc.h> #include <s3/cmd_ln.h> #include <s3/s3.h> #include <assert.h> #include <string.h> #include <stdio.h> #define N_FEAT 1 static uint32 n_feat = N_FEAT; static uint32 vecsize[1]; static uint32 mfcc_len; static uint32 delta_wsize = 2; static uint32 long_delta_wsize = 4; uint32 v8_doubledelta_wsize = 1; const char * v8_feat_doc() { return "1 stream :== < cep + dcep + longdcep + ddcep >"; } uint32 v8_feat_id() { return FEAT_ID_V8; } uint32 v8_feat_n_stream() { return n_feat; } uint32 v8_feat_blksize() { return vecsize[0]; } const uint32 * v8_feat_vecsize() { return vecsize; } void v8_feat_set_in_veclen(uint32 veclen) { mfcc_len = veclen; vecsize[0] = 4 * veclen; cmn_set_veclen(veclen); agc_set_veclen(veclen); } void longdeltacep_frame(vector_t ldcep, vector_t mfcc) { int32 s_w; int32 k; int32 mfcc_len; mfcc_len = feat_mfcc_len(); s_w = long_delta_wsize * mfcc_len; for (k = 0; k < mfcc_len; k++) { /* compute the short duration diff cep */ ldcep[k] = mfcc[k + s_w] - mfcc[k - s_w]; } } void v8_deltacep_frame(vector_t dcep, vector_t mfcc) { int32 s_w; int32 k; int32 mfcc_len; mfcc_len = feat_mfcc_len(); s_w = delta_wsize * mfcc_len; for (k = 0; k < mfcc_len; k++) { /* compute the short duration diff cep */ dcep[k] = mfcc[k + s_w] - mfcc[k - s_w]; } } void v8_doubledelta_frame(vector_t ddcep, vector_t mfcc) { int32 d_w; int32 dd_w; int32 mfcc_frame_len; int32 k; float32 d1; float32 d2; mfcc_frame_len = feat_mfcc_len(); /* compute dcep window offset in terms of coefficients */ d_w = delta_wsize * mfcc_frame_len; /* compute ddcep window offset in terms of coefficients */ dd_w = v8_doubledelta_wsize * mfcc_frame_len; for (k = 0; k < mfcc_frame_len; k++) { /* compute 2nd diff of mfcc[k] */ /* dcep[k] of v8_doubledelta_wsize frames in future */ d1 = mfcc[k + d_w + dd_w] - mfcc[k - d_w + dd_w]; /* dcep[k] of v8_doubledelta_wsize frames in past */ d2 = mfcc[k + d_w - dd_w] - mfcc[k - d_w - dd_w]; ddcep[k] = d1 - d2; } } vector_t ** v8_feat_compute(vector_t *mfcc, uint32 *inout_n_frame) { vector_t mfcc_frame; vector_t **out; vector_t out_frame; uint32 svd_n_frame; uint32 n_frame; const char *comp_type = cmd_ln_access("-silcomp"); uint32 i, j; uint32 mfcc_len; uint32 cep_off; uint32 dcep_off; uint32 ldcep_off; uint32 ddcep_off; uint32 s_d_begin; uint32 s_d_end; uint32 l_d_begin; uint32 l_d_end; uint32 dd_begin; uint32 dd_end; void v8_mfcc_print(vector_t *mfcc, uint32 n_frame); mfcc_len = feat_mfcc_len(); /* # of coefficients c[0..MFCC_LEN-1] per frame */ cep_off = 0; /* cep feature is first and includes c[0] */ dcep_off = mfcc_len; /* dcep feature includes short diff */ ldcep_off = 2 * mfcc_len; /* long dcep feature includes long diff */ ddcep_off = 3 * mfcc_len; /* ddcep feature is mfcc_len long */ n_frame = svd_n_frame = *inout_n_frame; n_frame = sil_compression(comp_type, mfcc, n_frame); /* set the begin and end frames for the short dur diff cep */ s_d_begin = delta_wsize; s_d_end = n_frame - s_d_begin; /* set the begin and end frames for the short dur diff cep */ l_d_begin = long_delta_wsize; l_d_end = n_frame - l_d_begin; /* set the begin and end frames for the 2nd diff cep */ dd_begin = v8_doubledelta_wsize + delta_wsize; dd_end = n_frame - dd_begin; cmn(&mfcc[0][0], n_frame); agc(&mfcc[0][0], n_frame); out = feat_alloc(n_frame); for (i = 0, j = 0; i < n_frame; i++, j += mfcc_len) { out_frame = out[i][0]; mfcc_frame = mfcc[i]; memcpy(out_frame, mfcc_frame, mfcc_len * sizeof(float32)); if ((i >= s_d_begin) && (i < s_d_end)) { v8_deltacep_frame(out_frame + dcep_off, mfcc_frame); } if ((i >= l_d_begin) && (i < l_d_end)) { longdeltacep_frame(out_frame + ldcep_off, mfcc_frame); } if ((i >= dd_begin) && (i < dd_end)) { v8_doubledelta_frame(out_frame + ddcep_off, mfcc_frame); } } /* Deal w/ short diff boundaries */ for (i = 0; i < s_d_begin; i++) { memcpy(&out[i][0][dcep_off], &out[s_d_begin][0][dcep_off], (mfcc_len)*sizeof(float32)); } for (i = s_d_end; i < n_frame; i++) { memcpy(&out[i][0][dcep_off], &out[s_d_end-1][0][dcep_off], mfcc_len*sizeof(float32)); } /* Deal w/ long diff boundaries */ for (i = 0; i < l_d_begin; i++) { memcpy(&out[i][0][ldcep_off], &out[l_d_begin][0][ldcep_off], (mfcc_len)*sizeof(float32)); } for (i = l_d_end; i < n_frame; i++) { memcpy(&out[i][0][ldcep_off], &out[l_d_end-1][0][ldcep_off], mfcc_len*sizeof(float32)); } /* Deal w/ 2nd diff boundaries */ for (i = 0; i < dd_begin; i++) { memcpy(&out[i][0][ddcep_off], &out[dd_begin][0][ddcep_off], mfcc_len*sizeof(float32)); } for (i = dd_end; i < n_frame; i++) { memcpy(&out[i][0][ddcep_off], &out[dd_end-1][0][ddcep_off], mfcc_len*sizeof(float32)); } *inout_n_frame = n_frame; return out; } void v8_feat_print(const char *label, vector_t **f, uint32 n_frames) { /* DUMMY */ } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:38 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1996/03/25 15:36:31 eht * Changes to allow for settable input feature length * * Revision 1.2 1996/01/26 18:04:51 eht * *** empty log message *** * * Revision 1.1 1995/12/14 20:12:58 eht * Initial revision * */ <file_sep>/pocketsphinx/src/libpocketsphinx/glextree.h /* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2010 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file glextree.h * @brief Generic lexicon trees for token-fsg search (and maybe elsewhere) * @author <NAME> <<EMAIL>> */ #ifndef __GLEXTREE_H__ #define __GLEXTREE_H__ /* System includes. */ /* SphinxBase includes. */ #include <listelem_alloc.h> /* Local includes. */ #include "hmm.h" #include "dict2pid.h" #include "dict.h" typedef struct glexlink_s glexlink_t; typedef struct glexnode_s glexnode_t; /** * Link in a lexicon tree. */ struct glexlink_s { glexnode_t *dest; glexlink_t *next; /* LM lookahead weights might go here, eventually. */ }; /** * Generic lexicon tree node structure. */ struct glexnode_s { hmm_t *hmms; /**< One or more HMMs (leaves have more, exact number comes from dict2pid) */ union { glexlink_t *kids; /**< Outgoing links from this node. */ long n_leaves; /**< Number of HMMs for leaf nodes. &*/ } down; int32 wid; /**< Word ID, -1 for non-leaf nodes. */ }; /** * Lexicon tree root node structure. * * Root nodes are organized by right context and base phone, with all * roots sharing the same (lc, ci) pair contiguous. To make it easier * to dynamically add words, they are stored in a tree. Although the * code currently assumes three levels, extending this to 5-phones or * 7-phones or some more exotic configuration shouldn't be difficult. */ typedef struct glexroot_s glexroot_t; struct glexroot_s { int16 phone; /**< Phone for this level of the tree (lc, ci, rc). */ int16 n_down; /**< Number of children (0 for a leafnode). */ glexroot_t *sibs; /**< Next tree entry at this level. */ union { glexroot_t *kids; /**< First tree entry at the next level. */ glexlink_t *nodes; /**< Actual root nodes (single phone words get their own). */ } down; }; /** * Generic lexicon tree structure. */ typedef struct glextree_s glextree_t; struct glextree_s { hmm_context_t *ctx; /**< HMM context for this tree. */ dict_t *dict; /**< Dictionary used to build this tree. */ dict2pid_t *d2p; /**< Context-dependent mappings used. */ int refcount; /**< Reference count. */ glexroot_t root; /**< Root of tree holding root nodes. */ /** * Hash table indexing ssids to first internal nodes, used to * handle fan-in from root nodes. */ hash_table_t *internal; s3ssid_t *ssidbuf; /**< Externally allocated keys for @a internal. */ /** * Hash table indexing word IDs to second-phone leaf nodes, also * used for fan-in. */ hash_table_t *internal_leaf; glist_t internal_leaf_wids; /**< Storage for keys in @a internal_leaf. */ listelem_alloc_t *root_alloc; /**< Allocator for root tree nodes. */ listelem_alloc_t *node_alloc; /**< Allocator for tree nodes. */ listelem_alloc_t *link_alloc; /**< Allocator for tree links. */ /* Counters. */ int nlexroot; int nlexnode; int nlexhmm; }; /** * Filter for dictionary words when building the lextree. * * Frequently we wish to build the lexicon tree over only a subset of * the dictionary, such as that part which intersects with a language * model or grammar. In this case you can provide a function of this * type, which returns TRUE for words to be included and FALSE for * words to be skipped. */ typedef int (*glextree_wfilter_t)(glextree_t *tree, int32 wid, void *udata); /** * Build a lexicon tree from a dictionary and context mapping. */ glextree_t *glextree_build(hmm_context_t *ctx, dict_t *dict, dict2pid_t *d2p, glextree_wfilter_t filter, void *udata); /** * Add a word to the lexicon tree. * * Presumes that it's already been added to the dictionary and * dict2pid. */ void glextree_add_word(glextree_t *tree, int32 wid); /** * Verify that a word exists in the lexicon tree. */ int glextree_has_word(glextree_t *tree, int32 wid); /** * Retain a pointer to a lexicon tree. */ glextree_t *glextree_retain(glextree_t *tree); /** * Release a pointer to a lexicon tree. */ int glextree_free(glextree_t *tree); /** * Reset scores and histories for lexicon tree */ int glextree_clear(glextree_t *tree); #endif /* __GLEXTREE_H__ */ <file_sep>/SphinxTrain/src/programs/inc_comp/parse_cmd_ln.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: parse_cmd_ln.c * * Description: * This file contains the code to define and parse the command * line for the inc_comp command. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <stdio.h> #include <stdlib.h> #include <s3/cmd_ln.h> #include <s3/err.h> int parse_cmd_ln(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description: \n\ \n\ Increase the number of mixture of a continuous HMM. Notice that option \n\ -ninc actually means the number of mixture one wants to split from the \n\ original models. For example, if you have already 8 mixture and you \n\ want to go to 16, then 8 should be specified. \n\ \n\ Usually, the number of mixture is a power of two. You are also \n\ recommended to split the number of mixture from 1 -> 2 -> 4 -> 8 \n\ -> and so on. \n\ "; const char examplestr[] = "Example : \n\ \n\ inc_comp \n\ -ninc 16 \n\ -dcountfn mixture_weights \n\ -inmixwfn mixture_weights \n\ -outmixwfn out_mixture_weights \n\ -inmeanfn means \n\ -outmeanfn out_means \n\ -invarfn variance \n\ -outvarfn out_variance"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-ninc", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "1", "The # of densities to split"}, { "-inmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The weight file for all N den/mix"}, { "-outmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output mixing weight file name w/ N+NINC density weights/mixture"}, { "-inmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source mean file w/ N means"}, { "-outmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The new mean file w/ N+NINC means"}, { "-invarfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The source variance file w/ N means"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "variances file contains full covariances" }, { "-outvarfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The new variance file w/ N+NINC means"}, { "-dcountfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The density counts for the N source den/mix"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.9 2005/06/05 22:12:03 arthchan2003 * Bug no. 1160673, fix the help string of inc_comp. * * Revision 1.8 2004/11/29 01:43:45 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.7 2004/11/29 00:49:20 egouvea * Added missing include files to prevent warnings about printf not being defined * * Revision 1.6 2004/08/26 05:45:33 arthchan2003 * update of help and example strings of inc_comp * * Revision 1.5 2004/08/08 04:07:24 arthchan2003 * help and example strings of inc_comp * * Revision 1.4 2004/07/21 18:30:34 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.4 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.3 1996/07/29 16:26:54 eht * development release * * Revision 1.2 1996/01/26 18:22:55 eht * Development version * * Revision 1.1 1995/12/15 18:37:07 eht * Initial revision * * */ <file_sep>/SphinxTrain/python/cmusphinx/s3dict.py # Copyright (c) 2009 Carnegie Mellon University # # You may copy and modify this freely under the same terms as # Sphinx-III """Read/write Sphinx dictionary files This module reads and writes the text format dictionary files used by SphinxTrain, Sphinx-III, and PocketSphinx. """ __author__ = "<NAME> <<EMAIL>>" __version__ = "$Revision $" from collections import defaultdict from itertools import chain import re def open(file): return S3Dict(file) class S3Dict(dict): """ Class for reading / processing Sphinx format dictionary files. """ def __init__(self, infile=None, preserve_alts=False): self.preserve_alts = preserve_alts self.phoneset = defaultdict(int) self.maxalt = defaultdict(int) if infile != None: self.read(infile) def __contains__(self, key): if not isinstance(key, tuple): m = self.altre.match(key) if m: word, alt = m.groups() return dict.__contains__(self, (word, int(alt))) else: return dict.__contains__(self, (key, 1)) else: return dict.__contains__(self, key) def __getitem__(self, key): if not isinstance(key, tuple): m = self.altre.match(key) if m: word, alt = m.groups() return self.get_alt_phones(word, int(alt)) else: return self.get_phones(key) else: return self.get_alt_phones(*key) def __setitem__(self, key, val): if not isinstance(key, tuple): m = self.altre.match(key) if m: word, alt = m.groups() return self.set_alt_phones(word, int(alt), val) else: self.set_phones(key, val) else: w, p = key self.set_alt_phones(w, p, val) altre = re.compile(r'(.*)\(([^\)]+)\)') def read(self, infile): """ Read dictionary from a file. """ if isinstance(infile, file): fh = infile else: fh = file(infile) for line in fh: line = line.strip() # Skip any comment lines as in cmudict source if line.startswith('##'): continue if line.startswith(';;'): continue spam = line.split() word = unicode(spam[0], 'utf8') phones = spam[1:] self[word] = phones def write(self, outfile): """ Write dictionary to a file. """ if isinstance(outfile, file): fh = outfile else: fh = file(outfile, 'w') wlist = self.keys() wlist.sort() for k in wlist: word, alt = k if alt != 1: word = "%s(%d)" % (word, alt) fh.write("%s\t%s\n" % (word.encode('utf8'), " ".join(self[k]))) def get_phones(self, word): """ Get default pronunciation for word. If word is not present, KeyError will be raised. """ return dict.__getitem__(self, (word, 1)) def get_alt_phones(self, word, alt): """ Get alternate pronunciaition #alt for word. Alternate pronunciations are numbered from 1, where 1 is the default pronunciation. If word is not present, KeyError will be raised. If no alternate pronunciation alt exists, IndexError will be raised. """ if not dict.__contains__(self, (word, 1)): raise KeyError elif not dict.__contains__(self, (word, alt)): raise IndexError, "Alternate pronunciation index %d does not exist" % alt return dict.__getitem__(self, (word, alt)) def set_phones(self, word, phones): """ Set default pronunciation for word. """ dict.__setitem__(self, (word, 1), phones) self.maxalt[word] = 1 for ph in phones: self.phoneset[ph] += 1 # FIXME: should make a class for this def set_alt_phones(self, word, alt, phones): """ Set alternate pronunciaition #alt for word. If alt is greater than the maximum alternate pronunciation index plus one for this dictionary, IndexError will be raised. """ if alt > self.maxalt[word] + 1: raise IndexError, "Alternate pronunciation index %d too high" % alt dict.__setitem__(self, (word, alt), phones) self.maxalt[word] = max(alt, self.maxalt[word]) for ph in phones: self.phoneset[ph] += 1 def add_alt_phones(self, word, phones): """ Add a new alternate pronunciation for word. """ self.maxalt[word] += 1 dict.__setitem__(self, (word, self.maxalt[word]), phones) for ph in phones: self.phoneset[ph] += 1 def del_alt_phones(self, word, alt): """ Delete alternate pronunciation alt for word. If no such alternate pronunciation exists, IndexError will be raised. If this S3Dict was created with preserve_alts=True, the indices of remaining alternate pronunciations will be preserved (you can still this alternative index with set_alt_phones()). Otherwise, the remaining alternate pronunciations will be renumbered accordingly. """ if not dict.__contains__(self, (word, alt)): raise IndexError, "Alternate pronunciation index %d does not exist" % alt for ph in self[word, alt]: self.phoneset[ph] -= 1 if self.phoneset[ph] == 0: # FIXME: make a class del self.phoneset[ph] del self[word, alt] if alt == self.maxalt[word]: self.maxalt[word] -= 1 if not self.preserve_alts: alts = [] for i in range(1, self.maxalt[word] + 1): if (word,i) in self: alts.append(dict.__getitem__(self, (word, i))) del self[word, i] self.del_phones(word) for i, phones in enumerate(alts): dict.__setitem__(self, (word, i + 1), phones) self.maxalt[word] = len(alts) def del_phones(self, word): """ Delete all pronunciations for word. If you only wish to delete the default pronunciation (it is strongly suggested that you don't do this), use del_alt_phones(word, 1). """ for i in range(1, self.maxalt[word] + 1): if dict.__contains__(self, (word, i)): for ph in self[word,i]: self.phoneset[ph] -= 1 if self.phoneset[ph] == 0: # FIXME: make a class del self.phoneset[ph] dict.__delitem__(self, (word, i)) del self.maxalt[word] def words(self): """ Iterate over base words in this dictionary. """ for word,alt in self: if alt == 1: yield word def alts(self, word): """ Iterate over alternative pronunciations for a word. """ for i in range(1, self.maxalt[word] + 1): if (word,i) in self: yield self[word,i] def copy(self, other, w): """ Copy all pronunciations of w from other to self. """ for phones in other.alts(w): self.add_alt_phones(w, phones) def union(self, other): """ Compute the union of two dictionaries, returning the resulting dictionary. Lists of alternate pronunciations for words will be merged between the two dictionaries. The numeric identifiers of said alternates will not be preserved, however, the default pronunciation in the output is guaranteed to be the default pronunciation in self. """ newdict = self.__class__() sw = set(self.words()) ow = set(other.words()) # Simply copy words not shared between inputs for w in sw ^ ow: if w in self: copy(newdict, self, w) elif w in other: copy(newdict, other, w) # Merge pronunciations for all others for w in sw & ow: # Uniquify them prons = set() for phones in chain(self.alts(w), other.alts(w)): prons.add(tuple(phones)) # Set default pronunciation newdict[w] = self[w] prons.remove(tuple(self[w])) # Add all others in arbitrary order for phones in prons: newdict.add_alt_phones(w, list(phones)) return newdict def convert_to_40(d): badalts = [] for w in d.words(): baw = [] for i, p in enumerate(d.alts(w)): # Remove 'DX' outright because it is ambiguous if 'DX' in p: baw.append((w, i+1)) # Otherwise do AX -> AH, AXR -> ER else: j = 0 while j < len(p): if p[j] == 'AX': p[j] = 'AH' elif p[j] == 'IX': p[j] = 'IH' elif p[j] == 'AXR': p[j] = 'ER' elif p[j] == 'NX': p[j] = 'N' elif p[j] == 'TD': p[j] = 'T' elif p[j] == 'DD': p[j] = 'D' elif p[j] == 'TS': p[j:j+1] = ['T', 'S'] j += 1 elif p[j] == 'EN': p[j:j+1] = ['AH', 'N'] j += 1 elif p[j] == 'EM': p[j:j+1] = ['AH', 'M'] j += 1 j += 1 badalts.extend(baw[::-1]) for w, i in badalts: d.del_alt_phones(w, i) <file_sep>/SphinxTrain/src/programs/mk_s3gau/mk_s3gau.c /* ==================================================================== * Copyright (c) 1997-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: mk_s3gau.c * * Description: * Conversion from SPHINX-II codebooks to SPHINX-III mean and * variance files. * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/gauden.h> #include <s3/s3gau_io.h> #include <s3/s2_param.h> #include <s3/s2_read_cb.h> #include <s3/feat.h> #include <s3/err.h> #include <s3/cmd_ln.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> int main(int argc, char *argv[]) { gauden_t *g; const char *cb_basename[4]; char comment[1024]; time_t t; parse_cmd_ln(argc, argv); g = gauden_alloc(); gauden_set_min_var(*(float32 *)cmd_ln_access("-varfloor")); cb_basename[0] = (const char *)cmd_ln_access("-cepcb"); cb_basename[1] = (const char *)cmd_ln_access("-dcepcb"); cb_basename[2] = (const char *)cmd_ln_access("-powcb"); cb_basename[3] = (const char *)cmd_ln_access("-2dcepcb"); s2_read_cb(g, cmd_ln_access("-cbdir"), cb_basename, cmd_ln_access("-meanext"), cmd_ln_access("-varext"), TRUE, /* floor variances */ cmd_ln_access("-fixpowvar")); t = time(NULL); sprintf(comment, "Generated on %s\nby %s.\nFrom codebooks in %s\n", ctime(&t), argv[0], (const char *)cmd_ln_access("-cbdir")); E_INFO("writing %s\n", cmd_ln_access("-meanfn")); if (s3gau_write((const char *)cmd_ln_access("-meanfn"), (const vector_t ***)gauden_mean(g), gauden_n_mgau(g), gauden_n_feat(g), gauden_n_density(g), gauden_veclen(g)) != S3_SUCCESS) { E_FATAL_SYSTEM("could not write means file\n"); } if (cmd_ln_access("-varfn")) { E_INFO("Writing %s\n", cmd_ln_access("-varfn")); if (s3gau_write((const char *)cmd_ln_access("-varfn"), (const vector_t ***)gauden_var(g), gauden_n_mgau(g), gauden_n_feat(g), gauden_n_density(g), gauden_veclen(g)) != S3_SUCCESS) { E_FATAL_SYSTEM("could not write var file\n"); } } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.5 2004/07/21 19:17:25 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.4 2004/06/17 19:17:23 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:14 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.2 97/07/16 11:24:05 eht * Changes for new I/O routines * * Revision 1.1 97/03/07 08:56:56 eht * Initial revision * * */ <file_sep>/tools/common/src/java/edu/cmu/sphinx/tools/corpus/CorpusReader.java package edu.cmu.sphinx.tools.corpus; /** * Copyright 1999-2006 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * <p/> * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * <p/> * User: <NAME> * Date: Apr 2, 2006 * Time: 7:16:41 PM */ public interface CorpusReader { Corpus read(); } <file_sep>/SphinxTrain/include/s3/mllr_io.h /* ==================================================================== * Copyright (c) 1996-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ #ifndef __MLLR_IO__ #define __MLLR_IO__ #ifdef __cplusplus extern "C" { #endif #if 0 } #endif int32 store_reg_mat (const char *regmatfn, const uint32 *veclen, uint32 n_class, uint32 n_stream, float32 ****A, float32 ***B); int32 read_reg_mat (const char *regmatfn, const uint32 **veclen, uint32 *n_class, uint32 *n_stream, float32 *****A, float32 ****B); int32 free_mllr_A(float32 ****A, uint32 n_class, uint32 n_stream); int32 free_mllr_B(float32 ***B, uint32 n_class, uint32 n_stream); int32 free_mllr_reg(float32 *****regl, float32 ****regr, uint32 n_class, uint32 n_stream); #ifdef __cplusplus } #endif #endif /* __MLLR_IO__ */ <file_sep>/SphinxTrain/src/programs/map_adapt/cmd_ln.c /********************************************************************* * * $Header$ * * CMU ARPA Speech Project * * Copyright (c) 1994-2005 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: parse_cmd_ln.c * * Description: * * Author: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> *********************************************************************/ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <assert.h> /* defines, parses and (partially) validates the arguments given on the command line */ int parse_cmd_ln(int argc, char *argv[]) { #include "cmd_ln_defn.h" cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if(cmd_ln_int32("-help")){ printf("%s\n\n",helpstr); exit(1); } if(cmd_ln_int32("-example")){ printf("%s\n\n",examplestr); exit(1); } cmd_ln_print_configuration(); return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.2 2005/06/16 04:31:28 dhdfu * Replace this program with my own "map_update" code. This implements * the MAP update equations from Chin-Hui Lee and <NAME>'s * papers in addition to the (actually superior) simple interpolation * from Sam-Joo's code (which is still the default). There is no longer * any need to run norm to generate an ML estimate, we do that * internally. Also we can now adapt mixture weights, which may or may * not improve accuracy slightly versus only updating the means. */ <file_sep>/SphinxTrain/src/programs/map_adapt/cmd_ln_defn.h /********************************************************************* * * $Header$ * * CMU ARPA Speech Project * * Copyright (c) 1998 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: cmd_ln_defn.h * * Description: * Command line definitions for map_adapt * * Author: * <NAME> <<EMAIL>> *********************************************************************/ #ifndef CMD_LN_DEFN_H #define CMD_LN_DEFN_H const char helpstr[] = "Description: \n" "\n" "Given a speaker-independent (or other baseline) model and a\n" "set of forward-backward statistics collected from adaptation\n" "data using this model as initialization, map_adapt will update\n" "the model parameters to maximize the a posteriori probability\n" "of the adaptation data given a prior distribution derived from\n" "the baseline model.\n"; const char examplestr[] = "Example: \n" "map_adapt -mapmeanfn map_model/means -meanfn baseline/means \\\n" " -varfn baseline/variances -accumdir bwaccumdir\n"; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Baseline (speaker-independent) Gaussian density mean file"}, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Baseline (speaker-independent) Gaussian density variance file"}, { "-tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Baseline (speaker-independent) transition matrix parameter file name"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Baseline (speaker-independent) mixture weight parameter file name"}, { "-accumdir", CMD_LN_STRING_LIST, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "One or more paths containing reestimation sums from running bw on adaptation data" }, { "-fixedtau", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Use a uniform value for the prior hyperparameter tau"}, { "-bayesmean", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Use simple Bayesian updating for the means, ignoring tau (recommended)."}, { "-tau", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "10.0", "The uniform value for the tau (prior weight) hyperparameter"}, { "-mwfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "Mixing weight smoothing floor" }, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "Variance smoothing floor" }, { "-tpfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.0001", "Transition probability smoothing floor" }, { "-mapmeanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output MAP mean file"}, { "-mapvarfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output MAP var file"}, { "-mapmixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output MAP mixture weight file"}, { "-maptmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The output MAP transition matrix file"}, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; #endif /* CMD_LN_DEFN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2005/07/05 17:06:40 dhdfu * Requires -2passvar to be OFF! (doh) * * Revision 1.5 2005/07/05 16:21:01 dhdfu * Make variance re-estimation work (requires -2passvar to be off). * Implement and enable transition matrix re-estimation (does basically nothing, of course). * Refactor the code into a bunch of smaller functions to make it less unweildy. * * Revision 1.4 2005/06/17 18:32:22 dhdfu * Make this work again for SCHMM. Some steps towards fixing variance updates (it kind of works without -2passvar) but I fear we have to do it in two passes as there is no "shortcut" unlike for ML variance estimation * * Revision 1.3 2005/06/16 04:31:28 dhdfu * Replace this program with my own "map_update" code. This implements * the MAP update equations from <NAME> and <NAME>'s * papers in addition to the (actually superior) simple interpolation * from Sam-Joo's code (which is still the default). There is no longer * any need to run norm to generate an ML estimate, we do that * internally. Also we can now adapt mixture weights, which may or may * not improve accuracy slightly versus only updating the means. * * Currently this is BROKEN for semi-continuous models (the old map_adapt * worked fine for them but didn't do a whole lot since it couldn't * update mixture weights). But it shouldn't be hard to fix it. Also, * variance updating doesn't work, and transition matrix updating isn't * implemented. These might require some changes to bw. * * */ <file_sep>/archive_s3/s3.0/src/libmain/Makefile # # Makefile # # HISTORY # # 07-Jan-97 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include ../../../Makefile.defines VPATH = .:.. TARGET = libmain.a OBJS = agc.o \ am.o \ cmn.o \ dict.o \ fillpen.o \ gauden.o \ hmm.o \ hyp.o \ interp.o \ kbcore.o \ lm.o \ mdef.o \ senone.o \ tmat.o \ vithist.o \ wid.o \ wnet2pnet.o $(TARGET) : $(OBJS) ar crv $@ $? ranlib $@ install: $(TARGET) cp $(TARGET) $(S3LIBDIR) segnbest2hmmnet : segnbest2hmmnet.o \ hmm.o \ wid.o \ mdef.o \ dict.o \ gauden.o \ senone.o \ tmat.o \ lm.o \ vit_hist.o \ fillpen.o \ cmn.o \ agc.o \ $(CC) $(S3DEBUG) $(CFLAGS) -o $@ $> -lmisc -lfeat -lio -lutil -lm interp : interp.c $(CC) $(S3DEBUG) -D_INTERP_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lio -lutil -lm rm interp.o tmat : tmat.c $(CC) $(S3DEBUG) -D_TMAT_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lio -lutil -lm rm tmat.o gauden : gauden.c cmn.o agc.o $(CC) $(S3DEBUG) -D_GAUDEN_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lfeat -lio -lutil -lm rm gauden.o sen2s2 : sen2s2.c mdef.o $(CC) $(S3DEBUG) -D_SENONE_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lfeat -lio -lutil -lm senone : senone.c gauden.o cmn.o agc.o $(CC) $(S3DEBUG) -D_SENONE_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lfeat -lio -lutil -lm rm senone.o mdef : mdef.c $(CC) $(S3DEBUG) -D_MDEF_TEST_=1 $(CFLAGS) -o $@ $> -lutil rm mdef.o dict : dict.c mdef.o $(CC) $(S3DEBUG) -D_DICT_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lutil rm dict.o lm : lm.c $(CC) $(S3DEBUG) -D_LM_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lutil -lm rm lm.o kbcore : kbcore.c mdef.o dict.o lm.o fillpen.o wid.o gauden.o senone.o am.o tmat.o $(CC) $(S3DEBUG) -D_KBCORE_TEST_=1 $(CFLAGS) -o $@ $> -lmisc -lfeat -lio -lutil -lm rm kbcore.o clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/SphinxTrain/src/libs/libcommon/get_time.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: get_time.c * * Description: * A machine independent way to get a time for the purposes of * computing elapsed time. * * Currently, only known to work on OSF/1 and HPUX. * * Author: * <NAME> (<EMAIL>) * *********************************************************************/ #include <s3/get_time.h> #include <s3/err.h> #include <s3/s3.h> #include <sys_compat/time.h> #include <stddef.h> /* define NULL, etc. */ /********************************************************************* * * Function: get_time() * * Description: * Return some value (in units of seconds) which increases * at a constant rate with time. The purpose of this routine * is to provide a way to compute elapsed times for events. * Since the method for getting the current system time has * varied quite a lot over the years, it is wrapped up in * this routine. * * Function Inputs: * None * * Global Inputs: * None * * Return Values: * The current value of elapsed time * * Global Outputs: * None * * Errors: * * Pre-Conditions: * * Post-Conditions: * *********************************************************************/ int get_time(uint32 *sec, float32 *frac_sec) { #ifndef WIN32 struct timeval t; /* Use the BSD call */ if (gettimeofday(&t, NULL) < 0) { E_WARN_SYSTEM("Unable to get time\n"); return S3_ERROR; } /* On the Alpha, the header file sys/timers.h says * that tv_nsec is in terms of microseconds, but the * man page on clock_gettime says that the return value * is in terms of nanoseconds. The name of the field * suggests to me that it is nanoseconds, so for now... */ *sec = t.tv_sec; *frac_sec = t.tv_usec * 1e-6; return S3_SUCCESS; #else *sec = 0; *frac_sec = 0; return S3_SUCCESS; #endif } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 18:05:39 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.6 1996/06/17 14:36:41 eht * Get get_time to compile under WIN32 * * Revision 1.5 1995/10/24 18:48:06 eht * Use gettimeofday() instead of POSIX call since BSD * has had more time to propagate than POSIX * * Revision 1.4 1995/10/13 20:59:21 eht * Start to get ready for Windows NT * * Revision 1.3 1995/10/09 20:56:36 eht * Changes needed for prim_type.h * * Revision 1.2 1995/10/05 12:59:17 eht * Some necessary changes to get the beggar to work. * * Revision 1.1 1995/09/15 15:24:06 eht * Initial revision * * */ <file_sep>/SphinxTrain/include/s3/s3phseg_io.h /* ==================================================================== * Copyright (c) 2006 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: s3phseg_io.h * * Description: * SPHINX-III phone segmentation file I/O functions * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef S3PHSEG_IO_H #define S3PHSEG_IO_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/prim_type.h> #include <s3/acmod_set.h> typedef struct s3phseg_s { acmod_id_t phone; /* phone id */ uint32 sf, ef; /* Start and end frame for this phone occurrence */ int32 score; /* Acoustic score for this segment of alignment */ int32 tscore; /* Transition ("LM") score for this segment */ struct s3phseg_s *next; /* Next entry in alignment */ } s3phseg_t; int s3phseg_read(const char *fn, acmod_set_t *acmod_set, s3phseg_t **out_phseg); int s3phseg_write(const char *fn, acmod_set_t *acmod_set, s3phseg_t *phseg); void s3phseg_free(s3phseg_t *phseg); #ifdef __cplusplus } #endif #endif /* S3PHSEG_IO_H */ <file_sep>/archive_s3/s3.2/src/tmat.h /* * tmat.h * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 29-Feb-2000 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added tmat_chk_1skip(), and made tmat_chk_uppertri() public. * * 10-Dec-1999 <NAME> (<EMAIL>) at Carnegie Mellon University. * Added tmat_dump(). * * 11-Mar-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started based on original S3 implementation. */ #ifndef _S3_TMAT_H_ #define _S3_TMAT_H_ #include <libutil/libutil.h> #include "s3types.h" /* * Transition matrix data structure. All phone HMMs are assumed to have the same * topology. */ typedef struct { int32 ***tp; /* The transition matrices; int32 since probs in logs3 domain: tp[tmatid][from-state][to-state] */ int32 n_tmat; /* #matrices */ int32 n_state; /* #source states in matrix (only the emitting states); #destination states = n_state+1, it includes the exit state */ } tmat_t; tmat_t *tmat_init (char *tmatfile, /* In: input file */ float64 tpfloor); /* In: floor value for each non-zero transition probability */ void tmat_dump (tmat_t *tmat, FILE *fp); /* For debugging */ /* * Checks that no transition matrix in the given object contains backward arcs. * Returns 0 if successful, -1 if check failed. */ int32 tmat_chk_uppertri (tmat_t *tmat); /* * Checks that transition matrix arcs in the given object skip over at most 1 state. * Returns 0 if successful, -1 if check failed. */ int32 tmat_chk_1skip (tmat_t *tmat); #endif <file_sep>/misc_scripts/do_decode.sh #!/bin/bash # decode using the speed parms and merged speakers if [ $# != 2 ] ; then echo "usage: do_decode.sh <cfgtemplate> <testset> (e.g: 1046, PP50, etc)" ; exit ; fi testset=$2 # nset="n0inf n15dB n10dB" # my version of names nset="infdB 15dB 10dB" # Chanwoo's version decfg=speed # substute in proper testset info grep -v "ctlfile" $1 > $$.temp1 grep -v "reffile" $$.temp1 > $$.temp2 echo "ctlfile = \$ctldir/$testset.ctl" >> $$.temp2 echo "reffile = \$ctldir/$testset.ref" >> $$.temp2 # go through each noise level for lev in $nset ; do sed -e s/NOISELEVEL/$lev/ < $$.temp2 > $$.cfg # set the current noise level in the config ./scripts/decodecep2.pl -config $$.cfg -expid ${lev}_${testset}_$decfg tail -2 logdir/${lev}_${testset}_$decfg/${lev}_${testset}_$decfg.align tail -2 logdir/${lev}_${testset}_$decfg/${lev}_${testset}_$decfg.log cp -p $$.cfg logdir/${lev}_${testset}_$decfg/${lev}_${testset}_$decfg.cfg done rm $$.* # <file_sep>/archive_s3/s3.2/src/wid.h /* * wid.c -- Mapping word-IDs between LM and dictionary. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Mar-1999 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _S3_WID_H_ #define _S3_WID_H_ #include <libutil/libutil.h> #include "dict.h" #include "lm.h" /* * Create mappings between dictionary and LM word-IDs. In short: * - An array of s3lmwid_t entries (map[]) is created; where map[i] is the LM word-ID for * the dictionary word-ID i. Mappings are created for the alternative pronunciations as * well. For words not in the LM, the corresponding entries are BAD_S3LMWID. * - Similarly, lm->ug[u].dictwid is assigned the dictionary word id for unigram word u. * Return value: The map[] array built as described above. */ s3lmwid_t *wid_dict_lm_map (dict_t *dict, /* In: Dictionary */ lm_t *lm); /* In/Out: LM; lm->ug[].dictwid values are updated. */ /* * Augment the given wordprob array with alternative pronunciations from the dictionary. * Return value: #entries in the augmented wordprob array (including the original ones). */ int32 wid_wordprob2alt (dict_t *dict, /* In: Dictionary */ wordprob_t *wp, /* In/Out: Input wordprob array, to be augmented with alternative pronunciations for the entries that already exist in it. Caller must have allocated this array. */ int32 n); /* In: #Input entries in the wordprob array */ #endif <file_sep>/scons/shipDictator.py import subprocess import platform import os import sys import string Import('javapath') Import('dictator') dir = '../../scons_ship/dictator' Install(dir, '../../scons_build/jars/common.jar') Install(dir, '../tools/common/lib/batch.jar') Install(dir, '../tools/common/lib/dom4j-1.6.1.jar') Install(dir, '../tools/common/lib/forms_rt_license.txt') Install(dir, '../tools/common/lib/forms_rt.jar') Install(dir, '../tools/common/lib/javolution.jar') Install(dir, '../tools/common/lib/sphinx4.jar') Install(dir, '../tools/common/data/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar') Install(dir, '../tools/dictator/build/dictator.config.xml') Install(dir, str(dictator[0])) shipDictator = Alias('foo', dir) classpath = 'WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar' + os.pathsep classpath += 'batch.jar' + os.pathsep classpath += 'common.jar' + os.pathsep classpath += 'dictator.jar' + os.pathsep classpath += 'dom4j-1.6.1.jar' + os.pathsep classpath += 'forms_rt.jar' + os.pathsep classpath += 'javolution.jar' + os.pathsep classpath += 'sphinx4.jar' def build(target, source, env): execenv = Environment(ENV = os.environ) execenv['ENV']['PATH'] = javapath subprocessenv = execenv['ENV'] cmd = 'java -Xmx256m -classpath "' + classpath + '" edu.cmu.sphinx.tools.dictator.DictatorView' P = subprocess.Popen(cmd, cwd = dir, env = subprocessenv, shell = True) return P.wait() env = Environment(ENV = {'PATH' : javapath }, BUILDERS = {'RunDictator' : Builder(action = build)}) runDictator = env.RunDictator('bar', shipDictator) Depends(runDictator, shipDictator) Export('shipDictator') Export('runDictator') <file_sep>/archive_s3/s3.0/pgm/segnbestrescore/segnbest2hmmnet.c /* * segnbest2hmmnet.c -- Create a complete triphone HMM network from a segmented * N-best list file. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 26-Jun-97 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libfeat/libfeat.h> #include "dict.h" #include "gauden.h" #include "senone.h" #include "tmat.h" #include "lm.h" #include "fillpen.h" #include "hmm.h" #include "misc.h" #include "cmn.h" #include "agc.h" #define MAXWDS 4096 #define MAX_UNIQ_HIST 4096 typedef struct { mdef_t *mdef; dict_t *dict; lm_t *lm; fillpen_t *fillpen; gauden_t *gauden; senone_t *sen; tmat_t *tmat; s3lmwid_t *dict2lmwid; am_eval_t *am; } kb_t; /* * The search graph (DAG) consists of word nodes and links. The following structures * represent these two types of entities. */ typedef struct wnode_s { s3wid_t wid; struct wnode_s *lmbase; /* For bypassing "filler" nodes that are transparent to the LM. If this is a non-filler node, lmbase points to itself, else to the nearest non-filler predecessor */ glist_t succ; /* List of successor word nodes */ struct wnode_s *pred; /* Predecessor node for the purpose of figuring out the LM history and phonetic context. Even though there may actually be several predecessors, all of them present the same history. So we keep just one predecessor link */ glist_t p0list; /* List of initial phones for this word node. (It is a list because there may be many right context instances for a single-phone word. */ } wnode_t; typedef struct wlink_s { wnode_t *dst; } wlink_t; static int32 n_wnode, n_wlink; static void wnode_free (void *data) { glist_myfree (((wnode_t *)data)->succ, sizeof(wlink_t)); glist_free (((wnode_t *)data)->p0list); } static void wnet_free (glist_t wdag) { glist_apply (wdag, wnode_free); glist_myfree (wdag, sizeof(wnode_t)); } static void link_wnodes (wnode_t *src, wnode_t *dst) { wlink_t *wl; wl = (wlink_t *) mymalloc (sizeof(wlink_t)); wl->dst = dst; src->succ = glist_add (src->succ, (void *)wl); n_wlink++; } /* Convert a word-id array to a wnode_t list */ static glist_t seg2wnodelist (glist_t dag, s3wid_t *wid, int32 nwid) { wnode_t *wn, *prev; int32 i; assert (nwid > 0); prev = NULL; for (i = 0; i < nwid; i++) { wn = (wnode_t *) mymalloc (sizeof(wnode_t)); wn->wid = wid[i]; wn->lmbase = NULL; /* Undefined at the moment */ wn->succ = NULL; wn->pred = prev; dag = glist_add (dag, (void *)wn); if (prev) link_wnodes (prev, wn); prev = wn; } return dag; } /* * Convert rwid[] into hist[]: * rwid[w] = Input list of nodes that end in wid w and end the currnet segment. * hist[i] = Output list of nodes ending the current segment that present * the SAME HISTORY to the next segment. * Return value: #valid entries in hist[]. */ static int32 build_hist (glist_t *hist, glist_t *rwid, dict_t *d) { int32 n_hist; int32 w, i; gnode_t *gn; wnode_t *wn; s3wid_t bw; static int32 *wid2hist = NULL; n_hist = 0; if (! wid2hist) wid2hist = (int32 *) ckd_calloc (d->n_word, sizeof(int32)); for (w = 0; w < d->n_word; w++) { if (! rwid[w]) continue; if (! dict_filler_word (d, w)) { hist[n_hist++] = rwid[w]; } else { for (i = 0; i < d->n_word; i++) wid2hist[i] = -1; for (gn = rwid[w]; gn; gn = gn->next) { wn = (wnode_t *)(gn->data); assert (wn->lmbase != wn); if (! wn->lmbase) { /* Must be dummy root node */ assert (wn->wid == d->silwid); assert (! wn->pred); bw = wn->wid; } else bw = dict_basewid(d, wn->lmbase->wid); if (wid2hist[bw] < 0) wid2hist[bw] = n_hist++; hist[wid2hist[bw]] = glist_add (hist[wid2hist[bw]], (void *)wn); } glist_free (rwid[w]); } rwid[w] = NULL; } return n_hist; } /* * Build a wordnet from a segmented nbest file. The segmented N-best file contains * a number of time-segments for an utterance. For each segment, there are a number * of alternative (Nbest) segment-hypotheses, including a right-context word for each * hypothesis. This context is ignored. Therefore, there may be duplicate hypotheses * in a given segment, which have to be ignored. Each segment has a number of possible * unique histories, determined by the previous segment(s). Since we use triphone * acoustic models and N-gram language models, the entire history to the beginning of * the utterance is not relevant. Rather, a unique history is decided by the rightmost * base phoneme of the complete history, and (N-2) most recent base words. (For now, * N=3; i.e. trigram LMs.) * Each hypothesis in the segment is linked to every hypothesis in the previous segment, * as follows: A single copy of the hypothesis can be shared by (or linked to) more * than one hypothesis in the previous segment, iff the latter result in the same * history. */ static glist_t segnbest2wordnet (kb_t *kb, char *file) { FILE *fp; dict_t *dict; char line[32768]; int32 ntok, nwid; char *wstr[MAXWDS]; s3wid_t wid[MAXWDS]; wnode_t *root; /* Root node of word DAG */ wnode_t *seghead, *segtail; /* Head/tail nodes of a segment hypothesis instance */ glist_t dag; /* List of nodes in entire search DAG */ glist_t *lwid, *rwid; /* lwid[w] = list of nodes that begin with wid w, and rwid[w] = nodes that end with w in current segment */ glist_t *hist; /* hist[i] = list of ending nodes in previous segment that present the SAME HISTORY to the current segment */ int32 n_hist; /* #Currently valid entries in hist[] above */ int32 segsf, prev_segsf; int32 n_seghyp; gnode_t *gn; wnode_t *wn; int32 i, j; E_INFO("Loading %s\n", file); if ((fp = fopen(file, "r")) == NULL) { E_ERROR("fopen(%s,r) failed\n", file); return NULL; } /* Skip header */ if (fgets (line, sizeof(line), fp) == NULL) { E_ERROR("Empty file: %s\n", file); fclose (fp); return NULL; } dict = kb->dict; lwid = (glist_t *) ckd_calloc (dict->n_word, sizeof(glist_t)); rwid = (glist_t *) ckd_calloc (dict->n_word, sizeof(glist_t)); hist = (glist_t *) ckd_calloc (MAX_UNIQ_HIST, sizeof(glist_t)); prev_segsf = -1; n_hist = 0; n_wnode = 0; n_wlink = 0; n_seghyp = 0; /* Create a DAG with a single root node with a SILENCE_WORD */ root = (wnode_t *) mymalloc (sizeof(wnode_t)); root->wid = dict->silwid; root->lmbase = NULL; root->succ = NULL; /* Empty list of links from this node */ root->pred = NULL; dag = glist_add (NULL, (void *) root); rwid[dict->silwid] = glist_add (NULL, (void *) root); n_wnode++; while (fgets (line, sizeof(line), fp) != NULL) { if ((ntok = str2words (line, wstr, MAXWDS)) < 0) E_FATAL("Increase MAXWDS (from %d)\n", MAXWDS); /* Too many tokens */ if ((ntok == 1) && (strcmp (wstr[0], "End") == 0)) break; assert ((ntok >= 5) && (ntok & 0x1)); if (sscanf (wstr[1], "%d", &segsf) != 1) E_FATAL("Bad startframe value: %s\n", wstr[1]); /* * Convert words in line to word-ids. * Format: score sf word sf word ... sf right-context-word; skip the context word. */ for (i = 2, nwid = 0; i < ntok-2; i += 2, nwid++) { wid[nwid] = dict_wordid (dict, wstr[i]); if (NOT_WID(wid[nwid])) E_FATAL("Unknown word: %s\n", wstr[i]); } if (segsf == prev_segsf) { /* * Check if this word sequence has been seen before in this segment * (i.e., check lists beginning with wid[0]). If seen, skip it. */ for (gn = lwid[wid[0]]; gn; gn = gn->next) { wn = (wnode_t *) (gn->data); for (j = 0; (j < nwid) && wn && (wid[j] == wn->wid); j++) { wn = (wn->succ) ? ((wlink_t *) (wn->succ->data))->dst : NULL; } if ((! wn) && (j >= nwid)) break; } if (gn) /* Duplicate segment; skip it */ continue; } else { /* * Current segment ended, start a new one. * First, forget about the history list for the previous segment. */ for (i = 0; i < n_hist; i++) { glist_free (hist[i]); hist[i] = NULL; } /* Build history list from rwid in the current segment, and clear rwid */ n_hist = build_hist (hist, rwid, dict); /* Clear lwid */ for (i = 0; i < dict->n_word; i++) { glist_free (lwid[i]); lwid[i] = NULL; } #if 0 E_INFO("Frm %5d: %6d hyp instances\n", prev_segsf, n_seghyp); E_INFO("Frm %5d: %6d unique histories\n", segsf, n_hist); #endif prev_segsf = segsf; n_seghyp = 0; } /* * Tack this new segment to the end of all possible predecessor segments. * A new copy of the new segment is needed whenever the predecessor segment * presents a new phonemic left context, OR a new linguistic context of * (ngram-2) words. * In short, for each unique history, create a separate instance of the new * segment and link all predecessors with that history to the new instance. */ for (i = 0; i < n_hist; i++) { dag = seg2wnodelist (dag, wid, nwid); n_wnode += nwid; /* Find the head and tail wnodes of the segment just created */ segtail = (wnode_t *)(dag->data); for (j = 0, gn = dag; j < nwid-1; j++, gn = gn->next); seghead = (wnode_t *)(gn->data); /* Successor links from all predecessors with the i-th history to seghead */ for (gn = hist[i]; gn; gn = gn->next) link_wnodes ((wnode_t *)(gn->data), seghead); /* * Predecessor link from seghead to ONE predecessor with this history. * One link is enough since all predecessors in hist[i] have the same history. */ seghead->pred = (wnode_t *)(hist[i]->data); /* Enter seghead into wl_leftwid, and the tail into wl_rightwid */ lwid[seghead->wid] = glist_add (lwid[seghead->wid], (void *)seghead); rwid[segtail->wid] = glist_add (rwid[segtail->wid], (void *)segtail); /* Update lmbase for all the new nodes */ for (wn = seghead; wn; ) { wn->lmbase = (! dict_filler_word (dict, wn->wid)) ? wn : wn->pred->lmbase; wn = (wn->succ) ? ((wlink_t *) (wn->succ->data))->dst : NULL; } n_seghyp++; } } fclose (fp); #if 0 E_INFO("Frm %5d: %6d hyp instances\n", prev_segsf, n_seghyp); #endif /* * Link all nodes to a single FINISH_WORD node. (HACK!! This assumes that finish * word model is context-independent.) */ wn = (wnode_t *) mymalloc (sizeof(wnode_t)); wn->wid = dict->finishwid; wn->lmbase = wn; wn->succ = NULL; wn->pred = NULL; /* No unique predecessor; THIS FIELD MUST NOT BE TOUCHED */ dag = glist_add (dag, (void *)wn); n_wnode++; for (i = 0; i < dict->n_word; i++) { for (gn = rwid[i]; gn; gn = gn->next) link_wnodes ((wnode_t *)(gn->data), wn); } for (i = 0; i < dict->n_word; i++) { glist_free (lwid[i]); lwid[i] = NULL; glist_free (rwid[i]); rwid[i] = NULL; } for (i = 0; i < n_hist; i++) glist_free (hist[i]); ckd_free(lwid); ckd_free(rwid); ckd_free(hist); #if 0 for (gn = dag; gn; gn = gn->next) printf ("%s\n", dict_wordstr (dict, ((wnode_t *)(gn->data))->wid)); #endif return dag; } /* * Phonetic equivalent representation of wordnet. Another DAG with phone nodes and links. */ typedef struct pnode_s { s3wid_t wid; /* Word-id; only valid on last phone of word; otherwise BAD_WID */ s3pid_t pid; /* Triphone id */ hmm_t hmm; /* Search HMM structure */ glist_t succ; /* List of successor phone nodes */ } pnode_t; typedef struct plink_s { pnode_t *dst; int32 lscr; } plink_t; static int32 n_pnode, n_plink; static void pnode_dump (FILE *fp, int32 frm, pnode_t *pn, kb_t *kb) { char buf[128]; fprintf (fp, "%5d:", frm); mdef_phone_str (kb->mdef, pn->pid, buf); fprintf (fp, "\t%s", buf); if (IS_WID(pn->wid)) fprintf (fp, "\t%s", dict_wordstr(kb->dict, pn->wid)); fprintf (fp, "\n"); hmm_dump (fp, &(pn->hmm)); fflush (fp); } static void pnode_free (void *data) { glist_myfree (((pnode_t *)data)->succ, sizeof(plink_t)); } static void pnet_free (glist_t pdag) { glist_apply (pdag, pnode_free); glist_myfree (pdag, sizeof(pnode_t)); } /* Allocate HMM data for each pnode */ static void pnet_hmm_alloc (kb_t *kb, glist_t pdag) { gnode_t *gn; pnode_t *pn; for (gn = pdag; gn; gn = gn->next) { pn = (pnode_t *)(gn->data); hmm_state_alloc (&(pn->hmm)); } } /* Allocate HMM data for each pnode */ static void pnet_hmm_free (kb_t *kb, glist_t pdag) { gnode_t *gn; pnode_t *pn; for (gn = pdag; gn; gn = gn->next) { pn = (pnode_t *)(gn->data); hmm_state_free (&(pn->hmm)); } } static void link_pnodes (pnode_t *src, pnode_t *dst, int32 lscr) { plink_t *pl; pl = (plink_t *) mymalloc (sizeof(plink_t)); pl->dst = dst; pl->lscr = lscr; src->succ = glist_add (src->succ, (void *)pl); n_plink++; } /* * Convert a wordnet into a phone net. We take advantage of the fact that the nodes in * the wordnet DAG nodelist are in reverse topological order. So, if two nodes w1 and w2 * appear in that order in wdag, there may be a link from w2 to w1 but there CANNOT be * a link from w1 to w2. Therefore, we can construct the phone DAG by picking off words * from wdag in order, transforming them into phone nodes, and linking them to the phone * DAG already constructed so far. */ static glist_t wnet2pnet (kb_t *kb, glist_t wdag) { dict_t *dict; mdef_t *mdef; glist_t pdag; gnode_t *gwn; gnode_t *gwl; wnode_t *wn; wlink_t *wl; int32 pronlen; int32 n_rc; pnode_t **rc_pn; pnode_t *pn, *last_pn; gnode_t *p0list; s3cipid_t lc, rc, ci; int32 lscr; int32 i, k, p; dict = kb->dict; mdef = kb->mdef; pdag = NULL; n_pnode = 0; n_plink = 0; rc_pn = (pnode_t **) ckd_calloc (mdef->n_ciphone, sizeof(pnode_t *)); /* Create a pnode for the final wdag node, without any context words */ wn = (wnode_t *)(wdag->data); assert ((! wn->pred) && (! wn->succ)); /* HACK!! */ assert (wn->wid == dict->finishwid); pronlen = dict->word[wn->wid].pronlen; if (pronlen != 1) E_FATAL("Not prepared to handle FINISH_WORD with pronunciation-length != 1\n"); pn = (pnode_t *) mymalloc (sizeof(pnode_t)); pn->wid = wn->wid; pn->succ = NULL; pn->pid = dict->word[wn->wid].ciphone[0]; pn->hmm.sen = mdef->phone[pn->pid].state; pn->hmm.n_state = mdef->n_emit_state; pn->hmm.active = -1; n_pnode++; pdag = glist_add (pdag, (void *)pn); wn->p0list = glist_add (NULL, (void *)pn); for (gwn = wdag->next; gwn; gwn = gwn->next) { wn = (wnode_t *)(gwn->data); wn->p0list = NULL; pronlen = dict->word[wn->wid].pronlen; /* Create phone nodes right to left; last CIphone first */ ci = dict->word[wn->wid].ciphone[pronlen-1]; /* Left context CIphone for the last phone */ if (pronlen > 1) lc = dict->word[wn->wid].ciphone[pronlen-2]; else { if (! wn->pred) lc = BAD_CIPID; else { k = dict->word[wn->pred->wid].pronlen; lc = dict->word[wn->pred->wid].ciphone[k-1]; } } /* Create phone nodes for each distinct right context, link to successor words */ for (i = 0; i < mdef->n_ciphone; i++) rc_pn[i] = NULL; n_rc = 0; assert (wn->succ); for (gwl = wn->succ; gwl; gwl = gwl->next) { wl = (wlink_t *)(gwl->data); rc = dict->word[wl->dst->wid].ciphone[0]; if (! rc_pn[rc]) { rc_pn[rc] = (pnode_t *) mymalloc (sizeof(pnode_t)); rc_pn[rc]->wid = wn->wid; rc_pn[rc]->succ = NULL; rc_pn[rc]->pid = mdef_phone_id_nearest(mdef, ci, lc, rc, (pronlen > 1) ? WORD_POSN_END : WORD_POSN_SINGLE); rc_pn[rc]->hmm.sen = mdef->phone[rc_pn[rc]->pid].state; rc_pn[rc]->hmm.n_state = mdef->n_emit_state; rc_pn[rc]->hmm.active = -1; n_pnode++; n_rc++; pdag = glist_add (pdag, (void *)(rc_pn[rc])); } /* Find LM score for transition from wn to wl->dst */ if (dict_filler_word (dict, wl->dst->wid)) lscr = fillpen (kb->fillpen, wl->dst->wid); else { s3lmwid_t w1, w2, w3; wnode_t *wn1, *wn2; /* Special case for start word */ if (dict_basewid (dict, wl->dst->wid) == dict->startwid) { assert (wn->wid == dict->silwid); assert (wn->pred == NULL); lscr = 0; } else { w3 = kb->dict2lmwid[wl->dst->wid]; wn2 = wn->lmbase; assert (wn2); w2 = kb->dict2lmwid[wn2->wid]; if ((wn1 = wn2->pred) != NULL) wn1 = wn1->lmbase; w1 = wn1 ? kb->dict2lmwid[wn1->wid] : BAD_LMWID; lscr = lm_tg_score (kb->lm, w1, w2, w3); } } /* Link rc_pn[rc] to all initial phone instances of wl->dst */ for (p0list = wl->dst->p0list; p0list; p0list = p0list->next) link_pnodes (rc_pn[rc], (pnode_t *)(p0list->data), lscr); } /* All other phones */ for (p = pronlen-2; p >= 0; p--) { ci = dict->word[wn->wid].ciphone[p]; rc = dict->word[wn->wid].ciphone[p+1]; if (p > 0) lc = dict->word[wn->wid].ciphone[p-1]; else { if (! wn->pred) lc = BAD_CIPID; else { k = dict->word[wn->pred->wid].pronlen; lc = dict->word[wn->pred->wid].ciphone[k-1]; } } pn = (pnode_t *) mymalloc (sizeof(pnode_t)); pn->wid = BAD_WID; pn->succ = NULL; pn->pid = mdef_phone_id_nearest (mdef, ci, lc, rc, (p > 0) ? WORD_POSN_INTERNAL : WORD_POSN_BEGIN); pn->hmm.sen = mdef->phone[pn->pid].state; pn->hmm.n_state = mdef->n_emit_state; pn->hmm.active = -1; n_pnode++; pdag = glist_add (pdag, (void *)pn); if (p == pronlen-2) { /* Penultimate phone */ for (i = 0; i < mdef->n_ciphone; i++) if (rc_pn[i]) link_pnodes (pn, rc_pn[i], 0); } else link_pnodes (pn, last_pn, 0); last_pn = pn; } if (pronlen > 1) wn->p0list = glist_add (NULL, (void *)last_pn); else { wn->p0list = NULL; for (i = 0; i < mdef->n_ciphone; i++) if (rc_pn[i]) wn->p0list = glist_add (wn->p0list, (void *)(rc_pn[i])); } #if 0 printf ("pronlen= %3d rc= %2d %s\n", pronlen, n_rc, dict_wordstr (dict, wn->wid)); #endif } ckd_free (rc_pn); return pdag; } /* BUGCHECK: if the same pnode has been entered twice into the active list */ static void chk_dup_pn (pnode_t **pn, int32 n) { int32 i, j; for (i = 0; i < n; i++) for (j = 0; j < i-1; j++) if (pn[i] == pn[j]) E_FATAL("Duplicate pnode\n"); } static void vit_search (kb_t *kb, glist_t pdag, float32 **mfc, int32 nfr, char *uttid) { am_eval_t *am; gnode_t *gn; pnode_t *pn, *npn; plink_t *pl; mdef_t *mdef; dict_t *dict; tmat_t *tmat; int32 **tp; hmm_t *hmm, *nhmm; pnode_t **cur_pn, **next_pn; /* Current and next pnode active lists */ int32 n_cur_pn, n_next_pn; int32 f, cf, featwin; int32 bestscr, hscr, newscore, beam, wordbeam, thresh, wordthresh; int32 *senscale; int32 i; hist_t *hist; glist_t hlist; /* List of history nodes */ glist_t hyp; /* Word-sequence hypothesis + assoc. info for the utterance */ mdef = kb->mdef; dict = kb->dict; tmat = kb->tmat; cmn (mfc, nfr, feat_cepsize()); agc_max (mfc, nfr); cur_pn = (pnode_t **) ckd_calloc (n_pnode, sizeof(pnode_t *)); next_pn = (pnode_t **) ckd_calloc (n_pnode, sizeof(pnode_t *)); n_cur_pn = 0; n_next_pn = 0; /* Initialize pdag; Use the dummy initial silence word to start all initial pnodes */ gn = pdag; pn = (pnode_t *)(gn->data); assert (pn->wid == dict->silwid); for (gn = pn->succ; gn; gn = gn->next) { pl = (plink_t *)(gn->data); pn = pl->dst; hmm_clear (&(pn->hmm)); hmm_enter (&(pn->hmm), 0, 0, NULL, 0); /* * HACK!! To allow for a non-existent initial silence, set all state scores to 0 * so that we can exit this HMM ASAP. */ for (i = 0; i < pn->hmm.n_state; i++) pn->hmm.state[i].scr = 0; cur_pn[n_cur_pn++] = pn; } featwin = feat_window_size(); am = kb->am; beam = logs3 (*((float64 *) cmd_ln_access ("-beam"))); wordbeam = logs3 (*((float64 *) cmd_ln_access ("-nwbeam"))); hlist = NULL; senscale = (int32 *) ckd_calloc (S3_MAX_FRAMES, sizeof(int32)); for (f = featwin, cf = 0; f < nfr-featwin; f++, cf++) { #if 0 chk_dup_pn (cur_pn, n_cur_pn); #endif #if 0 for (i = 0; i < n_cur_pn; i++) pnode_dump (stdout, cf, cur_pn[i], kb); #endif /* Mark active senones */ bitvec_clear_all (am->sen_active, kb->sen->n_sen); for (i = 0; i < n_cur_pn; i++) _set_sen_active (am, cur_pn[i]->hmm.sen, cur_pn[i]->hmm.n_state); senscale[cf] = _am_eval (am, mfc+f); #if 0 for (i = 0; i < kb->sen->n_sen; i++) { if (bitvec_is_set(am->sen_active, i)) printf ("\t%5d %12d\n", i, am->senscr[i] + senscale[cf]); } #endif bestscr = (int32)0x80000000; for (i = 0; i < n_cur_pn; i++) { tp = tmat->tp[mdef->phone[cur_pn[i]->pid].tmat]; hscr = hmm_eval (&(cur_pn[i]->hmm), am->senscr, tp); if (hscr > bestscr) bestscr = hscr; } if (bestscr <= LOGPROB_ZERO) E_FATAL("Bestscore(%d) < LOGPROB_ZERO @frm %d; increase -logbase\n", bestscr); /* Figure out which HMMs remain or become active next frame */ thresh = bestscr + beam; wordthresh = bestscr + wordbeam; n_next_pn = 0; for (i = 0; i < n_cur_pn; i++) { pn = cur_pn[i]; hmm = &(pn->hmm); if (hmm->bestscr >= thresh) { /* This HMM remains active in the next frame */ if (hmm->active < cf+1) { hmm->active = cf+1; next_pn[n_next_pn++] = pn; } /* Check if this is a final HMM for a word, and whether exited it */ if (IS_WID(pn->wid)) { if (hmm->state[hmm->n_state].scr >= wordthresh) { hist = (hist_t *) mymalloc (sizeof(hist_t)); hist->wid = pn->wid; hist->frm = cf; hist->scr = hmm->state[hmm->n_state].scr; hist->hist = hmm->state[hmm->n_state].hist; hlist = glist_add (hlist, (void *)hist); /* Replace exit state with new history node, for propagation */ hmm->state[hmm->n_state].hist = hist; } } /* Transition to next phones */ if (hmm->state[hmm->n_state].scr >= thresh) { for (gn = pn->succ; gn; gn = gn->next) { pl = (plink_t *)(gn->data); newscore = hmm->state[hmm->n_state].scr + pl->lscr; if (newscore >= thresh) { npn = pl->dst; nhmm = &(npn->hmm); if (nhmm->active < cf) hmm_clear (nhmm); if (nhmm->active < cf+1) next_pn[n_next_pn++] = npn; hmm_enter (nhmm, newscore, hmm->state[hmm->n_state].data, hmm->state[hmm->n_state].hist, cf+1); } } } } } /* Swap cur_pn and next_pn for next frame */ { pnode_t **tmp; tmp = cur_pn; cur_pn = next_pn; next_pn = tmp; n_cur_pn = n_next_pn; } } /* Backtrace through history list */ #if 0 hist_dump (stdout, hlist, dict); #endif hyp = hist_backtrace (hlist, dict->finishwid, cf-1, senscale, dict); _hyp_update_lscr (hyp, kb->lm, kb->fillpen, dict, kb->dict2lmwid); _hyp_print_detail (stdout, uttid, hyp); _hyp_print_base (stdout, uttid, hyp, dict); glist_myfree (hyp, sizeof(hyp_t)); glist_myfree (hlist, sizeof(hist_t)); ckd_free (cur_pn); ckd_free (next_pn); ckd_free (senscale); } static void process_utt (kb_t *kb, char *nbestfile, char *cepfile, int32 sf, int32 ef, char *uttid) { glist_t wdag; glist_t pdag; float32 **mfc; int32 nfr, featwin; am_eval_t *am; wdag = segnbest2wordnet (kb, nbestfile); if (wdag) { pdag = wnet2pnet (kb, wdag); E_INFO("%s: word DAG: %d nodes, %d links; phone DAG: %d nodes, %d links\n", uttid, n_wnode, n_wlink, n_pnode, n_plink); wnet_free (wdag); lm_cache_stats_dump (kb->lm); lm_cache_reset (kb->lm); pnet_hmm_alloc (kb, pdag); am = kb->am; featwin = feat_window_size (); if ((nfr = s2mfc_read (cepfile, sf, ef, featwin, &mfc)) < 0) E_FATAL("MFC read (%s) failed\n", uttid); E_INFO("%s: %d frames\n", uttid, nfr - (featwin << 1)); vit_search (kb, pdag, mfc, nfr, uttid); pnet_hmm_free (kb, pdag); pnet_free (pdag); } } static void process_ctl (kb_t *kb, char *ctl) { FILE *fp; char uttfile[4096]; char uttid[4096]; int32 sf, ef; char nbestfile[16384]; char *nbestdir; char *cepdir; char cepfile[4096]; if ((fp = fopen(ctl, "r")) == NULL) E_FATAL_SYSTEM("fopen(%s,r) failed\n", ctl); nbestdir = (char *) cmd_ln_access ("-nbestdir"); assert (nbestdir); cepdir = (char *) cmd_ln_access ("-cepdir"); kb->am = _am_eval_init (kb->gauden, kb->sen); while (_ctl_read (fp, uttfile, &sf, &ef, uttid) >= 0) { sprintf (nbestfile, "%s/%s.nbest", nbestdir, uttid); _ctl2cepfile (uttfile, cepdir, cepfile); process_utt (kb, nbestfile, cepfile, sf, ef, uttid); } fclose (fp); } static arg_t arglist[] = { { "-logbase", ARG_FLOAT32, "1.0001", "Base in which all log values calculated" }, { "-feat", ARG_STRING, "s3_1x39", "Feature vector type (s3_1x39 or s2_4x)" }, { "-mdef", REQARG_STRING, NULL, "Model definition input file" }, { "-dict", REQARG_STRING, NULL, "Pronunciation dictionary input file" }, { "-fdict", REQARG_STRING, NULL, "Filler word pronunciation dictionary input file" }, { "-mean", REQARG_STRING, NULL, "Mixture gaussian means input file" }, { "-var", REQARG_STRING, NULL, "Mixture gaussian variances input file" }, { "-varfloor", ARG_FLOAT32, "0.0001", "Mixture gaussian variance floor (applied to -var file)" }, { "-sen2mgaumap", ARG_STRING, ".cont.", "Senone to mixture-gaussian mapping file (or .semi. or .cont.)" }, { "-mixw", REQARG_STRING, NULL, "Senone mixture weights input file" }, { "-mixwfloor", ARG_FLOAT32, "0.0000001", "Senone mixture weights floor (applied to -mixw file)" }, { "-tmat", REQARG_STRING, NULL, "HMM state transition matrix input file" }, { "-tmatfloor", ARG_FLOAT32, "0.0001", "HMM state transition probability floor (applied to -tmat file)" }, { "-lm", REQARG_STRING, NULL, "Trigram language model .DMP file" }, { "-lw", ARG_FLOAT32, "9.5", "Language weight: empirical exponent applied to LM probabilty" }, { "-wip", ARG_FLOAT32, "0.2", "Word insertion penalty" }, { "-fpen", ARG_STRING, NULL, "Filler penalty file (overrides silpen and fillpen defaults)" }, { "-silpen", ARG_FLOAT32, "0.1", "Default probability of silence word" }, { "-fillpen", ARG_FLOAT32, "0.05", "Default probability of a non-silence filler word" }, { "-beam", ARG_FLOAT64, "1e-64", "Main pruning beam" }, { "-nwbeam", ARG_FLOAT64, "1e-30", "Pruning beam for word exit" }, { "-ctl", REQARG_STRING, NULL, "Control file listing utterances to be processed" }, { "-nbestdir", ARG_STRING, ".", "Directory of segmented N-best files (for utterances in -ctl file)" }, { "-cepdir", ARG_STRING, ".", "Directory of mfc files (for utterances in -ctl file)" }, { NULL, ARG_INT32, NULL, NULL } }; main (int32 argc, char *argv[]) { float64 lw, wip; char uttid[4096]; kb_t kb; unlimit (); cmd_ln_parse (arglist, argc, argv); logs3_init ( *((float32 *) cmd_ln_access("-logbase")) ); feat_init ((char *) cmd_ln_access ("-feat")); kb.mdef = mdef_init ((char *) cmd_ln_access ("-mdef")); kb.dict = dict_init (kb.mdef, (char *) cmd_ln_access ("-dict"), (char *) cmd_ln_access ("-fdict")); kb.gauden = gauden_init ((char *) cmd_ln_access ("-mean"), (char *) cmd_ln_access ("-var"), *((float32 *) cmd_ln_access ("-varfloor"))); kb.sen = senone_init ((char *) cmd_ln_access ("-mixw"), (char *) cmd_ln_access ("-sen2mgaumap"), *((float32 *) cmd_ln_access ("-mixwfloor"))); kb.tmat = tmat_init ((char *) cmd_ln_access ("-tmat"), *((float32 *) cmd_ln_access ("-tmatfloor"))); lw = *((float32 *) cmd_ln_access("-lw")); wip = *((float32 *) cmd_ln_access("-wip")); kb.lm = lm_read ((char *) cmd_ln_access ("-lm"), lw, wip); kb.fillpen = fillpen_init (kb.dict, (char *) cmd_ln_access ("-fpen"), lw, wip); kb.dict2lmwid = _dict2lmwid (kb.dict, kb.lm); process_ctl (&kb, (char *) cmd_ln_access ("-ctl")); } <file_sep>/archive_s3/s3.2/src/libutil/Makefile # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # # # For compiling this library, do the following: # cd to this directory (i.e., libutil) # setenv MACHINE linux (or alpha, sun, etc. as appropriate) # make # The result is libutil.a in a $MACHINE subdirectory # VPATH = .:.. include Makefile.defines TARGET = libutil.a OBJS = bitvec.o \ case.o \ ckd_alloc.o \ cmd_ln.o \ err.o \ filename.o \ glist.o \ hash.o \ heap.o \ io.o \ profile.o \ str2words.o \ unlimit.o alpha_OBJS = rpcc.o CFLAGS = ${$(MACHINE)_CFLAGS} $(CMDFLAGS) install: mkdir -p $(MACHINE) (cd $(MACHINE); $(MAKE) $(MFLAGS) -f ../Makefile $(TARGET)) $(TARGET): $(OBJS) ${$(MACHINE)_OBJS} $(AR) crv $@ $? $(RANLIB) $@ clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# (cd $(MACHINE); rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~) <file_sep>/archive_s3/s3/src/libfbs/tmat.c /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * tmat.c * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 20-Dec-96 <NAME> (<EMAIL>) at Carnegie Mellon University. * Changed tmat_read to use the new libio/bio_fread functions. * * 13-Nov-95 <NAME> (<EMAIL>) at Carnegie Mellon University. * Created, liberally borrowed from Eric Thayer's S3 trainer. */ #include "tmat.h" #include "vector.h" #include "logs3.h" #include <libio/libio.h> #include <libutil/libutil.h> #include <assert.h> #include <string.h> #define TMAT_PARAM_VERSION "1.0" static tmat_t *tmat; /* The set of transition probability matrices */ #if 0 void tmat_dump (float32 ***tmat, int32 d1, int32 d2, int32 d3) { int32 i, j, k; for (i = 0; i < d1; i++) { E_INFO ("TMAT %d:\n", i); for (j = 0; j < d2; j++) { for (k = 0; k < d3; k++) printf (" %.3e", tmat[i][j][k]); printf ("\n"); } printf ("\n"); } } #endif static int32 tmat_read(tmat_t *t, char *file_name) { char version[1024], tmp; int32 row_dim; FILE *fp; int32 byteswap, chksum_present; uint32 chksum; float32 **tp; int32 i, j, k, tp_per_tmat; char **argname, **argval; E_INFO("Reading HMM transition matrix: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], TMAT_PARAM_VERSION) != 0) E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], TMAT_PARAM_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #tmat, #from-states, #to-states, arraysize */ if ((bio_fread (&(t->n_tmat), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&row_dim, sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(t->n_state), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&i, sizeof(int32), 1, fp, byteswap, &chksum) != 1)) { E_FATAL("bio_fread(%s) (arraysize) failed\n", file_name); } if (t->n_state != row_dim+1) { E_FATAL("%s: #from-states(%d) != #to-states(%d)-1\n", file_name, row_dim, t->n_state); } if (i != t->n_tmat * row_dim * t->n_state) { E_FATAL("%s: #float32s(%d) doesn't match dimensions: %d x %d x %d\n", file_name, i, t->n_tmat, row_dim, t->n_state); } /* Allocate memory for tmat data */ t->tp = (int32 ***) ckd_calloc_3d (t->n_tmat, t->n_state-1, t->n_state, sizeof(int32)); /* Temporary structure to read in the float data */ tp = (float32 **) ckd_calloc_2d (t->n_state-1, t->n_state, sizeof(float32)); /* Read transition matrices, normalize and floor them, and convert to logs3 domain */ tp_per_tmat = (t->n_state-1) * t->n_state; for (i = 0; i < t->n_tmat; i++) { if (bio_fread (tp[0], sizeof(float32), tp_per_tmat, fp, byteswap, &chksum) != tp_per_tmat) { E_FATAL("fread(%s) (arraydata) failed\n", file_name); } /* Normalize and floor */ for (j = 0; j < t->n_state-1; j++) { if (vector_normalize (tp[j], t->n_state) != S3_SUCCESS) E_ERROR("Normalization failed for tmat %d from state %d\n", i, j); vector_nz_floor (tp[j], t->n_state, t->tpfloor); vector_normalize (tp[j], t->n_state); /* Convert to logs3. Take care of special case when tp = 0.0! */ for (k = 0; k < t->n_state; k++) { t->tp[i][j][k] = (tp[j][k] == 0.0) ? LOGPROB_ZERO : logs3(tp[j][k]); } } } ckd_free_2d ((void **) tp); if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&tmp, 1, 1, fp) == 1) E_ERROR("Non-empty file beyond end of data\n"); fclose(fp); E_INFO("Read %d transition matrices of size %dx%d\n", t->n_tmat, t->n_state-1, t->n_state); return S3_SUCCESS; } #if 0 static void tmat_dump (tmat_t *t) { int32 i, from, to; for (i = 0; i < t->n_tmat; i++) { printf ("[%3d]\n", i); for (from = 0; from < t->n_state-1; from++) { printf ("\t"); for (to = 0; to < t->n_state; to++) printf (" %12d", t->tp[i][from][to]); printf ("\n"); } printf ("\n"); } } #endif /* * Check model tprob matrices that they conform to upper-diagonal assumption. */ int32 tmat_chk_uppertri (tmat_t *tmat) { int32 i, from, to; /* Check that each tmat is upper-triangular */ for (i = 0; i < tmat->n_tmat; i++) { for (to = 0; to < tmat->n_state-1; to++) for (from = to+1; from < tmat->n_state-1; from++) if (tmat->tp[i][from][to] > LOGPROB_ZERO) { E_ERROR("Tmat %d not upper triangular\n", i); return -1; } } return 0; } tmat_t *tmat_init (char *tmatfile, float32 tpfloor) { tmat = (tmat_t *) ckd_calloc (1, sizeof(tmat_t)); tmat->tpfloor = tpfloor; tmat_read (tmat, tmatfile); return tmat; } tmat_t *tmat_gettmat ( void ) { return tmat; } <file_sep>/CLP/src/common.cc #include "common.h" #include <cstdio> // I used this one instead of the standard one because for some weird reason this one is faster int getlineH(istream& istr, string& line) { static char temp[1000000]; if(! istr.getline(temp, 1000000)) return 0; line = temp; return 1; } // ///////////////////////////////////////////////////////////////////////// string itoa(int no) { static char s[20]; sprintf(s, "%d", no); return s; } // ///////////////////////////////////////////////////////////////////////// <file_sep>/scons/sphinx4.py import platform import os import fnmatch Import('javapath') srcDir = os.path.normpath('../sphinx4/src/sphinx4') classDir = os.path.normpath('../../scons_build/classes/sphinx4') classpath = '../sphinx4/lib/js.jar' classpath = classpath.replace('/', os.sep) env = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS = '-source 1.5 -classpath "' + classpath + '"', JARCHDIR = classDir) classes = env.Java(target = classDir, source = srcDir ) #Windows sucks but the next three lines make it suck less if platform.system() == 'Windows': env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS -d ${TARGET.attributes.java_classdir} -sourcepath ${SOURCE.dir.rdir()} $SOURCES' env['JAVACCOM']="${TEMPFILE('$_JAVACCOM')}" jarFile = os.path.normpath('../../scons_build/jars/sphinx4.jar') sphinx4 = env.Jar(target = jarFile, source = classDir) Export('sphinx4') <file_sep>/SphinxTrain/src/programs/mk_mdef_gen/hash.c /* ==================================================================== * Copyright (c) 2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * Hashing routines used in mk_mdef_gen * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/s3.h> #include <stdlib.h> #include <string.h> #include "hash.h" unsigned hash(char *s0, char *s1, char *s2, char *s3) { unsigned hashval; for (hashval = 0; *s0 != '\0'; s0++) hashval = *s0 + 31*hashval; for (; *s1 != '\0'; s1++) hashval = *s1 + 31*hashval; for (; *s2 != '\0'; s2++) hashval = *s2 + 31*hashval; for (; *s3 != '\0'; s3++) hashval = *s3 + 31*hashval; return hashval % HASHSIZE; } hashelement_t *lookup(char *b, char *l, char *r, char *wp, hashelement_t **hashtable) { hashelement_t *np; for (np = hashtable[hash(b,l,r,wp)]; np != NULL; np = np->next) if (strcmp(b, np->basephone) == 0 && strcmp(l, np->leftcontext) == 0 && strcmp(r, np->rightcontext) == 0 && strcmp(wp, np->wordposition) == 0) return np; return NULL; } hashelement_t *install(char *b, char *l, char *r, char *wp, hashelement_t **hashtable) { hashelement_t *np; unsigned hashval; if ((np = lookup(b, l, r, wp, hashtable)) == NULL) { np = (hashelement_t *) calloc (1,sizeof(*np)); if (np == NULL || (np->basephone = strdup(b)) == NULL || (np->leftcontext = strdup(l)) == NULL || (np->rightcontext = strdup(r)) == NULL || (np->wordposition = strdup(wp)) == NULL) return NULL; np->dictcount = 0; np->count = 0; hashval = hash(b,l,r,wp); np->next = hashtable[hashval]; hashtable[hashval] = np; } return np; } void freehash(hashelement_t **hash) { int32 i; hashelement_t *e1, *e2; for (i=0; i < HASHSIZE; i++){ e1 = hash[i]; while (e1 != NULL){ e2 = e1->next; free(e1->basephone); if (e1->leftcontext != NULL) free(e1->leftcontext); if (e1->rightcontext != NULL) free(e1->rightcontext); if (e1->wordposition != NULL) free(e1->wordposition); free(e1); e1 = e2; } } free(hash); } unsigned dicthash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 37*hashval; return hashval % DICTHASHSIZE; } dicthashelement_t *dictlookup(char *s, dicthashelement_t **hashtable) { dicthashelement_t *np; for (np = hashtable[dicthash(s)]; np != NULL; np = np->next) if (strcmp(s, np->word) == 0) return np; return NULL; } dicthashelement_t *dictinstall(char *name, dicthashelement_t **hashtable) { dicthashelement_t *np; unsigned hashval; if ((np = dictlookup(name, hashtable)) == NULL) { np = (dicthashelement_t *) calloc (1,sizeof(*np)); if (np == NULL || (np->word = strdup(name)) == NULL) return NULL; np->nphns = 0; hashval = dicthash(name); np->next = hashtable[hashval]; hashtable[hashval] = np; } return np; } void freedicthash(dicthashelement_t **dicthash) { int32 i; dicthashelement_t *e1, *e2; for (i=0; i < DICTHASHSIZE; i++){ e1 = dicthash[i]; while (e1 != NULL){ e2 = e1->next; free(e1->word); for (i=0;i<e1->nphns;i++) free(e1->phones[i]); free(e1->phones); free(e1); e1 = e2; } } free(dicthash); } unsigned phnhash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31*hashval; return hashval % PHNHASHSIZE; } phnhashelement_t *phnlookup(char *s, phnhashelement_t **hashtable) { phnhashelement_t *np; for (np = hashtable[phnhash(s)]; np != NULL; np = np->next) if (strcmp(s, np->phone) == 0) return np; return NULL; } phnhashelement_t *phninstall(char *name, phnhashelement_t **hashtable) { phnhashelement_t *np; unsigned hashval; if ((np = phnlookup(name, hashtable)) == NULL) { np = (phnhashelement_t *) calloc (1,sizeof(*np)); if (np == NULL || (np->phone = strdup(name)) == NULL) return NULL; hashval = phnhash(name); np->next = hashtable[hashval]; hashtable[hashval] = np; } return np; } void freephnhash(phnhashelement_t **phnhash) { int32 i; phnhashelement_t *e1, *e2; for (i=0; i < PHNHASHSIZE; i++){ e1 = phnhash[i]; while (e1 != NULL){ e2 = e1->next; free(e1->phone); free(e1); e1 = e2; } } free(phnhash); } <file_sep>/archive_s3/s3/src/libfbs/Makefile # ==================================================================== # Copyright (c) 1995-2002 Carnegie Mellon University. All rights # reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # This work was supported in part by funding from the Defense Advanced # Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # # THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND # ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ==================================================================== # # # # Makefile # # HISTORY # # 23-Dec-95 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # include $(S3ROOT)/Makefile.defines VPATH = .:.. TARGET = s3decode OBJS = agc.o \ cmn.o \ gauden.o \ senone.o \ interp.o \ tmat.o \ logs3.o \ vector.o \ dict.o \ mdef.o \ lm.o \ fillpen.o \ mllr.o \ fwd.o \ main.o CFLAGS = $(S3DEBUG) $(S2HMMTOPO) ${$(MACHINE)_CFLAGS} $(TARGET): $(OBJS) $(CC) $(CFLAGS) -L$(LIBDIR) -o $(TARGET) $(OBJS) -lfeat -lio -lutil -lm install: $(TARGET) - mv $(BINDIR)/$(TARGET) $(BINDIR)/$(TARGET).old cp $(TARGET) $(BINDIR) rm -f $(BINDIR)/$(TARGET).old logs3: logs3.c $(CC) -g -D_LOGS3_TEST_=1 $(CFLAGS) -L$(LIBDIR) -o logs3 logs3.c -lutil -lm clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/SphinxTrain/src/libs/libcommon/lts.c /*************************************************************************/ /* */ /* Language Technologies Institute */ /* Carnegie Mellon University */ /* Copyright (c) 1999 */ /* All Rights Reserved. */ /* */ /* Permission is hereby granted, free of charge, to use and distribute */ /* this software and its documentation without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of this work, and to */ /* permit persons to whom this work is furnished to do so, subject to */ /* the following conditions: */ /* 1. The code must retain the above copyright notice, this list of */ /* conditions and the following disclaimer. */ /* 2. Any modifications must be clearly marked as such. */ /* 3. Original authors' names are not deleted. */ /* 4. The authors' names are not used to endorse or promote products */ /* derived from this software without specific prior written */ /* permission. */ /* */ /* CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK */ /* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */ /* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ /* SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE */ /* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */ /* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */ /* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */ /* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */ /* THIS SOFTWARE. */ /* */ /*************************************************************************/ /* Author: <NAME> (<EMAIL>) */ /* Date: December 1999 */ /*************************************************************************/ /* */ /* Letter to sound rule support */ /* */ /*************************************************************************/ /* Modified for SphinxTrain by <NAME> <<EMAIL>> */ #include <stdio.h> #include <string.h> #include <ctype.h> #include "s3/s3.h" #include "s3/common.h" #include "s3/lts.h" #include "s3/lexicon.h" #include "s2/byteorder.h" static cst_lts_phone apply_model(cst_lts_letter *vals, cst_lts_addr start, const cst_lts_model *model); static char *cst_substr(const char *str,int start, int length) { char *nstr = NULL; if (str) { nstr = ckd_malloc(length+1); strncpy(nstr,str+start,length); nstr[length] = '\0'; } return nstr; } int lts_apply(const char *in_word,const char *feats, const cst_lts_rules *r, lex_entry_t *out_phones) { int pos, index, i, maxphones; cst_lts_letter *fval_buff; cst_lts_letter *full_buff; cst_lts_phone phone; char *left, *right, *p; char hash; char zeros[8]; char *word; /* Downcase the incoming word unless we are a non-roman alphabet. */ word = ckd_salloc((char *)in_word); if (!r->letter_table) for (i = 0; i < strlen(word); ++i) word[i] = tolower((int)word[i]); /* Fill in out_phones structure as best we can. */ maxphones = strlen(word) + 10; out_phones->phone = ckd_malloc(maxphones * sizeof(char *)); out_phones->ci_acmod_id = ckd_malloc(maxphones * sizeof(acmod_id_t)); out_phones->phone_cnt = 0; /* For feature vals for each letter */ fval_buff = ckd_calloc((r->context_window_size*2)+ r->context_extra_feats, sizeof(cst_lts_letter)); /* Buffer with added contexts */ full_buff = ckd_calloc((r->context_window_size*2)+ /* TBD assumes single POS feat */ strlen(word)+1, sizeof(cst_lts_letter)); if (r->letter_table) { for (i=0; i<8; i++) zeros[i] = 2; sprintf((char *)full_buff,"%.*s%c%s%c%.*s", r->context_window_size-1, zeros, 1, word, 1, r->context_window_size-1, zeros); hash = 1; } else { /* Assumes l_letter is a char and context < 8 */ sprintf((char *)full_buff,"%.*s#%s#%.*s", r->context_window_size-1, "00000000", word, r->context_window_size-1, "00000000"); hash = '#'; } /* Do the prediction forwards (begone, foul LISP!) */ for (pos = r->context_window_size; full_buff[pos] != hash; ++pos) { /* Fill the features buffer for the predictor */ sprintf((char *)fval_buff,"%.*s%.*s%s", r->context_window_size, full_buff+pos-r->context_window_size, r->context_window_size, full_buff+pos+1, feats); if ((!r->letter_table && ((full_buff[pos] < 'a') || (full_buff[pos] > 'z')))) { #ifdef EXCESSIVELY_CHATTY E_WARN("lts:skipping unknown char \"%c\"\n", full_buff[pos]); #endif continue; } if (r->letter_table) index = full_buff[pos] - 3; else index = (full_buff[pos]-'a')%26; phone = apply_model(fval_buff, r->letter_index[index], r->models); /* delete epsilons and split dual-phones */ if (0 == strcmp("epsilon",r->phone_table[phone])) continue; /* dynamically grow out_phones if necessary. */ if (out_phones->phone_cnt + 2 > maxphones) { maxphones += 10; out_phones->phone = ckd_realloc(out_phones->phone, maxphones*sizeof(char *)); out_phones->ci_acmod_id = ckd_realloc(out_phones->ci_acmod_id, maxphones * sizeof(acmod_id_t)); } if ((p=strchr(r->phone_table[phone],'-')) != NULL) { left = cst_substr(r->phone_table[phone],0, strlen(r->phone_table[phone])-strlen(p)); right = cst_substr(r->phone_table[phone], (strlen(r->phone_table[phone])-strlen(p))+1, (strlen(p)-1)); out_phones->phone[out_phones->phone_cnt++] = left; out_phones->phone[out_phones->phone_cnt++] = right; } else out_phones->phone[out_phones->phone_cnt++] = ckd_salloc((char *)r->phone_table[phone]); } ckd_free(full_buff); ckd_free(fval_buff); ckd_free(word); return S3_SUCCESS; } static cst_lts_phone apply_model(cst_lts_letter *vals,cst_lts_addr start, const cst_lts_model *model) { /* because some machines (ipaq/mips) can't deal with addrs not on */ /* word boundaries we use a static and copy the rule values each time */ /* so we know its properly aligned */ /* Hmm this still might be wrong on some machines that align the */ /* structure cst_lts_rules differently */ cst_lts_rule state; unsigned short nstate; static const int sizeof_cst_lts_rule = 6; memmove(&state,&model[start*sizeof_cst_lts_rule],sizeof_cst_lts_rule); for ( ; state.feat != CST_LTS_EOR; ) { if (vals[state.feat] == state.val) nstate = state.qtrue; else nstate = state.qfalse; /* This should really happen at compilation time */ /* if (WORDS_BIGENDIAN) */ /* byteswap macros are slightly bogus */ SWAP_W(nstate); memmove(&state,&model[nstate*sizeof_cst_lts_rule],sizeof_cst_lts_rule); } return (cst_lts_phone)state.val; } #ifdef UNIT_TEST /* gcc -DUNIT_TEST -I../../../include ckd_alloc.c cmu6_lts_rules.c err.c lts.c */ void lex_print(lex_entry_t *ent) { int i; for (i = 0; i < ent->phone_cnt; ++i) { printf("%s ", ent->phone[i]); } printf("\n"); } int main(int argc, char *argv[]) { lex_entry_t out; int i; lts_apply("HELLO", "", &cmu6_lts_rules, &out); lex_print(&out); ckd_free(out.phone); ckd_free(out.ci_acmod_id); lts_apply("EXCELLENT", "", &cmu6_lts_rules, &out); lex_print(&out); ckd_free(out.phone); ckd_free(out.ci_acmod_id); return 0; } #endif <file_sep>/SphinxTrain/include/s3/feat.h /* ==================================================================== * Copyright (c) 1995-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: feat.h * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #ifndef FEAT_H #define FEAT_H #ifdef __cplusplus extern "C" { #endif #if 0 } #endif #include <s3/vector.h> #include <s3/prim_type.h> #define FEAT_ID_SPHINX_II_STD 0 #define FEAT_ID_V1 1 #define FEAT_ID_V2 2 #define FEAT_ID_V3 3 #define FEAT_ID_V4 4 #define FEAT_ID_V5 5 #define FEAT_ID_V6 6 #define FEAT_ID_V7 7 #define FEAT_ID_V8 8 #define FEAT_ID_MAX 9 #define FEAT_ID_NONE 0xffffffff /* These default values will be used by the command line parser, * therefore they're defined as strings */ #define FEAT_DEFAULT_CEP_LENGTH "13" #define FEAT_DEFAULT_FEATURE_TYPE "1s_c_d_dd" #define FEAT_DEFAULT_FEATURE_EXTENSION "mfc" typedef struct feat_conf_s { void (*set_in_veclen)(uint32 len); const char * (*doc)(void); uint32 (*id)(void); uint32 (*n_stream)(void); uint32 (*blksize)(void); const uint32 * (*vecsize)(void); vector_t ** (*compute)(vector_t *mfcc, uint32 *inout_n_frame); void (*print)(const char *label, vector_t **f, uint32 n_frame); } feat_conf_t; int feat_set(const char *id_name); uint32 feat_id(void); const char * feat_doc(void); void feat_set_in_veclen(uint32 len); int32 feat_read_lda(const char *ldafile, uint32 dim); int32 ** feat_set_subvecs(char const *str); uint32 feat_mfcc_len(void); uint32 feat_n_stream(void); const uint32 * feat_vecsize(void); uint32 feat_blksize(void); int feat_ck_vecsize(const char *tag, const uint32 *vecsize, uint32 n_stream); vector_t ** feat_compute(vector_t *mfcc, uint32 *inout_n_frame); void feat_print(const char *label, vector_t **feat, uint32 n_frame); void feat_print_mfcc(vector_t *mfcc, uint32 n_frame); vector_t ** feat_alloc(uint32 n_frames); void feat_free(vector_t **f); #define FEAT_NO_SIZE 0xffffffff #ifdef __cplusplus } #endif #endif /* FEAT_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.4 2004/07/21 17:46:09 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:30 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:12 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:30 awb * *** empty log message *** * * Revision 1.7 97/07/16 11:39:10 eht * *** empty log message *** * * Revision 1.6 1996/08/05 13:00:10 eht * - Begin feat control block type of structure * - Add silence deletion function * * Revision 1.5 1996/03/25 15:46:57 eht * Added ability to set input feature vector size * changed feat_comp_id() to feat_id() * * Revision 1.4 1996/01/26 18:33:28 eht * *** empty log message *** * * Revision 1.3 1995/12/04 15:00:27 eht * Added prototype for feat_n_stream() * * Revision 1.2 1995/10/09 20:55:35 eht * Changes needed for prim_type.h * * Revision 1.1 1995/08/15 13:44:14 eht * Initial revision * * */ <file_sep>/archive_s3/s3.0/pgm/makedict/Makefile include ../../Makefile.defines VPATH = .:.. makedict : makedict.c $(CC) $(S3DEBUG) $(CFLAGS) -o $@ $> ../../../src/libmain/$(MACHINE)/dict.o ../../../src/libmain/$(MACHINE)/mdef.o -lmisc -lutil clean : rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# <file_sep>/SphinxTrain/python/cmusphinx/mllr.py #!/usr/bin/env python """ Adapt acoustic models using maximum-likelihood linear regression. This module implements single-class mean and variance adaptation using MLLR as described in <NAME> & P.C. Woodland, "Mean and Variance Adaptation within the MLLR Framework", Computer Speech and Language, vol. 10, pp 249-264. TODO: Multiple regression classes. """ # Copyright (c) 2006 Carnegie Mellon University # # You may copy and modify this freely under the same terms as # Sphinx-III __author__ = "<NAME> <<EMAIL>>" __version__ = "$Revision $" import numpy as np import sys import s3gaucnt import s3gau import getopt import s3lda def extend(mean): """ Produce an "extended mean vector". """ return np.concatenate(((1,),mean)) def estimate_mllr_mean(stats, inmean, invar): """ Estimate an MLLR transformation of the means based on observed statistics. This function calculates an MLLR transformation W (an n by n+1 matrix) for each feature stream which, when applied to C{inmean}, maximizes the likelihood of the data as represented by C{stats}. Currently this does only one class, but it will promptly be extended once the "learning exercise" is over. @param stats: Observation counts, as returned by C{cmusphinx.s3gaucnt.accumdirs} or C{cmusphinx.s3gaucnt.accumdirs_full}. @type stats: cmusphinx.s3gaucnt.S3GauCnt @param inmean: Input mean parameters @type inmean: cmusphinx.s3gau.S3Gau @param invar: Input diagonal covariance parameters @type inmvar: cmusphinx.s3gau.S3Gau @return: MLLR transformations, one per feature stream @rtype: list(numpy.ndarray) """ # List of W matrices Ws = [] for i in range(0, inmean.n_feat): ndim = inmean.veclen[i] # Collection of G matrices G = np.zeros((ndim, ndim+1, ndim+1)) # Z matrix (for the single class and stream) Z = np.zeros((ndim, ndim+1)) # W matrix W = np.zeros((ndim, ndim+1)) # One-class MLLR: just sum over all densities for j in range(0, inmean.n_mgau): for k in range(0, inmean.density): # Extended mean vector xmean = extend(inmean[j][i][k]) # Inverse variance (also use only the diagonal) invvar = invar[j][i][k] if len(invvar.shape) > 1: invvar = np.diag(invvar) invvar = 1./invvar.clip(1e-5,np.inf) # Sum of posteriors (i.e. sum_t L_m_r(t)) dnom = stats.dnom[j,i,k] # Sum of mean statistics obsmean = stats.mean[j][i][k] for l in range(0, ndim): # v_{ll} = sum_t L(t) \Sigma_{ll}^{-1} # D = \ksi \ksi^T # G^{l} = v_{ll} D G[l] += dnom * invvar[l] * np.outer(xmean, xmean) # Z = \sum_r\sum_t L(t) \Sigma_r^{-1} o(t) \ksi_r^T Z += np.outer(invvar * obsmean, xmean) # Now solve for the rows of W for j in range(0, ndim): W[j] = np.linalg.solve(G[j], Z[j]) Ws.append(W) return Ws def write_mllr(fout, Ws, Hs=None): """ Write out MLLR transformations of the means in the format that Sphinx3 understands. @param Ws: MLLR transformations of means, one per feature stream @ptype Ws: list(numpy.ndarray) @param Hs: MLLR transformations of variances, one per feature stream @ptype Hs: list(numpy.ndarray) @param fout: Filename or filehandle to write to. @ptype fout: string or file """ if isinstance(fout, file): fh = fout else: fh = file(fout, 'w') # One-class MLLR for now fh.write("%d\n" % 1) fh.write("%d\n" % len(Ws)) for i,W in enumerate(Ws): fh.write("%d\n" % W.shape[0]) # Write rotation and bias terms separately for w in W: for x in w[1:]: fh.write("%f " % x) fh.write("\n") for x in W[:,0]: fh.write("%f " % x) fh.write("\n") if Hs != None: for x in Hs[i]: fh.write("%f " % x) fh.write("\n") else: fh.write("1.0 " * W.shape[0]) fh.write("\n") def estimate_mllr_variance(stats, inmean, invar, Ws): """ Estimate a diagonal MLLR transformation of the variances based on observed statistics. This function calculates an MLLR transformation H (a diagonal nxn matrix, represented as a vector) which maximizes the likelihood of the data as represented by C{stats}, when applied to the inverse Cholesky factor of the covariance matrix B as B^T H B. For diagonal covariances this reduces to a scaling of the variance by the diagonal of H, since the diagonal b = (sqrt(var^{-1}))^{-1} = var^{0.5} and thus B^T H B = \Sigma H when \Sigma and H are diagonal. Note that this function will raise an exception if -2passvar yes was enabled when collecting the observation counts, since it requires them to consist of the sum of the outer products of the observation vectors scaled by their posterior probabilities, (L_m_r(t)o(t)o(t)^T in Cambridge papers). Currently this does only one class and one stream, but it will promptly be extended once the "learning exercise" is over. @param stats: Observation counts, as returned by C{cmusphinx.s3gaucnt.accumdirs} or C{cmusphinx.s3gaucnt.accumdirs_full}. @type stats: cmusphinx.s3gaucnt.S3GauCnt @param inmean: Input mean parameters @type inmean: cmusphinx.s3gau.S3Gau @param invar: Input covariance parameters @type inmvar: cmusphinx.s3gau.S3Gau @param Ws: Previously computed MLLR transformations of means @ptype Ws: list(numpy.ndarray) @return: MLLR transformations of variances @rtype: list(numpy.ndarray) """ if stats.pass2var: raise RuntimeException, "Statistics using -2passvar yes are not allowed" Hs = [] for i, W in enumerate(Ws): ndim = inmean.veclen[i] # Output "matrix" H H = np.zeros(ndim) # One-class MLLR: just sum over all densities norm = 0 for j in range(0, inmean.n_mgau): for k in range(0, inmean.density): # Extended mean vector xmean = extend(inmean[j][i][k]) # Transform it mean = np.dot(W, xmean) # Cholesky factorization not needed for diagonals... invvar = 1./invar[j][i][k].clip(1e-5,np.inf) if len(invvar.shape) > 1: invvar = np.diag(invvar) # Note: the code actually just computes diagonals # sum(L_m_r o o^T) (obs squared) nom = stats.var[j][i][k] # \hat mu_m_r \bar o_m_r^T (cross term 1) nom -= mean * stats.mean[j][i][k] # \bar o_m_r \hat mu_m_r^T (cross term 2) nom -= stats.mean[j][i][k] * mean # \mu_m_r \mu_m_r^T sum(L_m_r) (mean squared) nom += mean * mean * stats.dnom[j][i][k] # Multiply in variances and accumulate H += invvar * nom # Accumulate normalizer norm += stats.dnom[j][i][k] Hs.append(H / norm) return Hs if __name__ == '__main__': def usage(): sys.stderr.write("Usage: %s INMEAN INVAR ACCUMDIRS...\n" % sys.argv[0]) try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) except getopt.GetoptError: usage() sys.exit(2) if len(args) < 3: usage() sys.exit(2) ldafn = None for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() inmean = s3gau.open(args[0]) invar = s3gau.open(args[1]) accumdirs = args[2:] stats = s3gaucnt.accumdirs(accumdirs) Ws = estimate_mllr_mean(stats, inmean, invar) Hs = estimate_mllr_variance(stats, inmean, invar, Ws) write_mllr(sys.stdout, Ws, Hs) <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/confdesigner/PortWidget.java /* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. */ package edu.cmu.sphinx.tools.confdesigner; import org.netbeans.api.visual.laf.LookFeel; import org.netbeans.api.visual.layout.LayoutFactory; import org.netbeans.api.visual.model.ObjectState; import org.netbeans.api.visual.widget.ImageWidget; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.widget.Widget; import org.openide.ErrorManager; import org.openide.util.Utilities; import javax.swing.*; import java.awt.*; /** * A widget representing image. The origin of the widget is at its top-left corner. * * @author <NAME> */ // TODO - alignment public class PortWidget extends Widget { private Image image; private Image disabledImage; private int width, height; private boolean paintAsDisabled; private static final Image SHAPE_IMAGE = Utilities.loadImage("org/netbeans/modules/visual/resources/vmd-pin.png"); private static final Color COLOR_NORMAL = new Color(0xBACDF0); private static final Color COLOR_HOVERED = Color.BLACK; private static final Color COLOR_SELECTED = new Color(0x748CC0); private static final Color COLOR_HIGHLIGHTED = new Color(49, 106, 197); private ImageWidget imageWidget; private LabelWidget labelWidget; /** * Creates an image widget. * * @param scene the scene * @param label the label */ public PortWidget(Scene scene, String label) { super(scene); LookFeel lookFeel = getScene().getLookFeel(); setLayout(LayoutFactory.createHorizontalFlowLayout(LayoutFactory.SerialAlignment.LEFT_TOP, 5)); imageWidget = new ImageWidget(scene); setImage(SHAPE_IMAGE); addChild(imageWidget); labelWidget = new LabelWidget(scene); setLabel(label); labelWidget.setFont(scene.getDefaultFont().deriveFont(14.0f)); addChild(labelWidget); setState(ObjectState.createNormal()); } /** * Sets a label. * * @param label the label */ public final void setLabel(String label) { labelWidget.setLabel(label); } /** * Returns the image widget part of the icon node widget. * * @return the image widget */ public final ImageWidget getImageWidget() { return imageWidget; } /** * Returns the label widget part of the icon node widget. * * @return the label widget */ public final LabelWidget getLabelWidget() { return labelWidget; } /** * Returns an image. * * @return the image */ public Image getImage() { return image; } /** * Sets an image * * @param image the image */ public void setImage(Image image) { if (this.image == image) return; int oldWidth = width; int oldHeight = height; this.image = image; this.disabledImage = null; width = image != null ? image.getWidth(null) : 0; height = image != null ? image.getHeight(null) : 0; if (oldWidth == width && oldHeight == height) repaint(); else revalidate(); } /** * Returns whether the label is painted as disabled. * * @return true, if the label is painted as disabled */ public boolean isPaintAsDisabled() { return paintAsDisabled; } public Widget getPort() { return imageWidget; } /** * Sets whether the label is painted as disabled. * * @param paintAsDisabled if true, then the label is painted as disabled */ public void setPaintAsDisabled(boolean paintAsDisabled) { boolean repaint = this.paintAsDisabled != paintAsDisabled; this.paintAsDisabled = paintAsDisabled; if (repaint) repaint(); } /** * Implements the widget-state specific look of the widget. * * @param previousState the previous state * @param state the new state */ public void notifyStateChanged(ObjectState previousState, ObjectState state) { if (state.isHovered()) setForeground(COLOR_HOVERED); else if (state.isSelected()) setForeground(COLOR_SELECTED); else if (state.isHighlighted()) setForeground(COLOR_HIGHLIGHTED); else if (state.isFocused()) setForeground(COLOR_HOVERED); else setForeground(COLOR_NORMAL); //todo enable me! // if (state.isSelected ()) { // setControlPointShape (PointShape.SQUARE_FILLED_SMALL); // setEndPointShape (PointShape.SQUARE_FILLED_BIG); // } else { // setControlPointShape (PointShape.NONE); // setEndPointShape (POINT_SHAPE_IMAGE); // } } /** * Calculates a client area of the image * * @return the calculated client area */ protected Rectangle calculateClientArea() { if (image != null) return new Rectangle(0, 0, width, height); return super.calculateClientArea(); } /** Paints the image widget. */ protected void paintWidget() { if (image == null) return; Graphics2D gr = getGraphics(); if (image != null) { if (paintAsDisabled) { if (disabledImage == null) { disabledImage = GrayFilter.createDisabledImage(image); MediaTracker tracker = new MediaTracker(getScene().getView()); tracker.addImage(disabledImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { ErrorManager.getDefault().notify(e); } } gr.drawImage(disabledImage, 0, 0, null); } else gr.drawImage(image, 0, 0, null); } } } <file_sep>/archive_s3/s3.2/src/libutil/heap.c /* * heap.c -- Generic heap structure for inserting in any and popping in sorted * order. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1999 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 05-Mar-99 <NAME> (<EMAIL>) at Carnegie Mellon University * Fixed bug in heap_destroy() (in while loop exit condition). * * 23-Dec-96 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "heap.h" #include "ckd_alloc.h" typedef struct heap_s { void *data; /* Application data at this node */ int32 val; /* Associated with above application data; according to which heap is sorted (in ascending order) */ int32 nl, nr; /* #left/right descendants of this node (for balancing heap) */ struct heap_s *l; /* Root of left descendant heap */ struct heap_s *r; /* Root of right descendant heap */ } heapnode_t; #if 0 static void heap_dump (heapnode_t *top, int32 level) { int32 i; if (! top) return; for (i = 0; i < level; i++) printf (" "); /* print top info */ heap_dump (top->l, level+1); heap_dump (top->r, level+1); } #endif heap_t heap_new ( void ) { heapnode_t **h; h = (heapnode_t **) ckd_calloc (1, sizeof(heapnode_t *)); *h = NULL; return ((heap_t) h); } static heapnode_t *subheap_insert (heapnode_t *root, void *data, int32 val) { heapnode_t *h; void *tmpdata; int32 tmpval; if (! root) { h = (heapnode_t *) mymalloc (sizeof(heapnode_t)); h->data = data; h->val = val; h->l = h->r = NULL; h->nl = h->nr = 0; return h; } /* Root already exists; if new value is less, replace root node */ if (root->val > val) { tmpdata = root->data; tmpval = root->val; root->data = data; root->val = val; data = tmpdata; val = tmpval; } /* Insert new or old (replaced) node in right or left subtree; keep them balanced */ if (root->nl > root->nr) { root->r = subheap_insert (root->r, data, val); root->nr++; } else { root->l = subheap_insert (root->l, data, val); root->nl++; } return root; } int32 heap_insert (heap_t heap, void *data, int32 val) { heapnode_t **hp; hp = (heapnode_t **) heap; *hp = subheap_insert (*hp, data, val); return 0; } static heapnode_t *subheap_pop (heapnode_t *root) { heapnode_t *l, *r; /* Propagate best value from below into root, if any */ l = root->l; r = root->r; if (! l) { if (! r) { myfree ((char *) root, sizeof(heapnode_t)); return NULL; } else { root->data = r->data; root->val = r->val; root->r = subheap_pop (r); root->nr--; } } else { if ((! r) || (l->val < r->val)) { root->data = l->data; root->val = l->val; root->l = subheap_pop (l); root->nl--; } else { root->data = r->data; root->val = r->val; root->r = subheap_pop (r); root->nr--; } } return root; } int32 heap_pop (heap_t heap, void **data, int32 *val) { heapnode_t **hp, *h; hp = (heapnode_t **) heap; h = *hp; if (! h) return 0; *data = h->data; *val = h->val; *hp = subheap_pop (h); return 1; } int32 heap_top (heap_t heap, void **data, int32 *val) { heapnode_t **hp, *h; hp = (heapnode_t **) heap; h = *hp; if (! h) return 0; *data = h->data; *val = h->val; return 1; } int32 heap_destroy (heap_t heap) { void *data; int32 val; /* Empty the heap and free it */ while (heap_pop (heap, &data, &val) > 0); ckd_free ((char *)heap); return 0; } <file_sep>/archive_s3/s3.0/pgm/misc/sendump-read.c #include <libutil/libutil.h> static int32 pval[256][256]; static unsigned char pid[256][20000]; main (int32 argc, char *argv[]) { int32 i, c, f, n, nwt, nsen; char line[4096]; FILE *fp; if (argc != 2) E_FATAL("Usage: %s <senfile>\n", argv[0]); if ((fp = fopen(argv[1], "rb")) == NULL) E_FATAL("fopen(%s,rb) failed\n", argv[1]); for (;;) { if (fread (&n, sizeof(int32), 1, fp) != 1) E_FATAL("fread linelen failed\n"); if (n == 0) break; if (fread (line, sizeof(char), n, fp) != n) E_FATAL("fread(line) failed\n"); } if (fread (&nwt, sizeof(int32), 1, fp) != 1) E_FATAL("fread(nwt) failed\n"); if (fread (&nsen, sizeof(int32), 1, fp) != 1) E_FATAL("fread(nsen) failed\n"); for (f = 0; f < 4; f++) { for (c = 0; c < 256; c++) { if (fread (pval[c], sizeof(int32), 256, fp) != 256) break; if (fread (pid[c], 1, nsen, fp) != nsen) E_FATAL("fread(pid) failed\n"); } for (i = 0; i < nsen; i++) { printf ("%d %d\n", f, i); for (c = 0; c < 256; c++) printf (" %7d", pval[c][pid[c][i]]); printf ("\n"); } } } <file_sep>/pocketsphinx/test/unit/test_tokentree.c #include <pocketsphinx.h> #include <stdio.h> #include <string.h> #include <time.h> #include "pocketsphinx_internal.h" #include "tokentree.h" #include "test_macros.h" int main(int argc, char *argv[]) { tokentree_t *tree; token_t *root, *tok; void *data; int32 val; tree = tokentree_init(); TEST_ASSERT(root = tokentree_add(tree, 0, 0, NULL)); heap_top(tree->leaves, &data, &val); TEST_EQUAL(data, (void *)root); tokentree_add(tree, 10, 4, root); tok = tokentree_add(tree, 8, 1, root); tokentree_add(tree, 33, 2, root); tokentree_add(tree, 14, 3, root); heap_top(tree->leaves, &data, &val); TEST_EQUAL(data, (void *)tok); TEST_EQUAL(heap_size(tree->leaves), 4); tokentree_prune(tree, 15); TEST_EQUAL(heap_size(tree->leaves), 3); tokentree_add(tree, 8, 1, root); tokentree_add(tree, 42, 6, root); tokentree_prune_topn(tree, 3); TEST_EQUAL(heap_size(tree->leaves), 3); tokentree_free(tree); return 0; } <file_sep>/archive_s3/s3.0/pgm/timealign/Makefile # # Makefile # # HISTORY # # 07-Jan-97 <NAME> (<EMAIL>) at Carnegie Mellon University # Created. # VPATH = .:.. include ../../../Makefile.defines TARGET = timealign OBJS = wdnet.o \ align.o \ align-main.o $(TARGET): $(OBJS) $(CC) $(CFLAGS) -o $(TARGET) $(OBJS) -lmain -lmisc -lfeat -lio -lutil -lm rm align-main.o clean: rm -f *.o *.a *.BAK *.CKP .*.BAK .*.CKP *~ .*~ #*# wdnet-test : wdnet.c $(CC) $(S3DEBUG) -D_WDNET_TEST_=1 $(CFLAGS) -o $@ $> -lmain -lmisc -lio -lutil -lm install: $(TARGET) cp $(TARGET) $(S3BINDIR) <file_sep>/archive_s3/s3/src/misc/line2wid.h /* ==================================================================== * Copyright (c) 1995-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * line2wid.h -- Convert a ref or hyp line (word string sequence) to an array of * word ids. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 27-Feb-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #ifndef _LINE2WID_ #define _LINE2WID_ #include <main/s3types.h> #include <main/dict.h> /* * Convert a line of words terminated by an (uttid) into a corresponding array of word * ids. The word ids may be BAD_WID if not found in the given pronunciation dictionary. * Return value: no. of words read into wid; -ve if any error occurs. */ int32 line2wid (dict_t *dict, /* In: Dictionary to use for building word ids */ char *line, /* In: Input text string terminated by (uttid) */ s3wid_t *wid, /* Out: Array of word-ids for words in line; wid[] must be allocated by caller */ int32 max_n_wid, /* In: Size of wid[] */ int32 add_oov, /* In: If TRUE, add OOV words to dictionary with no pronunciation; otherwise leave their word id as BAD_WID */ char *uttid); /* Out: Utterance id encountered at the end of line; uttid[] must be allocated by caller */ /* * Check if word is of the form (uttid). If so, copy into uttid and return 1. * Otherwise return 0. uttid must be allocated by caller and long enough to fit * any utterance id. */ int32 is_uttid (char *word, char *uttid); #endif <file_sep>/scons/dictator.py import platform import os import fnmatch Import('javapath') Import('sphinx4') Import('common') srcDir = os.path.normpath('../tools/dictator/src/java') classDir = os.path.normpath('../../scons_build/classes/dictator') libpath = '..' + os.sep + 'tools' + os.sep + 'common' + os.sep + 'lib' + os.sep classpath = libpath + 'batch.jar' + os.pathsep classpath += libpath + 'dom4j-1.6.1.jar' + os.pathsep classpath += libpath + 'forms_rt_license.jar' + os.pathsep classpath += libpath + 'forms_rt.jar' + os.pathsep classpath += libpath + 'javolution.jar' + os.pathsep classpath += str(sphinx4[0]) + os.pathsep classpath += str(common[0]) wsjdmp = Install(classDir, '../tools/common/data/wsj5k.DMP') env = Environment(ENV = {'PATH' : javapath }, JAVACFLAGS = '-source 1.5 -classpath "' + classpath + '"', JARCHDIR = classDir) classes = env.Java(target = classDir, source = srcDir ) jarFile = os.path.normpath('../../scons_build/jars/dictator.jar') manifest = os.path.normpath('../tools/dictator/build/MANIFEST.MF') dictator = env.Jar(target = jarFile, source = [classDir, manifest]) Depends(classes, common) Depends(wsjdmp, classes) Depends(dictator, wsjdmp) Export('dictator') <file_sep>/archive_s3/s3.3/Makefile.am SUBDIRS = src \ doc \ scripts EXTRA_DIST = autogen.sh test: $(LIBTOOL) --mode=execute src/programs/livepretend \ $(top_srcdir)/model/lm/an4/an4.ctl \ $(top_srcdir)/model/lm/an4 \ $(top_srcdir)/model/lm/an4/args.an4.test <file_sep>/SphinxTrain/src/libs/libs2io/pset_io.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: pset_io.c * * Description: * Read a file which "defines" the simple questions for state * clustering * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include <s3/pset_io.h> #include <s3/ckd_alloc.h> #include <s3/err.h> #include <s3/s3.h> #include <string.h> #include <stdlib.h> #include <stdio.h> pset_t * read_pset_file(const char *file_name, acmod_set_t *acmod_set, uint32 *n_pset) { FILE *fp; char line[1024]; char sav_line[1024]; uint32 i, j, lc, n_phone, p; pset_t *out; uint32 n_ci; fp = fopen(file_name, "r"); if (fp == NULL) { E_WARN_SYSTEM("Unable to open %s", file_name); return NULL; } for (lc = 0; fgets(line, 1024, fp) != NULL; lc++); out = ckd_calloc(lc, sizeof(pset_t)); *n_pset = lc; rewind(fp); n_ci = acmod_set_n_ci(acmod_set); for (i = 0; i < lc; i++) { fgets(line, 1024, fp); line[strlen(line)-1] = '\0'; strcpy (sav_line, line); strtok(line, " \t"); for (n_phone = 0; strtok(NULL, " \t"); n_phone++); strcpy (line, sav_line); out[i].n_phone = n_phone; if (n_phone > 0) { out[i].phone = ckd_calloc(n_phone, sizeof(acmod_id_t)); out[i].member = ckd_calloc(n_ci, sizeof(uint32)); out[i].name = strdup(strtok(line, " \t")); for (j = 0; j < n_phone; j++) { char *phone = strtok(NULL, " \t"); p = (uint32)acmod_set_name2id(acmod_set, phone); if (p == (uint32)NO_ACMOD) { E_WARN("Unknown phone %s in set %s\n", phone, out[i].name); continue; } out[i].phone[j] = (acmod_id_t)p; out[i].member[p] = TRUE; } } else { out[i].name = strdup(strtok(line, " \t")); out[i].posn = ckd_calloc(N_WORD_POSN, sizeof(uint32)); if (strcmp(out[i].name, "WDBNDRY_B") == 0) { out[i].posn[(int)WORD_POSN_BEGIN] = TRUE; } else if (strcmp(out[i].name, "WDBNDRY_E") == 0) { out[i].posn[(int)WORD_POSN_END] = TRUE; } else if (strcmp(out[i].name, "WDBNDRY_S") == 0) { out[i].posn[(int)WORD_POSN_SINGLE] = TRUE; } else if (strcmp(out[i].name, "WDBNDRY_I") == 0) { out[i].posn[(int)WORD_POSN_INTERNAL] = TRUE; } else { E_FATAL("Unknown null question %s\n", out[i].name); } out[i].phone = NULL; } } return out; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.6 2006/03/14 22:43:25 dhdfu * small correctness fix as suggested by Evandro - use NO_ACMOD instead of -1 * * Revision 1.5 2006/03/14 19:30:31 dhdfu * Ignore (with a warning) unknown phones in a questions file, instead of segfaulting * * Revision 1.4 2004/07/21 18:30:31 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.3 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.1 97/07/16 11:36:22 eht * Initial revision * * */ <file_sep>/tools/confdesigner/src/edu/cmu/sphinx/tools/executor/BatchFileExecutor.java package edu.cmu.sphinx.tools.executor; import edu.cmu.sphinx.recognizer.Recognizer; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Component; import edu.cmu.sphinx.util.props.S4String; import edu.cmu.sphinx.frontend.util.AudioFileDataSource; import edu.cmu.sphinx.result.Result; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; /** * DOCUMENT ME! * * @author <NAME> */ public class BatchFileExecutor implements Executable { @S4Component(type = Recognizer.class) public static final String PROP_RECOGNIZER = "recognizer"; @S4Component(type = AudioFileDataSource.class) public static final String PROP_DATA_SOURCE = "dataSource"; @S4String public static final String PROP_DRIVER = "batchFile"; private Recognizer recognizer; private String batchFile; private AudioFileDataSource dataSource; private String name; public void doExecute() { List<File> files = readDriver(batchFile); for (File file : files) { dataSource.setAudioFile(file, file.getPath()); Result r; while ((r = recognizer.recognize()) != null) { System.out.print(r.getBestResultNoFiller() + ""); } System.out.println(""); } } public void newProperties(PropertySheet ps) throws PropertyException { dataSource = (AudioFileDataSource) ps.getComponent(PROP_DATA_SOURCE); recognizer = (Recognizer) ps.getComponent(PROP_RECOGNIZER); batchFile = ps.getString(PROP_DRIVER); name = ps.getInstanceName(); assert batchFile != null : "batch file is not set!"; } public String getName() { return null; } /** Reads and verifies a driver file. */ public static List<File> readDriver(String fileName) { File inputFile = new File(fileName); List<File> driverFiles = null; try { if (!inputFile.isFile() || !inputFile.canRead()) throw new IllegalArgumentException("file to read is not valid"); BufferedReader bf = new BufferedReader(new FileReader(inputFile)); driverFiles = new ArrayList<File>(); String line; while ((line = bf.readLine()) != null && line.trim().length() != 0) { File file = new File(line); assert file.isFile() : "file " + file + " does not exist!"; driverFiles.add(file); } bf.close(); } catch (IOException e) { e.printStackTrace(); } assert driverFiles != null; return driverFiles; } } <file_sep>/SphinxTrain/src/programs/bw/train_cmd_ln.c /* ==================================================================== * Copyright (c) 1994-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /********************************************************************* * * File: train_cmd_ln.c * * Description: * * Author: * <NAME> (<EMAIL>) *********************************************************************/ #include "train_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/err.h> #include <s3/s3.h> #include <sys_compat/file.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <assert.h> int validate_writeable_dir(char *switch_name, void *arg) { #ifndef WIN32 char *path = arg; struct stat s; if (path == NULL) { E_ERROR("%s is a necessary switch\n", switch_name); return FALSE; } if (stat(path, &s) < 0) { E_ERROR("%s %s does not exist or is inaccessible\n", switch_name, path); return FALSE; } if (!S_ISDIR(s.st_mode)) { E_ERROR("%s %s is not a directory\n", switch_name, path); return FALSE; } if ((s.st_mode && S_IWOTH) || ((s.st_uid == getuid()) && (s.st_mode && S_IWUSR)) || ((s.st_gid == getgid()) && (s.st_mode && S_IWGRP))) { return TRUE; } else { E_ERROR("%s %s is not writeable\n", switch_name, path); return FALSE; } #else /* WIN32 */ /* Do no validation for now. Need to figure out WIN32 compatible way */ return TRUE; #endif } int validate_opt_writeable_dir(char *switch_name, void *arg) { #ifndef WIN32 char *path = arg; struct stat s; if (path == NULL) { return TRUE; } if (stat(path, &s) < 0) { E_ERROR("%s %s does not exist or is inaccessible\n", switch_name, path); return FALSE; } if (!S_ISDIR(s.st_mode)) { E_ERROR("%s %s is not a directory\n", switch_name, path); return FALSE; } if ((s.st_mode && S_IWOTH) || ((s.st_uid == getuid()) && (s.st_mode && S_IWUSR)) || ((s.st_gid == getgid()) && (s.st_mode && S_IWGRP))) { return TRUE; } else { E_ERROR("%s %s is not writeable\n", switch_name, path); return FALSE; } #else /* WIN32 */ /* Do no validation for now. Need to figure out WIN32 compatible way */ return TRUE; #endif } int validate_readable_dir(char *switch_name, void *arg) { #ifndef WIN32 char *path = arg; struct stat s; if (path == NULL) { E_ERROR("%s is a necessary switch\n", switch_name); return FALSE; } if (stat(path, &s) < 0) { E_ERROR("%s %s does not exist or is inaccessible\n", switch_name, path); return FALSE; } if (!S_ISDIR(s.st_mode)) { E_ERROR("%s %s is not a directory\n", switch_name, path); return FALSE; } if ((s.st_mode && S_IROTH) || ((s.st_uid == getuid()) && (s.st_mode && S_IRUSR)) || ((s.st_gid == getgid()) && (s.st_mode && S_IRGRP))) { return TRUE; } else { E_ERROR("%s %s is not readable\n", switch_name, path); return FALSE; } #else /* WIN32 */ /* Do no validation for now. Need to figure out a WIN32 compatible way */ return TRUE; #endif } int validate_agc(char *switch_name, void *arg) { if ((strcmp(arg, "max") == 0) || (strcmp(arg, "emax") == 0) || (strcmp(arg, "none") == 0)) { return TRUE; } else { E_ERROR("Unknown agc type %s %s\n", switch_name, arg); return FALSE; } assert(FALSE); } int validate_cmn(char *switch_name, void *arg) { if ((strcmp(arg, "current") == 0) || (strcmp(arg, "none") == 0) || (strcmp(arg, "prior") == 0)) { return TRUE; } else { E_ERROR("Unknown CMN type %s %s\n", switch_name, arg); } return TRUE; } int validate_silcomp(char *switch_name, void *arg) { if ((strcmp(arg, "none") == 0) || (strcmp(arg, "sildelfn") == 0) || (strcmp(arg, "prior") == 0) || (strcmp(arg, "current") == 0)) { return TRUE; } else { E_ERROR("Unknown silence compression type %s %s\n", switch_name, arg); return FALSE; } assert(FALSE); } /* defines, parses and (partially) validates the arguments given on the command line */ int train_cmd_ln_parse(int argc, char *argv[]) { uint32 isHelp; uint32 isExample; const char helpstr[] = "Description:\n\ Strictly speaking, bw only implements the first-part of the Baum-Welch \n\ algorithm. That is it go through forward and backward algortihm and\n\ collect the necessary statistics for parameter estimation.\n\ \n\ The advantage of this architecture is that researcher can easily write \n\ programs to do parameter estimation and they have no need to tweak the \n\ huge and usually difficult Baum-Welch algorithm. \n\ \n\ In terms of functionality, one important thing you need to know is option \n\ -part and -npart. They can allow you to split the training into N equal parts\n\ Say, if there are M utterances in your control file, then this \n\ will enable you to run the training separately on each (M/N)th \n\ part. This flag may be set to specify which of these parts you want to \n\ currently train on. As an example, if your total number of parts (-npart) is 3, \n\ -part can take one of the values 1,2 or 3. \n\ \n\ To control the speed of the training, -abeam (control alpha search) \n\ and -bbeam (control beta search) can be used to control the searching \n\ time. Notice that if the beams are too small, the path may not reach \n\ the end of the search and results in estimation error \n\ Too many lost path may also cause training set likelihood not unable to increase \n\ \n\ Several options allow the user to control the behaviour of bw such \n\ that silence or pauses can be taken care. For example. One could use \n\ -sildelfn to specify periods of time which was assume to be silence. \n\ One could also use -sildel and -siltag to specify a silence and allow \n\ them to be optionall deleted. \n\ \n\ Finally, one can use the viterbi training mode of the code. Notice \n\ though, the code is not always tested by CMU's researcher \n\ \n\ I also included the following paragraph from Rita's web page. "; const char examplestr[]= "Example: \n\ Command used to train continuous HMM \n\ (Beware, this only illustrates how to use this command, for detail on \n\ how to tune it, please consult the manual. ) \n\ bw \n\ -moddeffn mdef -ts2cbfn .cont.\n\ -mixwfn mixw -tmatfn tmatn -meanfn mean -varfn var\n\ -dictfn dict -fdictfn fillerdict \n\ -ctlfn control_files \n\ -part 1 -npart 1 \n\ -cepdir feature_dir -cepext mfc \n\ -lsnfn transcription \n\ -accumdir accumdir \n\ -abeam 1e-200 -bbeam 1e-200 \n\ -meanreest yes -varreest yes \n\ -tmatreest yes -feat 1s_12c_12d_3p_12dd \n\ -ceplen 13 \n\ \n\ If yo want to do parallel training for N machines. Run N trainers with \n\ -part 1 -npart N \n\ -part 2 -npart N \n\ .\n\ .\n\ -part N -npart N "; static arg_def_t defn[] = { { "-help", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows the usage of the tool"}, { "-example", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Shows example of how to use the tool"}, { "-hmmdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Default directory for acoustic model files (mdef, means, variances, transition_matrices, noisedict)" }, { "-moddeffn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The model definition file for the model inventory to train" }, { "-tmatfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The transition matrix parameter file name"}, { "-mixwfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The mixture weight parameter file name"}, { "-meanfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The mean parameter file name"}, { "-varfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The var parameter file name"}, { "-fullvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Variances are full covariance matrices"}, { "-diagfull", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Evaluate Gaussian densities using diagonals only"}, { "-mwfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "Mixing weight smoothing floor" }, { "-tpfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.0001", "Transition probability smoothing floor" }, { "-varfloor", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.00001", "The minimum variance"}, { "-topn", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "4", "Compute output probabilities based this number of top scoring densities."}, { "-dictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The content word dictionary" }, { "-fdictfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The filler word dictionary (e.g. SIL, SILb, ++COUGH++)" }, { "-ltsoov", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Use CMUDict letter-to-sound rules to generate pronunciations for out-of-vocabulary words" }, { "-ctlfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The training corpus control file" }, { "-nskip", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The number of utterances to skip at the beginning of a control file" }, { "-runlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "-1", /* until eof */ "The number of utterances to process in the (skipped) control file" }, { "-part", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Identifies the corpus part number (range 1..NPART)" }, { "-npart", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Partition the corpus into this many equal sized subsets" }, { "-cepext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_EXTENSION, "The cepstrum file extension" }, { "-cepdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The cepstrum data root directory" }, { "-phsegext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "phseg", "Phone segmentation file extension" }, { "-phsegdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Phone segmentation file root directory" }, { "-outphsegdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Phone segmentation file output root directory" }, { "-sentdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The sentence transcript file directory"}, { "-sentext", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "sent", "The sentence transcript file extension"}, { "-lsnfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "The corpus word transcript file"}, { "-accumdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "A path where accumulated counts are to be written." }, { "-ceplen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_CEP_LENGTH, "The length of the input feature (e.g. MFCC) vectors"}, { "-cepwin", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "sliding window of features to concatenate (for -feat 1s_c ONLY)"}, { "-agc", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "max", "The type of automatic gain control to do {max|emax}"}, { "-cmn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "current", "The do cepstral mean normalization based on {current|prior} utterance(s)"}, { "-varnorm", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "no", "Variance Normalize?"}, { "-silcomp", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "none", "Do silence compression based on {current|prior} utterance"}, /* By ARCHAN at 200, fix the long-time legacy problem of not able to delete silence*/ { "-sildel", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Allow optional silence deletion in the Baum-Welch algorithm or the Viterbi algorithm."}, { "-siltag", CMD_LN_STRING, CMD_LN_NO_VALIDATION, "SIL", "Specify the tag of silence, by default it is <sil>."}, { "-abeam", CMD_LN_FLOAT64, CMD_LN_NO_VALIDATION, "1e-100", "Evaluate alpha values subject to this beam"}, { "-bbeam", CMD_LN_FLOAT64, CMD_LN_NO_VALIDATION, "1e-100", "Evaluate beta values (update reestimation sums) subject to this beam"}, { "-varreest", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate variances"}, { "-meanreest", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate means"}, { "-mixwreest", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate mixing weights"}, { "-tmatreest", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Reestimate transition probability matrices"}, { "-mllrmat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "An MLLR transformation file to apply to the means of the model"}, { "-cb2mllrfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, ".1cls.", "Codebook-to-MLLR-class mapping file name" }, { "-ts2cbfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Tied-state-to-codebook mapping file name" }, { "-feat", CMD_LN_STRING, CMD_LN_NO_VALIDATION, FEAT_DEFAULT_FEATURE_TYPE, "This argument selects the derived feature computation to use."}, { "-svspec", CMD_LN_STRING, CMD_LN_NO_VALIDATION, NULL, "Split single stream features into subvectors according to this specification."}, { "-ldafn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File containing an LDA transformation matrix."}, { "-ldadim", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "29", "# of output dimensions for LDA"}, { "-ldaaccum", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Apply LDA in accumulation of statistics only (NOTE: no dimensionality reduction will be done)."}, { "-timing", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "yes", "Controls whether profiling information is displayed"}, { "-viterbi", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Controls whether Viterbi training is done"}, { "-2passvar", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Reestimate variances based on prior means"}, { "-sildelfn", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "File which specifies frames of background 'silence' to delete" }, { "-spthresh", CMD_LN_FLOAT32, CMD_LN_NO_VALIDATION, "0.0", "State posterior probability floor for reestimation. States below this are not counted"}, { "-maxuttlen", CMD_LN_INT32, CMD_LN_NO_VALIDATION, "0", "Maximum # of frames for an utt ( 0 => no fixed limit )"}, { "-ckptintv", CMD_LN_INT32, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Checkpoint the reestimation sums every -chkptintv utts" }, { "-outputfullpath", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Output full path of utterance to bw log output" }, { "-fullsuffixmatch", CMD_LN_BOOLEAN, CMD_LN_NO_VALIDATION, "no", "Expect utterance id in transcript to be a suffix of the partial path in the control file" }, { "-pdumpdir", CMD_LN_STRING, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, "Dump state/mixture posterior probabilities to files in this directory" }, { NULL, CMD_LN_UNDEF, CMD_LN_NO_VALIDATION, CMD_LN_NO_DEFAULT, NULL } }; cmd_ln_define(defn); if (argc == 1) { cmd_ln_print_definitions(); exit(1); } cmd_ln_parse(argc, argv); if (cmd_ln_validate() == FALSE) { E_FATAL("Unable to validate command line arguments\n"); } isHelp = *(uint32 *) cmd_ln_access("-help"); isExample = *(uint32 *) cmd_ln_access("-example"); if(isHelp){ printf("%s\n\n",helpstr); } if(isExample){ printf("%s\n\n",examplestr); } if(isHelp || isExample){ E_INFO("User asked for help or example.\n"); exit(1); } if(!isHelp && !isExample){ cmd_ln_print_configuration(); } return 0; } /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.14 2006/03/27 04:08:57 dhdfu * Optionally use a set of phoneme segmentations to constrain Baum-Welch * training. * * Revision 1.13 2006/02/23 22:21:29 eht * add -outputfullpath and -fullsuffixmatch arguments to bw. * * Default behavior is to keep the existing system behavior when the * corpus module tries to match the transcript utterance id with the * partial path contained in the control file. * * Using -fullsuffixmatch yes will do the following: * The corpus module will check whether the string contained * inside parentheses in the transcript for the utterances * matches the final part of the control file partial path * for the utterance. For instance, if the control file * partial path is: * tidigits/train/man/ae/243za * the following strings will be considered to match: * 243za * ae/243za * man/ae/243za * . * . * . * In any event, the utterance will be used by bw for training. * This switch just modifies when the warning message for * mismatching control file and transcripts is generated. * * Using -outputfullpath yes will output the entire subpath from the * control file in the log output of bw rather than just the final path * component. This allows for simpler automatic processing of the output * of bw. * * Revision 1.12 2005/09/15 19:36:00 dhdfu * Add (as yet untested) support for letter-to-sound rules (from CMU * Flite) when constructing sentence HMMs in Baum-Welch. Currently only * rules for CMUdict exist. Of course this is not a substitute for * actually checking pronunciations... * * Revision 1.11 2005/04/07 21:23:39 egouvea * Improved the documentation, making it easier to find pointers, fixed the setup script, and fixed some of the doxygen comments * * Revision 1.10 2004/11/29 01:43:44 egouvea * Replaced handling of help or example so that user gets an INFO message instead of a scarier FATAL_ERROR * * Revision 1.9 2004/08/08 02:58:22 arthchan2003 * add help and example strings for bw * * Revision 1.8 2004/07/21 18:30:33 egouvea * Changed the license terms to make it the same as sphinx2 and sphinx3. * * Revision 1.7 2004/07/17 08:00:23 arthchan2003 * deeply regretted about one function prototype, now revert to the state where multiple pronounciations code doesn't exist * * Revision 1.5 2004/06/17 19:17:14 arthchan2003 * Code Update for silence deletion and standardize the name for command -line arguments * * Revision 1.4 2001/04/05 20:02:31 awb * *** empty log message *** * * Revision 1.3 2001/03/01 00:47:44 awb * *** empty log message *** * * Revision 1.2 2000/09/29 22:35:13 awb * *** empty log message *** * * Revision 1.1 2000/09/24 21:38:31 awb * *** empty log message *** * * Revision 1.14 97/07/16 11:36:22 eht * *** empty log message *** * * Revision 1.13 1996/08/06 14:03:47 eht * -sildelfn argument to specify silence deletion list * * Revision 1.12 1996/07/29 16:18:48 eht * Make -accumdir optional so that it may be omitted for * debugging purposes * MLLR command line options * -veclen to -ceplen * -minvar to -varfloor (now named consistently w/ the other floors) * added -2passvar switch to allow reestimation based on prior means * * Revision 1.11 1996/03/26 14:03:24 eht * - Added '-timing' argument * - changed doc strings for some arguments * * Revision 1.10 1996/02/02 17:41:47 eht * Add alpha and beta beams * * Revision 1.9 1996/01/26 18:23:49 eht * Reformatted argument specifications * * Revision 1.8 1995/11/30 20:42:07 eht * Add argument for transition matrix reestimation * Add argument for state parameter definition file * * */ <file_sep>/sphinx_fsttools/dict.c /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 1999-2001 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /* * HISTORY * * 05-Nov-98 <NAME> (<EMAIL>) at Carnegie-Mellon University * dict_load now terminates program if input dictionary * contains errors. * * 21-Nov-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Bugfix: Noise dictionary was not being considered in figuring * dictionary size. * * 18-Nov-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Added ability to modify pronunciation of an existing word in * dictionary (in dict_add_word()). * * 10-Aug-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Added check for word already existing in dictionary in * dict_add_word(). * * 27-May-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Included <NAME>'s personaldic handling (similar to * oovdic). * * 11-Apr-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Made changes to replace_dict_entry to handle the addition of * alternative pronunciations (linking in alt, wid, fwid fields). * * 02-Apr-97 <NAME> (<EMAIL>) at Carnegie-Mellon University * Caused a fatal error if max size exceeded, instead of realloc. * * 08-Dec-95 <NAME> (<EMAIL>) at Carnegie-Mellon University * Added function dict_write_oovdict(). * * 06-Dec-95 <NAME> (<EMAIL>) at Carnegie-Mellon University * Added functions dict_next_alt() and dict_pron(). * * Revision 8.5 94/10/11 12:32:03 rkm * Minor changes. * * Revision 8.4 94/07/29 11:49:59 rkm * Changed handling of OOV subdictionary (no longer alternatives to <UNK>). * Added placeholders for dynamic addition of words to dictionary. * Added dict_add_word () for adding new words to dictionary. * * Revision 8.3 94/04/14 15:08:31 rkm * Added function dictid_to_str(). * * Revision 8.2 94/04/14 14:34:11 rkm * Added OOV words sub-dictionary. * * Revision 8.1 94/02/15 15:06:26 rkm * Basically the same as in v7; includes multiple start symbols for * the LISTEN project. * * 11-Feb-94 <NAME> (rkm) at Carnegie-Mellon University * Added multiple start symbols for the LISTEN project. * * 9-Sep-92 <NAME> (faa) at Carnegie-Mellon University * Added special silences for start_sym and end_sym. * These special silences * (SILb and SILe) are CI models and as such they create a new context, * however since no triphones model these contexts explicity they are * backed off to silence, which is the desired context. Therefore no * special measures are take inside the decoder to handle these * special silences. * 14-Oct-92 <NAME> (eht) at Carnegie Mellon University * added Ravi's formal declarations for dict_to_id() so int32 -> pointer * problem doesn't happen on DEC Alpha * 14-Oct-92 <NAME> (eht) at Carnegie Mellon University * added Ravi's changes to make calls into hash.c work properly on Alpha * */ /* System headers. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /* SphinxBase headers. */ #include <prim_type.h> #include <cmd_ln.h> #include <ckd_alloc.h> #include <pio.h> #include <hash_table.h> #include <err.h> #include <strfuncs.h> #include <glist.h> /* Local headers. */ #include "dict.h" #ifdef DEBUG #define DFPRINTF(x) fprintf x #else #define DFPRINTF(x) #endif #define QUIT(x) {fprintf x; exit(-1);} static dict_entry_t *_new_dict_entry(dict_t *dict, char *word_str, char *pronoun_str); static void _dict_list_add(dict_t * dict, dict_entry_t * entry); static int dict_load(dict_t * dict, mdef_t *mdef, char const *filename, int32 * word_id); #define MAX_PRONOUN_LEN 150 static int32 get_dict_size(char const *file) { FILE *fp; __BIGSTACKVARIABLE__ char line[1024]; int32 n; if ((fp = fopen(file, "r")) == NULL) return -1; for (n = 0;; n++) if (fgets(line, sizeof(line), fp) == NULL) break; fclose(fp); return n; } int32 dict_ciphone_id(dict_t *dict, char const *phone) { if (dict->mdef) return mdef_ciphone_id(dict->mdef, (char *)phone); else { int32 pid; if (hash_table_lookup_int32(dict->ciphones, phone, &pid) < 0) { pid = dict->ciphone_count; if (dict->ciphone_str == NULL) dict->ciphone_str = ckd_calloc(1, sizeof(char *)); else dict->ciphone_str = ckd_realloc(dict->ciphone_str, (pid + 1) * sizeof(char *)); dict->ciphone_str[pid] = ckd_salloc(phone); (void)hash_table_enter_int32(dict->ciphones, dict->ciphone_str[pid], pid); ++dict->ciphone_count; } return pid; } } char const * dict_ciphone_str(dict_t *dict, int32 pid) { if (dict->mdef) return mdef_ciphone_str(dict->mdef, pid); else { return dict->ciphone_str[pid]; } } int32 dict_n_ciphone(dict_t *dict) { if (dict->mdef) return mdef_n_ciphone(dict->mdef); else { return dict->ciphone_count; } } dict_t * dict_init(cmd_ln_t *config, mdef_t *mdef) { dict_t *dict = ckd_calloc(1, sizeof(*dict)); int32 word_id = 0, j; dict_entry_t *entry; void *val; char const *filename, *n_filename; dict->config = config; dict->mdef = mdef; if (mdef == NULL) dict->ciphones = hash_table_new(40, HASH_CASE_NO); dict->ciphone_count = 0; dict->ciphone_str = NULL; dict->dict_entry_alloc = listelem_alloc_init(sizeof(dict_entry_t)); filename = cmd_ln_str_r(config, "-dict"); n_filename = cmd_ln_str_r(config, "-fdict"); /* * Find size of dictionary and set hash and list table size hints. * (Otherwise, the simple-minded PC malloc library goes berserk.) */ if ((j = get_dict_size(filename)) < 0){ E_ERROR("Failed to open dictionary file %s\n", filename); dict_free(dict); return NULL; } if (n_filename) j += get_dict_size(n_filename); j += 3; /* </s>, <s> and <sil> */ if (dict->dict) hash_table_free(dict->dict); if (cmd_ln_boolean_r(config, "-dictcase")) dict->dict = hash_table_new(j, HASH_CASE_YES); else dict->dict = hash_table_new(j, HASH_CASE_NO); /* Load dictionaries */ if (dict_load(dict, mdef, filename, &word_id) != 0) { dict_free(dict); return NULL; } /* Make sure that <s>, </s>, and <sil> are always in the dictionary. */ if (hash_table_lookup(dict->dict, "</s>", &val) != 0) { char pronstr[5]; /* * Check if there is a special end silence phone. */ if (-1 == dict_ciphone_id(dict, "SILe")) { strcpy(pronstr, "SIL"); entry = _new_dict_entry(dict, "</s>", pronstr); if (!entry) { E_ERROR("Failed to add </s>(SIL) to dictionary\n"); dict_free(dict); return NULL; } } else { E_INFO("Using special end silence for </s>\n"); strcpy(pronstr, "SILe"); entry = _new_dict_entry(dict, "</s>", pronstr); } _dict_list_add(dict, entry); hash_table_enter(dict->dict, entry->word, (void *)(long)word_id); entry->wid = word_id; word_id++; } dict->config = config; /* Mark the start of filler words */ dict->filler_start = word_id; /* Add the standard start symbol (<s>) if not already in dict */ if (hash_table_lookup(dict->dict, "<s>", &val) != 0) { char pronstr[5]; /* * Check if there is a special begin silence phone. */ if (-1 == dict_ciphone_id(dict, "SILb")) { strcpy(pronstr, "SIL"); entry = _new_dict_entry(dict, "<s>", pronstr); if (!entry) { E_ERROR("Failed to add <s>(SIL) to dictionary\n"); dict_free(dict); return NULL; } } else { E_INFO("Using special begin silence for <s>\n"); strcpy(pronstr, "SILb"); entry = _new_dict_entry(dict, "<s>", pronstr); if (!entry) { E_ERROR("Failed to add <s>(SILb) to dictionary\n"); dict_free(dict); return NULL; } } _dict_list_add(dict, entry); hash_table_enter(dict->dict, entry->word, (void *)(long)word_id); entry->wid = word_id; word_id++; } /* Finally create a silence word if it isn't there already. */ if (hash_table_lookup(dict->dict, "<sil>", &val) != 0) { char pronstr[4]; strcpy(pronstr, "SIL"); entry = _new_dict_entry(dict, "<sil>", pronstr); if (!entry) { E_ERROR("Failed to add <sil>(SIL) to dictionary\n"); dict_free(dict); return NULL; } _dict_list_add(dict, entry); hash_table_enter(dict->dict, entry->word, (void *)(long)word_id); entry->wid = word_id; word_id++; } if (n_filename) { if (dict_load(dict, mdef, n_filename, &word_id) != 0) { dict_free(dict); return NULL; } } return dict; } void dict_free(dict_t * dict) { int32 i; int32 entry_count; dict_entry_t *entry; if (dict == NULL) return; entry_count = dict->dict_entry_count; for (i = 0; i < entry_count; i++) { entry = dict->dict_list[i]; ckd_free(entry->word); ckd_free(entry->phone_ids); ckd_free(entry->ci_phone_ids); } for (i = 0; i < dict->ciphone_count; ++i) { ckd_free(dict->ciphone_str[i]); } ckd_free(dict->ciphone_str); listelem_alloc_free(dict->dict_entry_alloc); ckd_free(dict->dict_list); ckd_free(dict->ci_index); if (dict->ciphones) hash_table_free(dict->ciphones); if (dict->dict) hash_table_free(dict->dict); ckd_free(dict); } static int dict_load(dict_t * dict, mdef_t *mdef, char const *filename, int32 *word_id) { __BIGSTACKVARIABLE__ char dict_str[1024]; __BIGSTACKVARIABLE__ char pronoun_str[1024]; dict_entry_t *entry; FILE *fs; int32 start_wid = *word_id; int32 err = 0; if ((fs = fopen(filename, "r")) == NULL) return -1; pronoun_str[0] = '\0'; while (EOF != fscanf(fs, "%s%[^\n]\n", dict_str, pronoun_str)) { int32 wid; /* Check for duplicate before we do anything. */ if (hash_table_lookup_int32(dict->dict, dict_str, &wid) == 0) { E_WARN("Skipping duplicate definition of %s\n", dict_str); continue; } entry = _new_dict_entry(dict, dict_str, pronoun_str); if (!entry) { E_ERROR("Failed to add %s to dictionary\n", dict_str); err = 1; continue; } if (hash_table_enter_int32(dict->dict, entry->word, *word_id) != *word_id) { E_ERROR("Failed to add %s to dictionary hash!\n", entry->word); err = 1; continue; } _dict_list_add(dict, entry); entry->wid = *word_id; pronoun_str[0] = '\0'; /* * Look for words of the form ".*(#)". These words are * alternate pronunciations. Also look for phrases * concatenated with '_'. */ { char *p = strrchr(dict_str, '('); /* * For alternate pron. the last car of the word must be ')' * This will handle the case where the word is something like * "(LEFT_PAREN" */ if (dict_str[strlen(dict_str) - 1] != ')') p = NULL; if (p != NULL) { void *wid; *p = '\0'; if (hash_table_lookup(dict->dict, dict_str, &wid) != 0) { E_ERROR ("Missing first pronunciation for [%s]\nThis means that e.g. [%s(2)] was found with no [%s]\nPlease correct the dictionary and re-run.\n", dict_str, dict_str, dict_str); return -1; } DFPRINTF((stdout, "Alternate transcription for [%s](wid = %d)\n", entry->word, (long)wid)); entry->wid = (long)wid; { while (dict->dict_list[(long)wid]->alt >= 0) wid = (void *)(long)dict->dict_list[(long)wid]->alt; dict->dict_list[(long)wid]->alt = *word_id; } } } *word_id = *word_id + 1; } E_INFO("%6d = words in file [%s]\n", *word_id - start_wid, filename); if (fs) fclose(fs); return err; } int32 dict_to_id(dict_t * dict, char const *dict_str) { int32 dictid; if (hash_table_lookup_int32(dict->dict, dict_str, &dictid) < 0) return NO_WORD; return dictid; } static dict_entry_t * _new_dict_entry(dict_t *dict, char *word_str, char *pronoun_str) { dict_entry_t *entry; __BIGSTACKVARIABLE__ char *phone[MAX_PRONOUN_LEN]; __BIGSTACKVARIABLE__ int32 ciPhoneId[MAX_PRONOUN_LEN]; __BIGSTACKVARIABLE__ int32 triphone_ids[MAX_PRONOUN_LEN]; int32 pronoun_len = 0; int32 i; __BIGSTACKVARIABLE__ char position[256]; /* phone position */ mdef_t *mdef = dict->mdef; memset(position, 0, sizeof(position)); /* zero out the position matrix */ position[0] = 'b'; /* First phone is at begginging */ while (1) { int n; char delim; if (pronoun_len >= MAX_PRONOUN_LEN) { E_ERROR("'%s': Too many phones for bogus hard-coded limit (%d), skipping\n", word_str, MAX_PRONOUN_LEN); return NULL; } n = nextword(pronoun_str, " \t", &phone[pronoun_len], &delim); if (n < 0) break; pronoun_str = phone[pronoun_len] + n + 1; /* * An '&' in the phone string indicates that this is a word break and * and that the previous phone is in the end of word position and the * next phone is the begining of word position */ if (phone[pronoun_len][0] == '&') { position[pronoun_len - 1] = WORD_POSN_END; position[pronoun_len] = WORD_POSN_BEGIN; continue; } ciPhoneId[pronoun_len] = dict_ciphone_id(dict, phone[pronoun_len]); if (ciPhoneId[pronoun_len] == -1) { E_ERROR("'%s': Unknown phone '%s'\n", word_str, phone[pronoun_len]); return NULL; } pronoun_len++; if (delim == '\0') break; } position[pronoun_len - 1] = WORD_POSN_END; /* Last phone is at the end */ /* * If the position marker sequence 'ee' appears or 'se' appears * the sequence should be '*s'. */ if (position[0] == WORD_POSN_END) /* Also handle single phone word case */ position[0] = WORD_POSN_SINGLE; for (i = 0; i < pronoun_len - 1; i++) { if (((position[i] == WORD_POSN_END) || (position[i] == WORD_POSN_SINGLE)) && (position[i + 1] == WORD_POSN_END)) position[i + 1] = WORD_POSN_SINGLE; } if (mdef && pronoun_len >= 2) { i = 0; triphone_ids[i] = mdef_phone_id(mdef, dict_ciphone_id(dict, phone[i]), dict_ciphone_id(dict, "SIL"), dict_ciphone_id(dict, phone[i+1]), WORD_POSN_BEGIN); if (triphone_ids[i] < 0) triphone_ids[i] = dict_ciphone_id(dict, phone[i]); triphone_ids[i] = mdef_pid2ssid(mdef, triphone_ids[i]); assert(triphone_ids[i] >= 0); for (i = 1; i < pronoun_len - 1; i++) { triphone_ids[i] = mdef_phone_id(mdef, dict_ciphone_id(dict, phone[i]), dict_ciphone_id(dict, phone[i-1]), dict_ciphone_id(dict, phone[i+1]), position[i]); if (triphone_ids[i] < 0) triphone_ids[i] = dict_ciphone_id(dict, phone[i]); triphone_ids[i] = mdef_pid2ssid(mdef, triphone_ids[i]); assert(triphone_ids[i] >= 0); } triphone_ids[i] = mdef_phone_id(mdef, dict_ciphone_id(dict, phone[i]), dict_ciphone_id(dict, phone[i-1]), dict_ciphone_id(dict, "SIL"), position[i]); if (triphone_ids[i] < 0) triphone_ids[i] = dict_ciphone_id(dict, phone[i]); triphone_ids[i] = mdef_pid2ssid(mdef, triphone_ids[i]); assert(triphone_ids[i] >= 0); } /* * It's too hard to model both contexts so I choose to model only * the left context. */ if (mdef && pronoun_len == 1) { triphone_ids[0] = dict_ciphone_id(dict,phone[0]); triphone_ids[0] = mdef_pid2ssid(mdef,triphone_ids[0]); } entry = listelem_malloc(dict->dict_entry_alloc); entry->word = ckd_salloc(word_str); entry->len = pronoun_len; entry->alt = -1; if (pronoun_len != 0) { entry->ci_phone_ids = (int32 *) ckd_calloc((size_t) pronoun_len, sizeof(int32)); memcpy(entry->ci_phone_ids, ciPhoneId, pronoun_len * sizeof(int32)); entry->phone_ids = (int32 *) ckd_calloc((size_t) pronoun_len, sizeof(int32)); memcpy(entry->phone_ids, triphone_ids, pronoun_len * sizeof(int32)); } else { E_WARN("%s has no pronounciation, will treat as dummy word\n", word_str); } return (entry); } static void _dict_list_add(dict_t * dict, dict_entry_t * entry) /*------------------------------------------------------------*/ { if (!dict->dict_list) dict->dict_list = (dict_entry_t **) ckd_calloc(hash_table_size(dict->dict), sizeof(dict_entry_t *)); if (dict->dict_entry_count >= hash_table_size(dict->dict)) { E_WARN("dict size (%d) exceeded\n", hash_table_size(dict->dict)); dict->dict_list = (dict_entry_t **) ckd_realloc(dict->dict_list, (hash_table_size(dict->dict) + 16) * sizeof(dict_entry_t *)); } dict->dict_list[dict->dict_entry_count++] = entry; } int32 dict_get_num_main_words(dict_t * dict) { /* FIXME FIXME: Relies on a particular ordering of the dictionary. */ return dict_to_id(dict, "</s>"); } int32 dict_pron(dict_t * dict, int32 w, int32 ** pron) { *pron = dict->dict_list[w]->ci_phone_ids; return (dict->dict_list[w]->len); } int32 dict_next_alt(dict_t * dict, int32 w) { return (dict->dict_list[w]->alt); } int32 dict_is_filler_word(dict_t * dict, int32 wid) { return (wid >= dict->filler_start); } <file_sep>/archive_s3/s3.0/pgm/misc/lat2nodes.c /* * lat2nodes.c -- Extract nodes from complete lattices. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 21-Oct-1997 <NAME> (<EMAIL>) at Carnegie Mellon University * Started. */ #include <libutil/libutil.h> #include <libmain/misc.h> static void lat2nodes (char *uttid, char *inlatdir, char *outlatdir, char *inlatext, char *outlatext) { char inlatfile[4096], outlatfile[4096], line[16384], wd[4096]; FILE *infp, *outfp; int32 inpipe, outpipe; int32 i, k, n, sf, fef, lef; sprintf (inlatfile, "%s/%s.%s", inlatdir, uttid, inlatext); sprintf (outlatfile, "%s/%s.%s", outlatdir, uttid, outlatext); E_INFO("%s -> %s\n", inlatfile, outlatfile); if ((infp = fopen_compchk (inlatfile, &inpipe)) == NULL) E_FATAL("fopen_compchk(%s,r) failed\n", inlatfile); if ((outfp = fopen_comp (outlatfile, "w", &outpipe)) == NULL) E_FATAL("fopen_comp(%s,w) failed\n", outlatfile); for (;;) { if (fgets (line, sizeof(line), infp) == NULL) E_FATAL("Premature EOF(%s)\n", inlatfile); fprintf (outfp, "%s", line); if ((sscanf (line, "%s %d", wd, &n) == 2) && (strcmp (wd, "Nodes") == 0)) break; } for (i = 0; i < n; i++) { if (fgets (line, sizeof(line), infp) == NULL) E_FATAL("Premature EOF(%s)\n", inlatfile); if ((sscanf (line, "%d %s %d %d %d", &k, wd, &sf, &fef, &lef) != 5) || (k != i)) E_FATAL("Bad input line: %s\n", line); fprintf (outfp, "%d %s %d %d %d\n", k, wd, sf, fef, lef); } for (;;) { if (fgets (line, sizeof(line), infp) == NULL) E_FATAL("Premature EOF(%s)\n", inlatfile); if ((sscanf (line, "%s %d", wd, &n) == 2) && (strcmp (wd, "BestSegAscr") == 0)) { fprintf (outfp, "BestSegAscr 0 (NODEID ENDFRAME ASCORE)\n"); break; } fprintf (outfp, "%s", line); } fprintf (outfp, "#\n"); fprintf (outfp, "Edges (FROM-NODEID TO-NODEID ASCORE)\n"); fprintf (outfp, "End\n"); fclose_comp (infp, inpipe); fclose_comp (outfp, outpipe); } main (int32 argc, char *argv[]) { char *inlatdir, *outlatdir, *inlatext, *outlatext; char uttfile[4096], uttid[4096]; int32 sf, ef; if (argc != 5) { E_INFO("Usage: %s inlatdir outlatdir inlatext outlatext < ctlfile\n", argv[0]); exit(0); } inlatdir = argv[1]; outlatdir = argv[2]; inlatext = argv[3]; outlatext = argv[4]; while (_ctl_read (stdin, uttfile, &sf, &ef, uttid) >= 0) lat2nodes (uttid, inlatdir, outlatdir, inlatext, outlatext); } <file_sep>/CLP/include/Similarities.h //------------------------------------------------------------------------------------------- // compute different similarities //------------------------------------------------------------------------------------------- // Copyright (c) 1999 <NAME> <EMAIL> All rights reserved. //------------------------------------------------------------------------------------------- #ifndef _Similarities_h #define _Similarities_h # include <iostream> # include <fstream> # include <iomanip> # include <cstdio> # include <string> # include <cstdlib> # include <cmath> # include <cassert> using namespace std; #include "LineSplitter.h" inline int minim(int a, int b); double compute_phonetic_similarity(const string& A, const string& B); double compute_word_similarity(const string& A, const string& B); float compute_time_overlap(float p1, float p2, float q1, float q2); float compute_time_overlap_ph(float p1, float p2, float q1, float q2); #endif <file_sep>/CLP/src/GetOpt.cc /* Getopt for GNU. Copyright (C) 1987, 1989 Free Software Foundation, Inc. (Modified by <NAME> for use with GNU G++.) This file is part of the GNU C++ Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> // MOD 6/30/2000 - added #include <string.h> // MOD 6/30/2000 - added #include <alloca.h> #ifdef __GNUG__ #pragma implementation #endif /* AIX requires the alloca decl to be the first thing in the file. */ #include "GetOpt.h" // MOD 6/30/2000 - "" instead of <> char* GetOpt::nextchar = 0; int GetOpt::first_nonopt = 0; int GetOpt::last_nonopt = 0; GetOpt::GetOpt (int argc, char **argv, const char *optstring) :opterr (1), nargc (argc), nargv (argv), noptstring (optstring) { /* Initialize the internal data when the first call is made. Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind = 1; optarg = nextchar = 0; /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') ordering = RETURN_IN_ORDER; else if (getenv ("_POSIX_OPTION_ORDER") != 0) ordering = REQUIRE_ORDER; else ordering = PERMUTE; } void GetOpt::exchange (char **argv) { int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *); char **temp = (char **) alloca (nonopts_size); /* Interchange the two blocks of data in argv. */ memcpy (temp, &argv[first_nonopt], nonopts_size); memcpy (&argv[first_nonopt], &argv[last_nonopt], (optind - last_nonopt) * sizeof (char *)); memcpy (&argv[first_nonopt + optind - last_nonopt], temp, nonopts_size); /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of theoption characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns `EOF'. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. A colon in OPTSTRING means that the previous character is an option that wants an argument. The argument is taken from the rest of the current ARGV-element, or from the following ARGV-element, and returned in `optarg'. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg'. If OPTSTRING starts with `-', it requests a different method of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above. */ int GetOpt::operator () (void) { if (nextchar == 0 || *nextchar == 0) { if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange (nargv); else if (last_nonopt != optind) first_nonopt = optind; /* Now skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < nargc && (nargv[optind][0] != '-' || nargv[optind][1] == 0)) optind++; last_nonopt = optind; } /* Special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != nargc && !strcmp (nargv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange (nargv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = nargc; optind = nargc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == nargc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return EOF; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (nargv[optind][0] != '-' || nargv[optind][1] == 0) { if (ordering == REQUIRE_ORDER) return EOF; optarg = nargv[optind++]; return 0; } /* We have found another option-ARGV-element. Start decoding its characters. */ nextchar = nargv[optind] + 1; } /* Look at and handle the next option-character. */ { char c = *nextchar++; char *temp = (char *) strchr (noptstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == 0) optind++; if (temp == 0 || c == ':') { if (opterr != 0) { if (c < 040 || c >= 0177) fprintf (stderr, "%s: unrecognized option, character code 0%o\n", nargv[0], c); else fprintf (stderr, "%s: unrecognized option `-%c'\n", nargv[0], c); } return '?'; } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != 0) { optarg = nextchar; optind++; } else optarg = 0; nextchar = 0; } else { /* This is an option that requires an argument. */ if (*nextchar != 0) { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == nargc) { if (opterr != 0) fprintf (stderr, "%s: no argument for `-%c' option\n", nargv[0], c); c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = nargv[optind++]; nextchar = 0; } } return c; } } <file_sep>/SphinxTrain/src/programs/map_adapt/parse_cmd_ln.h /********************************************************************* * * $Header$ * * CMU ARPA Speech Project * * Copyright (c) 1996-2005 Carnegie Mellon University. * All rights reserved. * ********************************************************************* * * File: parse_cmd_ln.h * * Description: * * Author: * *********************************************************************/ #ifndef PARSE_CMD_LN_H #define PARSE_CMD_LN_H int parse_cmd_ln(int argc, char *argv[]); #endif /* PARSE_CMD_LN_H */ /* * Log record. Maintained by RCS. * * $Log$ * Revision 1.2 2005/06/16 04:31:28 dhdfu * Replace this program with my own "map_update" code. This implements * the MAP update equations from <NAME> and <NAME> * papers in addition to the (actually superior) simple interpolation * from Sam-Joo's code (which is still the default). There is no longer * any need to run norm to generate an ML estimate, we do that * internally. Also we can now adapt mixture weights, which may or may * not improve accuracy slightly versus only updating the means. */ <file_sep>/archive_s3/s3.0/pgm/sen2s2/sen2s2.c /* * sen2s2.c -- Mixture density weights associated with each tied state. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1997 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * $Log$ * Revision 1.1 2000/04/24 09:07:29 lenzo * Import s3.0. * * * 21-Feb-97 <NAME> (<EMAIL>) at Carnegie Mellon University. * Started based on original S3 implementation. */ #include <libutil/libutil.h> #include <libio/libio.h> #include <libmisc/libmisc.h> #include <libmain/senone.h> #include <libmain/mdef.h> #define MIXW_PARAM_VERSION "1.0" #define SPDEF_PARAM_VERSION "1.2" static char *fmtdesc[] = { "BEGIN FILE FORMAT DESCRIPTION", "(int32) <length(string)> (including trailing 0)", "<string> (including trailing 0)", "... preceding 2 items repeated any number of times", "(int32) 0 (length(string)=0 terminates the header)", "(int32) <#codewords>", "(int32) <#pdfs>", "256 (int32) cluster-prob values for codebook-0 codeword-0", "#pdf (unsigned char) cluster-prob ids for codebook-0 codeword-0", "... preceding 2 items repeated for all codewords in codebook-0", "preceding 3 items repeated for codebooks 1, 2, 3.", "END FILE FORMAT DESCRIPTION", NULL, }; #if defined(_HPUX_SOURCE) #define SWAPW(x) x = ( (((x)<<8)&0x0000ff00) | (((x)>>8)&0x00ff) ) #define SWAPL(x) x = ( (((x)<<24)&0xff000000) | (((x)<<8)&0x00ff0000) | \ (((x)>>8)&0x0000ff00) | (((x)>>24)&0x000000ff) ) #else #define SWAPW(x) #define SWAPL(x) #endif static fwrite_int32 (fp, val) FILE *fp; int val; { SWAPL(val); fwrite (&val, sizeof(int), 1, fp); } static void senone_dump (const mdef_t *mdef, const senone_t *s, char *file) { int32 i, j, k, c, m, f, n, p, sb, se; mixw_t *fw; FILE *fpout; int32 lut[256]; senprob_t *sp; E_INFO("Writing S2 format sendump file: %s\n", file); if ((fpout = fopen(file, "wb")) == NULL) E_FATAL("fopen(%s,wb) failed\n", file); /* Write format description into header */ for (i = 0; fmtdesc[i] != NULL; i++) { n = strlen(fmtdesc[i])+1; fwrite_int32 (fpout, n); fwrite (fmtdesc[i], sizeof(char), n, fpout); } /* Terminate header */ fwrite_int32 (fpout, 0); /* Write #codewords, #pdfs */ if (s->n_mgau != 1) E_FATAL("#codebooks(%d) != 1\n", s->n_mgau); if (s->mgau2sen[0].n_sen != s->n_sen) E_FATAL("#senones for mgau[0](%d) != total #senones(%d)\n", s->mgau2sen[0].n_sen, s->n_sen); if (s->n_feat != 4) E_FATAL("#Features(%d) != 4\n", s->n_feat); for (i = 0; i < s->n_feat; i++) { if (s->mgau2sen[0].feat_mixw[i].n_wt != s->mgau2sen[0].feat_mixw[0].n_wt) E_FATAL("#Wts not same for all features\n"); } if (s->mgau2sen[0].feat_mixw[0].n_wt != 256) E_FATAL("#Wts(%d) != 256\n", s->mgau2sen[0].feat_mixw[0].n_wt); fwrite_int32 (fpout, s->mgau2sen[0].feat_mixw[0].n_wt); fwrite_int32 (fpout, s->n_sen); /* Create lut */ for (i = 0; i < 256; i++) lut[i] = -(i << s->shift); sp = (senprob_t *) ckd_calloc (s->n_sen, sizeof(senprob_t)); /* Write PDFs (#feat x #wt x #sen) */ if (mdef->n_emit_state != 5) E_FATAL("#States(%d) != 5\n", mdef->n_emit_state); for (f = 0; f < s->n_feat; f++) { fw = s->mgau2sen[0].feat_mixw; for (c = 0; c < fw[f].n_wt; c++) { /* * In S3, all CI-senones (for all CI-phones) come first. CD-senones later. * But in S2, for each CI-phone, CD-senones come first and then CI-senones. */ k = 0; for (p = 0; p < mdef->n_ciphone; p++) { /* CD senones first; find start and end points in S3 data */ sb = 0; for (j = 0; j < p; j++) sb += mdef->ciphone2n_cd_sen[j]; sb += (mdef->n_ciphone * mdef->n_emit_state); se = sb + mdef->ciphone2n_cd_sen[p] - 1; for (i = sb; i <= se; i++) { m = s->sen2mgau[i]; assert (m == 0); j = s->mgau2sen_idx[i]; assert (j == i); fprintf(stderr, " %4d %4d %4d %4d", f, c, i, fw[f].prob[j][c]); sp[k++] = fw[f].prob[j][c]; } fprintf (stderr, "\n"); fflush (stderr); /* CI senones next */ sb = p * mdef->n_emit_state; se = sb + mdef->n_emit_state - 1; for (i = sb; i <= se; i++) { m = s->sen2mgau[i]; assert (m == 0); j = s->mgau2sen_idx[i]; assert (j == i); sp[k++] = fw[f].prob[j][c]; } } assert (k == mdef->n_sen); /* Write lut for feat f, codeword c */ for (i = 0; i < 256; i++) fwrite_int32 (fpout, lut[i]); /* Write data for feat f, codeword c */ fwrite (sp, sizeof(uint8), s->n_sen, fpout); } } fclose (fpout); } static int32 senone_mgau_map_read (senone_t *s, char *file_name) { FILE *fp; int32 byteswap, chksum_present, n_mgau_present; uint32 chksum; int32 i; char eofchk; char **argname, **argval; float32 v; E_INFO("Reading senone-codebook map file: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; n_mgau_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], SPDEF_PARAM_VERSION) != 0) { E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], SPDEF_PARAM_VERSION); } /* HACK!! Convert version# to float32 and take appropriate action */ if (sscanf (argval[i], "%f", &v) != 1) E_FATAL("%s: Bad version no. string: %s\n", file_name, argval[i]); n_mgau_present = (v > 1.1) ? 1 : 0; } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #gauden (if version matches) */ if (n_mgau_present) { if (bio_fread (&(s->n_mgau), sizeof(int32), 1, fp, byteswap, &chksum) != 1) E_FATAL("fread(%s) (#gauden) failed\n", file_name); } /* Read 1d array data; s->sen2mgau allocated by called function */ if (bio_fread_1d ((void **)(&s->sen2mgau), sizeof(int32), &(s->n_sen), fp, byteswap, &chksum) < 0) { E_FATAL("bio_fread_1d(%s) failed\n", file_name); } /* Infer n_mgau if not present in this version */ if (! n_mgau_present) { s->n_mgau = 1; for (i = 0; i < s->n_sen; i++) { if (s->sen2mgau[i] >= s->n_mgau) s->n_mgau = s->sen2mgau[i]+1; } } if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); /* Check for validity of mappings */ for (i = 0; i < s->n_sen; i++) { if ((s->sen2mgau[i] >= s->n_mgau) || NOT_MGAUID(s->sen2mgau[i])) E_FATAL("Bad sen2mgau[%d]= %d, out of range [0, %d)\n", i, s->sen2mgau[i], s->n_mgau); } if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read %d->%d senone-codebook mappings\n", s->n_sen, s->n_mgau); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static void build_mgau2sen (senone_t *s, int32 n_cw) { int32 i, j, m, f; s3senid_t *sen; mixw_t *fw; /* Create mgau2sen map from sen2mgau */ s->mgau2sen = (mgau2sen_t *) ckd_calloc (s->n_mgau, sizeof(mgau2sen_t)); s->mgau2sen_idx = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; assert ((m < s->n_mgau) && (m >= 0)); (s->mgau2sen[m].n_sen)++; } sen = (s3senid_t *) ckd_calloc (s->n_sen, sizeof(s3senid_t)); for (m = 0; m < s->n_mgau; m++) { s->mgau2sen[m].sen = sen; sen += s->mgau2sen[m].n_sen; s->mgau2sen[m].n_sen = 0; } for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; j = s->mgau2sen[m].n_sen; s->mgau2sen[m].sen[j] = i; s->mgau2sen_idx[i] = j; (s->mgau2sen[m].n_sen)++; } /* Allocate space for the weights */ for (m = 0; m < s->n_mgau; m++) { fw = (mixw_t *) ckd_calloc (s->n_feat, sizeof(mixw_t)); s->mgau2sen[m].feat_mixw = fw; for (f = 0; f < s->n_feat; f++) { fw[f].n_wt = n_cw; fw[f].prob = (senprob_t **) ckd_calloc_2d (s->mgau2sen[m].n_sen, n_cw, sizeof(senprob_t)); } } } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ static int32 senone_mixw_read(senone_t *s, char *file_name, float64 mixwfloor) { FILE *fp; char **argname, **argval; int32 byteswap, chksum_present; uint32 chksum; float32 *pdf; int32 i, j, f, m, c, p, n_sen, n_err, n_cw, nval; char eofchk; mixw_t *fw; E_INFO("Reading senone mixture weights: %s\n", file_name); if ((fp = fopen(file_name, "rb")) == NULL) E_FATAL_SYSTEM("fopen(%s,rb) failed\n", file_name); /* Read header, including argument-value info and 32-bit byteorder magic */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) E_FATAL("bio_readhdr(%s) failed\n", file_name); /* Parse argument-value list */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], MIXW_PARAM_VERSION) != 0) E_WARN("Version mismatch(%s): %s, expecting %s\n", file_name, argval[i], MIXW_PARAM_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* Read #senones, #features, #codewords, arraysize */ n_sen = s->n_sen; if ((bio_fread (&(s->n_sen), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(s->n_feat), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&(n_cw), sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (bio_fread (&nval, sizeof(int32), 1, fp, byteswap, &chksum) != 1)) { E_FATAL("bio_fread(%s) (arraysize) failed\n", file_name); } if ((n_sen != 0) && (s->n_sen != n_sen)) E_FATAL("#senones(%d) conflict with mapping file(%d)\n", s->n_sen, n_sen); if (s->n_sen >= MAX_SENID) E_FATAL("%s: #senones (%d) exceeds limit (%d)\n", file_name, s->n_sen, MAX_SENID); if (s->n_feat <= 0) E_FATAL("Bad #features: %d\n", s->n_feat); if (n_cw <= 0) E_FATAL("Bad #mixing-wts/senone: %d\n", n_cw); /* Allocate sen2mgau map if not yet done so (i.e. no explicit mapping file given */ if (! s->sen2mgau) { assert ((s->n_mgau == 0) || (s->n_mgau == 1)); s->sen2mgau = (int32 *) ckd_calloc (s->n_sen, sizeof(int32)); if (s->n_mgau == 1) { /* Semicontinuous mode; all senones map to single, shared gaussian: 0 */ for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = 0; } else { /* Fully continuous mode; each senone maps to own parent gaussian */ s->n_mgau = s->n_sen; for (i = 0; i < s->n_sen; i++) s->sen2mgau[i] = i; } } else assert (s->n_mgau != 0); if (s->n_mgau >= MAX_MGAUID) E_FATAL("%s: #gauden (%d) exceeds limit (%d)\n", file_name, s->n_mgau, MAX_MGAUID); if (nval != s->n_sen * s->n_feat * n_cw) { E_FATAL("%s: #float32 values(%d) doesn't match dimensions: %d x %d x %d\n", file_name, nval, s->n_sen, s->n_feat, n_cw); } /* * Compute #LSB bits to be dropped to represent mixwfloor with 8 bits. * All PDF values will be truncated (in the LSB positions) by these many bits. */ if ((mixwfloor <= 0.0) || (mixwfloor >= 1.0)) E_FATAL("mixwfloor (%e) not in range (0, 1)\n", mixwfloor); p = logs3(mixwfloor); for (s->shift = 0, p = -p; p >= 256; s->shift++, p >>= 1); E_INFO("Truncating senone logs3(wt) values by %d bits, to 8 bits\n", s->shift); /* Allocate memory for s->mgau2sen and senone PDF data */ build_mgau2sen (s, n_cw); /* Temporary structure to read in floats */ pdf = (float32 *) ckd_calloc (n_cw, sizeof(float32)); /* Read senone probs data, normalize, floor, convert to logs3, truncate to 8 bits */ n_err = 0; for (i = 0; i < s->n_sen; i++) { m = s->sen2mgau[i]; /* Parent mgau */ j = s->mgau2sen_idx[i]; /* Index of senone i within list of senones for mgau m */ fw = s->mgau2sen[m].feat_mixw; for (f = 0; f < s->n_feat; f++) { if (bio_fread((void *)pdf, sizeof(float32), n_cw, fp, byteswap, &chksum) != n_cw) { E_FATAL("bio_fread(%s) (arraydata) failed\n", file_name); } /* Normalize and floor */ if (vector_sum_norm (pdf, n_cw) == 0.0) n_err++; vector_floor (pdf, n_cw, mixwfloor); vector_sum_norm (pdf, n_cw); /* Convert to logs3, truncate to 8 bits, and store in s->pdf */ for (c = 0; c < n_cw; c++) { p = -(logs3(pdf[c])); p += (1 << (s->shift-1)) - 1; /* Rounding before truncation */ p = (p < (255 << s->shift)) ? (p >> s->shift) : 255; /* Trunc/shift */ fw[f].prob[j][c] = p; } } } if (n_err > 0) E_WARN("Weight normalization failed for %d senones\n", n_err); ckd_free (pdf); if (chksum_present) bio_verify_chksum (fp, byteswap, chksum); if (fread (&eofchk, 1, 1, fp) == 1) E_FATAL("More data than expected in %s\n", file_name); fclose(fp); E_INFO("Read mixture weights for %d senones: %d features x %d codewords\n", s->n_sen, s->n_feat, n_cw); return 0; } /* In the old S3 files, all senones have the same "shape" (#codewords/senone/feat) */ senone_t *senone_init (char *mixwfile, char *sen2mgau_map, float64 mixwfloor) { senone_t *s; s = (senone_t *) ckd_calloc (1, sizeof(senone_t)); s->n_sen = 0; /* As yet unknown */ s->sen2mgau = NULL; assert (sen2mgau_map); if (strcmp (sen2mgau_map, ".semi.") == 0) { /* Not a file; map all senones to a single parent mgau */ s->n_mgau = 1; /* But we don't yet know the #senones */ } else if (strcmp (sen2mgau_map, ".cont.") == 0) { /* Not a file; map each senone to its own distinct parent mgau */ s->n_mgau = 0; /* We don't yet know the #senones */ } else { /* Read mapping file */ senone_mgau_map_read (s, sen2mgau_map); /* Fills in n_sen */ } assert (mixwfile); senone_mixw_read (s, mixwfile, mixwfloor); return s; } #if 0 int32 senone_eval (senone_t *s, s3senid_t sid, int32 f, int32 *dist, int32 n_dist) { int32 i, c, scr, fscr; s3mgauid_t m; mixw_t *fw; m = s->sen2mgau[sid]; assert ((m >= 0) && (m < s->n_mgau)); fw = &(s->mgau2sen[m].feat_mixw[f]); assert (fw->n_wt == n_dist); i = s->mgau2sen_idx[sid]; /* Weight first codeword */ scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } return scr; } void senone_eval_all (senone_t *s, s3mgauid_t m, int32 f, int32 *dist, int32 n_dist, int32 *senscr) { int32 i, c, scr, fscr; s3senid_t sid; mixw_t *fw; fw = &(s->mgau2sen[m].feat_mixw[f]); assert (fw->n_wt == n_dist); for (i = 0; i < s->mgau2sen[m].n_sen; i++) { sid = s->mgau2sen[m].sen[i]; #if 1 /* Weight first codeword */ scr = dist[0] - (fw->prob[i][0] << s->shift); /* Remaining codewords */ for (c = 1; c < fw->n_wt; c++) { fscr = dist[c] - (fw->prob[i][c] << s->shift); scr = logs3_add (scr, fscr); } senscr[sid] += scr; #else senscr[sid] += senone_eval (s, sid, f, dist, n_dist); #endif } } #endif main (int32 argc, char *argv[]) { mdef_t *m; senone_t *s; float64 wtflr; char *mdeffile, *senfile, *mgaumap, *feattype, *outfile; if (argc != 7) E_FATAL("Usage: %s feat mdef mgaumap mixw mixwfloor output\n", argv[0]); feattype = argv[1]; mdeffile = argv[2]; mgaumap = argv[3]; senfile = argv[4]; if (sscanf (argv[5], "%lf", &wtflr) != 1) E_FATAL("Usage: %s mean var varfloor sen mgaumap mixwfloor cep feat\n", argv[0]); outfile = argv[6]; logs3_init ((float64) 1.0001); feat_init (feattype); m = mdef_init (mdeffile); s = senone_init (senfile, mgaumap, wtflr); if (m->n_sen != s->n_sen) E_FATAL("#senones different in mdef(%d) and mixw(%d) files\n", m->n_sen, s->n_sen); senone_dump (m, s, outfile); } <file_sep>/tools/audiocollector/src/java/edu/cmu/sphinx/tools/datacollection/client/AudioCollector.java package edu.cmu.sphinx.tools.datacollection.client; import edu.cmu.sphinx.frontend.util.VUMeter; import edu.cmu.sphinx.tools.audio.Player; import edu.cmu.sphinx.tools.audio.Recorder; import edu.cmu.sphinx.tools.corpus.Corpus; import edu.cmu.sphinx.tools.corpus.RegionOfAudioData; import edu.cmu.sphinx.tools.corpus.Utterance; import edu.cmu.sphinx.util.props.ConfigurationManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ListIterator; /** * Created by IntelliJ IDEA. * User: bertrand * Date: Apr 04, 2006 * Time: 11:55:23 AM * The AudioController class contains all the logic and data for a datacollection session. Think of it as the * brains behind the scene. It has no presentation logic at all, and works like a transparent state machine * allowing modality specific renderers to leverage the same class. * Once created the modality specific application should drive this state machine with methods like "record" "next" * "play" "submit"etc... but once the session is finished "destroy" should always be called. */ public class AudioCollector { /*All the internal states of the AudioController*/ final static protected byte BEFORE_RECORDING = 0; final static protected byte DURING_RECORDING = 1; final static protected byte AFTER_RECORDING = 2; final static protected byte DURING_PLAY = 3; final static protected byte INVALID_STATE = 4; protected byte _currentState = BEFORE_RECORDING; protected boolean _hasAudioData = false; protected Utterance _utterance; protected Corpus _corpus; protected ListIterator _uttIterator; protected Recorder _recorder; protected Player _player; protected static SimpleDateFormat filenameGenerator = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); /** * This method returns a standardized name for each utterance based on the current time and subject * specific information * * @param userID from the Corpus * @param id from the Corpus * @return a standardized filename for the utterance */ protected static String getAudioFilename(String userID, String id) { StringBuffer sb = new StringBuffer(userID + "-" + id + "-"); filenameGenerator.format(new Date(), sb, new FieldPosition(0)); return sb.toString(); } /** * This only constructor takes in a serializedCorpus (created by CorpusTranscriptOnlyWriter), and a * ConfigurationManager (with all the client specific information about low level recording) * * @param serializedCorpus a serialized corpus created by CorpusTranscriptsOnlyWriter * @param cm ConfigurationManager */ public AudioCollector(String serializedCorpus, ConfigurationManager cm) { CorpusTranscriptsOnlyReader csr = new CorpusTranscriptsOnlyReader(serializedCorpus); _recorder = new Recorder(); _recorder.open(cm); _corpus = csr.read(); _uttIterator = _corpus.getUtterances().listIterator(); _utterance = (Utterance) _uttIterator.next(); _currentState = BEFORE_RECORDING; } /** * This is a cleanup method, that should invariably be called either at the end of the session or after the * session has been aborted for whatever reason. */ public void destroy() { if (_recorder != null) _recorder.close(); } private Corpus getFakeCorpus() { Corpus c = new Corpus(); Utterance utt1 = new Utterance(); utt1.setTranscript("test utterance one"); Utterance utt2 = new Utterance(); utt2.setTranscript("test utterance two"); Utterance utt3 = new Utterance(); utt3.setTranscript("test utterance three"); Utterance utt4 = new Utterance(); utt4.setTranscript("test utterance four"); Utterance utt5 = new Utterance(); utt5.setTranscript("test utterance five"); c.addUtterance(utt1); c.addUtterance(utt2); c.addUtterance(utt3); c.addUtterance(utt4); c.addUtterance(utt5); return c; } /** * returns the internal state of the AudioController, may be used by the renderer's UI to inform * the user of their current action. * * @return BEFORE_RECORDING, DURING_RECORDING,AFTER_RECORDING,DURING_PLAY,INVALID_STATE */ public byte getCurrentState() { return _currentState; } /** * returns the current VUMeter, if the AudioController is currently playing back an utterance * then that is the VUMeter that will get returned, otherwise it's the recorder's VUMeter * * @return current VUMeter based on the AudioController's state */ public VUMeter getCurrentVUMeter() { if (_player != null && _player.isPlaying()) return _player.getVUMeter(); else return _recorder.getVUMeter(); } /** * If there currently is audio data captured for the current utterance returns true otherwise false. * * @return is there currently any audio data captured for the current utterance */ public boolean hasCurrentAudioData() { return !(_utterance.getRegionOfAudioData() == null); } /** * The current transcript the subject is to read and utter * * @return current transcript */ public String getCurrentTranscript() { if (_utterance == null) return ""; else return _utterance.getTranscript(); } /** * Based on the AudioController's current state, returns true only if "previous" is a valid request for that state. * * @return is "previous" currently a valid request? */ public boolean isPreviousActive() { switch (_currentState) { case BEFORE_RECORDING: return _uttIterator.hasPrevious(); case DURING_RECORDING: return false; case AFTER_RECORDING: return _uttIterator.hasPrevious(); case DURING_PLAY: return false; default: return false; } } /** * Based on the AudioController's current state, returns true only if "next" is a valid request for that state. * * @return is "next" currently a valid request? */ public boolean isNextActive() { switch (_currentState) { case BEFORE_RECORDING: return (_uttIterator.hasNext() && hasCurrentAudioData()); case DURING_RECORDING: return false; case AFTER_RECORDING: return (_uttIterator.hasNext() && hasCurrentAudioData()); case DURING_PLAY: return false; default: return false; } } /** * Based on the AudioController's current state, returns true only if "submit" is a valid request for that state. * * @return is "submit" currently a valid request? */ public boolean isSubmitActive() { switch (_currentState) { case BEFORE_RECORDING: return ((!_uttIterator.hasNext()) && hasCurrentAudioData()); case DURING_RECORDING: return false; case AFTER_RECORDING: return ((!_uttIterator.hasNext()) && hasCurrentAudioData()); case DURING_PLAY: return false; default: return false; } } /** * Based on the AudioController's current state, returns true only if "play" is a valid request for that state. * * @return is "play" currently a valid request? */ public boolean isPlayActive() { switch (_currentState) { case BEFORE_RECORDING: return hasCurrentAudioData(); case DURING_RECORDING: return false; case AFTER_RECORDING: return hasCurrentAudioData(); case DURING_PLAY: return false; default: return false; } } /** * Based on the AudioController's current state, returns true only if "record" is a valid request for that state. * * @return is "record" currently a valid request? */ public boolean isRecordActive() { switch (_currentState) { case BEFORE_RECORDING: return true; case DURING_RECORDING: return false; case AFTER_RECORDING: return true; case DURING_PLAY: return false; default: return false; } } /** * Based on the AudioController's current state, returns true only if "stop" is a valid request for that state. * * @return is "stop" currently a valid request? */ public boolean isStopActive() { switch (_currentState) { case BEFORE_RECORDING: return false; case DURING_RECORDING: return true; case AFTER_RECORDING: return false; case DURING_PLAY: return true; default: return false; } } /** * Should always be called only if isPlayActive() returns true. returns a Player object allowing the * renderer to playback the current utterance to the subject. Calling stop() stops the playback. * * @return a player object for playback to the subject */ public Player play() { switch (_currentState) { case BEFORE_RECORDING: _currentState = INVALID_STATE; break; case DURING_RECORDING: _currentState = INVALID_STATE; break; case AFTER_RECORDING: { _currentState = DURING_PLAY; _player = new Player((_utterance.getRegionOfAudioData())); return _player; } case DURING_PLAY: _currentState = INVALID_STATE; break; default: _currentState = INVALID_STATE; } return null; } /** * Should always be called only if isRecordActive() returns true. returns a VUMeter object allowing the * renderer to display EQ for volume monitoring. calling stop() stops the recording. * * @return a VUMeter for volume monitoring */ public VUMeter record() { switch (_currentState) { case BEFORE_RECORDING: _currentState = DURING_RECORDING; break; case DURING_RECORDING: _currentState = INVALID_STATE; break; case AFTER_RECORDING: _currentState = DURING_RECORDING; break; case DURING_PLAY: _currentState = INVALID_STATE; break; default: _currentState = INVALID_STATE; } if (_currentState == DURING_RECORDING) { try { _recorder.start(getAudioFilename(_corpus.getProperty("userID"), _corpus.getProperty("ID"))); } catch (IOException e) { e.printStackTrace(); } return _recorder.getVUMeter(); } return null; } /** * Should always be called only if isStopActive() returns true. stops playbacks started with play() or recordings * started with record(). */ public void stop() { switch (_currentState) { case BEFORE_RECORDING: _currentState = INVALID_STATE; break; case DURING_RECORDING: { _currentState = AFTER_RECORDING; try { final RegionOfAudioData _regionOfAudioData = _recorder.stop(); _utterance.setRegionOfAudioData(_regionOfAudioData); } catch (IOException e) { e.printStackTrace(); } break; } case AFTER_RECORDING: _currentState = INVALID_STATE; break; case DURING_PLAY: _currentState = AFTER_RECORDING; break; default: _currentState = INVALID_STATE; } } /** * Should always be called only if isPreviousActive() returns true. Gets the previous utterance from the corpus * and makes that the current utterance for playback or rerecording or rereading the transcript. */ public void previous() { _utterance = (Utterance) _uttIterator.previous(); _currentState = AFTER_RECORDING; } /** * Should always be called only if isNextActive() returns true. Gets the next utterance from the corpus * and makes that the current utterance for recording. */ public void next() { _utterance = (Utterance) _uttIterator.next(); _currentState = BEFORE_RECORDING; } /** * Should always be called only if isSubmitActive() returns true. Gathers all the utterances recorded in * the session stuffs them in a zip file, does the same for the a serialized version of the corpus in XML * format, and submits it to the URL it's being passed * @param url to which the data will be posted to */ public void submit(URL url) { try { HttpURLConnection urlCon = (HttpURLConnection) url.openConnection(); urlCon.setDoOutput(true); urlCon.setDoInput(true); // urlCon.setRequestProperty("Content-Encoding", "application/zip"); urlCon.setRequestMethod("POST"); urlCon.setRequestProperty("Content-type", "application/zip"); urlCon.setAllowUserInteraction(false); urlCon.setUseCaches(false); OutputStream out = urlCon.getOutputStream(); CorpusXMLZipWriter cxzw = new CorpusXMLZipWriter(out); cxzw.write(_corpus); out.flush(); out.close(); urlCon.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream())); String retVal = in.readLine(); in.close(); System.out.println("=======> Wrote zip file to the outputstream returned: " + retVal); _currentState = INVALID_STATE; } catch (Exception e) { e.printStackTrace(); } } }<file_sep>/sphinx3/src/tests/unit_tests/test_hmm/Makefile.am check_PROGRAMS = testhmm INCLUDES = \ -I$(top_srcdir)/include \ -I$(top_builddir)/include LDADD = ${top_builddir}/src/libs3decoder/libs3decoder.la \ -lsphinxbase @ad_libs@ -lm AM_LDFLAGS = -static TESTS = _testhmm_tidigits.test
063bf24d3fc3f4a582ba31bb99a0b31eee336ad7
[ "HTML", "Markdown", "Makefile", "INI", "M4Sugar", "Java", "C#", "Text", "Python", "Ant Build System", "C", "C++", "Shell" ]
467
C++
khcqcn/cmusphinx
45179a75546b396a218435a40eaf07be68707f59
6f2bd35593ff40208340543bb43f56e60bf0a71a
refs/heads/master
<file_sep>window.onload = function() { chessBoard = new ChessBoard('matrix'); document.onkeydown = function(event){ if (!event) { event = window.event; } var keyCode = event.keyCode || event.which; if ((keyCode == 37) && (chessBoard.col > 1)) { chessBoard.clearCell(chessBoard.row, chessBoard.col); chessBoard.col--; chessBoard.setCell(chessBoard.row, chessBoard.col); } else if ((keyCode == 38) && (chessBoard.row < chessBoard.cellCount)) { chessBoard.clearCell(chessBoard.row, chessBoard.col); chessBoard.row++; chessBoard.setCell(chessBoard.row, chessBoard.col); } else if ((keyCode == 39) && (chessBoard.col < chessBoard.cellCount)) { chessBoard.clearCell(chessBoard.row, chessBoard.col); chessBoard.col++; chessBoard.setCell(chessBoard.row, chessBoard.col); } else if ((keyCode == 40) && (chessBoard.row > 1)) { chessBoard.clearCell(chessBoard.row, chessBoard.col); chessBoard.row--; chessBoard.setCell(chessBoard.row, chessBoard.col); } } } <file_sep>function Matrix(containerId, cellCount, cellLength) { var ARRAYOFLATTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; this.create = function(realCellCount, cell, matrix) { if((this.cellCount > 0) && (this.cellCount < 27) && (this.cellLength > 29) && (this.cellLength < 71)) { var count = realCellCount * realCellCount; matrix.innerHTML = ''; for (var i = 0; i < count; i++) { var div = document.createElement('div'); div.classList.add('cell'); this.row = Math.floor(i / realCellCount); this.col = i % realCellCount; if ((this.row == 0) || (this.col == 0) || (this.row == realCellCount - 1) || (this.col == realCellCount - 1)) { div.classList.add('border'); if ((this.col == 0) || (this.col == realCellCount - 1)) { if ((this.row > 0) && (this.row < realCellCount - 1)) { div.innerHTML = realCellCount - this.row - 1; } } if ((this.row == 0) || (this.row == realCellCount - 1)) { if ((this.col > 0) && (this.col < realCellCount - 1)) { div.innerHTML = ARRAYOFLATTERS[this.col - 1]; } } if ((this.col == realCellCount - 1) || (this.row == 0)) { div.classList.add('rotate'); } } else { if ((this.row + this.col) % 2 == 1) { div.classList.add('black'); } else { div.classList.add('white'); } } matrix.appendChild(div); cell[i].style.height = this.cellLength + 'px'; cell[i].style.width = this.cellLength + 'px'; } matrixLength = realCellCount * cell[0].offsetWidth; matrix.style.height = matrixLength + "px"; matrix.style.width = matrixLength + "px"; } else { matrix.innerHTML = 'Enter at the correct value!!!'; } } } function ChessBoard(containerId, cellCount, cellLength) { var ARRAYOFLATTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; Matrix.call(this); this.containerId = containerId; this.cellCount = (this.cellCount === undefined) ? 8 : this.cellCount; this.cellLength = (this.cellLength === undefined) ? 50 : this.cellLength; var matrix = document.getElementById(this.containerId); var cell = matrix.getElementsByClassName('cell'); var realCellCount = this.cellCount + 2; this.setCell = function(row, col){ numderOfCell = matrix.children[(realCellCount - row -1) * realCellCount + col]; numderOfCell.classList.add('active'); numderOfCell.innerHTML = ARRAYOFLATTERS[col - 1] + '' + row; } this.clearCell = function(row, col){ numderOfCell = matrix.children[(realCellCount - row -1) * realCellCount + col]; numderOfCell.classList.remove('active'); numderOfCell.innerHTML = ''; } this.create(realCellCount, cell, matrix); this.col = 1; this.row = 1; this.setCell(this.row, this.col); }
08b887546af468bdbc2c1076772dae3fa06d1090
[ "JavaScript" ]
2
JavaScript
Igor33/js-2_2
78ce2af4b0b20aafba52d722fb63e56186802329
30c6ebc1b83bb98cc5cd5dcf835c30f8334c6628
refs/heads/master
<file_sep>package me.zeddit import command.GeneralCommandListener import me.zeddit.playlists.PlaylistCache import me.zeddit.playlists.PlaylistStorageHandler import me.zeddit.playlists.PlaylistsCommands import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.JDABuilder import net.dv8tion.jda.api.hooks.AnnotatedEventManager import java.util.* import kotlin.collections.HashSet import kotlin.system.exitProcess var jda : JDA? = null val storageHandler = PlaylistStorageHandler() val cache : PlaylistCache = PlaylistCache(20) val guilds: MutableSet<AudioGuild> = HashSet() fun main(args: Array<String>) { val token = args[0] val mainCommands = MainCommands() val playlistsCommands = PlaylistsCommands() val cmdListener = GeneralCommandListener() cmdListener.addCommands(mainCommands, playlistsCommands) storageHandler.init() jda = JDABuilder.createDefault(token) .setEventManager(AnnotatedEventManager()) .addEventListeners(cmdListener) .build().awaitReady() sysInThread.start() } private val sysInThread = Thread { val sc = Scanner(System.`in`) var next : String while (true) { next = sc.next() if (next.equals("e", true)) { println("Shutting down..") cache.allItems().forEach { storageHandler.sync(it) println("Saved cached playlist with id ${it.id}!") } storageHandler.close() exitProcess(0) } } }<file_sep>package command class CommandResult(val commandName: GenericCommandName, val args: Array<String>) <file_sep>package me.zeddit.playlists import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.tools.FriendlyException import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import com.sedmelluq.discord.lavaplayer.track.AudioTrack import me.zeddit.awaitAll import me.zeddit.eprintln import java.util.concurrent.Callable import java.util.concurrent.Executors import java.util.concurrent.ThreadFactory // doesnt automatically setup so that invalid links can be removed! // ID format is the user id of the creator a dash and the playlist number eg 10-1 class Playlist(private val tracks: MutableList<String>, val id: String, val info: Info, private val playerManager: AudioPlayerManager) { data class Info(var name: String, var description: String) private val threadFactory = ThreadFactory { val thread = Thread(it) thread.name = "Playlist Track Loader Thread" thread } private var started: Boolean = false private var audioTracks: MutableList<AudioTrack> = ArrayList() get() { if (!started) { field = resetInternal() started = true } return field } set(value) { if (!started) { started =true } field = value } private fun String.constructTrackCallable(index: Int) : Callable<Result<Pair<List<AudioTrack>, Int>>> { val i = this return Callable { val loadingTr: MutableList<AudioTrack?> = ArrayList() playerManager.loadItemOrdered(Any(), i, object : AudioLoadResultHandler { override fun trackLoaded(loaded: AudioTrack) { loadingTr.add(loaded) } override fun playlistLoaded(playlist: AudioPlaylist) { if (i.matches(Regex("https?://"))) { loadingTr.add(playlist.tracks[0]) } else { playlist.tracks.forEach { loadingTr.add(it) } } } override fun noMatches() { loadingTr.add(null) } override fun loadFailed(exception: FriendlyException) { loadingTr.add(null) exception.printStackTrace() eprintln("Load failed for track with url $i") } }).get() val nonNull = loadingTr.filterNotNull() if (loadingTr.size - nonNull.size > 0) { return@Callable Result.failure(InvalidTrackException(i, this@Playlist.id)) } else { return@Callable Result.success(Pair(nonNull, index)) } } } @Synchronized private fun resetInternal() : MutableList<AudioTrack> { val service = Executors.newFixedThreadPool(5, threadFactory) val callables = ArrayList<Callable<Result<Pair<List<AudioTrack>, Int>>>>() for (i in tracks.indices) { callables.add(tracks[i].constructTrackCallable(i)) } return service.invokeAll(callables).awaitAll() .asSequence() .map { it.getOrThrow() } .sortedBy { it.second } .map { it.first } .flatten() .toMutableList() } @Synchronized fun reset() { audioTracks = resetInternal() } @Synchronized //The number of urls removed fun remove(url : String) : Int { val str = tracks.removeIf { it == url } val track = audioTracks.removeIf {it.info.uri == url} return if (str || track) 1 else 0 } @Synchronized fun remove(index: Int) { if (index !in tracks.indices) { throw IllegalStateException() } tracks.removeAt(index) reset() } // This method makes sure this class is immutable by returning a new list each time. Always will be sorted @Synchronized fun getTracks() : List<AudioTrack> { val service = Executors.newFixedThreadPool(5,threadFactory) val callables = ArrayList<Callable<Pair<AudioTrack, Int>>>() for (i in audioTracks.indices) { callables.add(Callable { Pair(audioTracks[i].makeClone(), i) }) } return service.invokeAll(callables).awaitAll().sortedBy { it.second }.map { it.first } } fun getTrackUrls() : List<String> = ArrayList(tracks) fun clone(id: String) : Playlist = Playlist(ArrayList(tracks), id, this.info, playerManager) @Synchronized fun remove(urls: List<String>) : Int { var count =0 urls.forEach { count += remove(it) } return count } @Synchronized fun add(urls: List<String>) : List<AudioTrack> { return Executors.newFixedThreadPool(5, threadFactory).invokeAll(MutableList(urls.size) { urls[it].constructTrackCallable(it) }).awaitAll().flatMap { it.getOrThrow().first }.onEach { addTrack(it) } } private fun addTrack(i: AudioTrack) { tracks.add(i.info.uri) audioTracks.add(i) } @Synchronized fun add(url: String) : List<AudioTrack> { val list = ArrayList<AudioTrack>() for (i in url.constructTrackCallable(0).call().getOrThrow().first) { addTrack(i) list.add(i) } return list } fun getUserID() : String { return id.split("-")[0] } fun getPlaylistNumber() : String { return id.split("-")[1] } override fun equals(other: Any?): Boolean { if (other === this) return true (other as? Playlist)?.let { return it.id == this.id } return false } override fun hashCode(): Int { return id.hashCode() } }<file_sep>package command interface GenericCommandName { }<file_sep>package command import me.zeddit.filterMap import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import net.dv8tion.jda.api.hooks.SubscribeEvent import java.awt.Color import java.time.Instant class GeneralCommandListener { private val commands = ArrayList<Command>() @SubscribeEvent fun onGuildMessageReceived(e: GuildMessageReceivedEvent) { if (e.isWebhookMessage) return if (e.author.isBot) return if (!e.message.contentRaw.startsWith("!")) return val results = commands.map { Pair(it, it.parseCommand(e.message.contentRaw, e)) } .filterMap({it.second != null}, {it -> Pair(it.first, it.second!!)}) if (results.isEmpty()) { e.channel.sendMessageEmbeds( EmbedBuilder() .setColor(Color.RED) .setTitle("Error") .addField("Something went wrong!", "Unknown command!", false) .setTimestamp(Instant.now()).build()).queue() return } results.forEach { it.first.onCommand(it.second, e) } } fun addCommands(vararg commands: Command) { commands.forEach { this.commands.add(it) } } }<file_sep>package me.zeddit.playlists import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers import command.Command import command.CommandResult import command.GenericCommandName import me.zeddit.* import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.entities.MessageEmbed import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import java.awt.Color import java.lang.StringBuilder import java.time.Instant import java.util.concurrent.Executors class PlaylistsCommands : Command { private val sp = Regex("\\s+") private val playerManager: AudioPlayerManager = DefaultAudioPlayerManager().apply { AudioSourceManagers.registerLocalSource(this) AudioSourceManagers.registerRemoteSources(this) } private enum class CommandName : GenericCommandName { ADD, REMOVE, QUEUE, CREATE, DELETE, SET, LIST, CLONE, } override fun parseCommand(cmd: String, e: GuildMessageReceivedEvent) : CommandResult? { if (!e.message.contentRaw.matches(Regex("!pl(aylist)?\\s+.+", RegexOption.IGNORE_CASE))) { return null } val pCmd = e.message.contentRaw.split(sp).toMutableList().apply { removeFirst() }.joinToString(" ") //lowercase cmdName val (cmdName, args) = pCmd.split(sp).let {list -> Pair(list[0].toLowerCase(), Array(list.size - 1) {list[it + 1]}) } val commandName = when (cmdName) { "add" -> CommandName.ADD "a" -> CommandName.ADD "remove" -> CommandName.REMOVE "r" -> CommandName.REMOVE "queue" -> CommandName.QUEUE "q" -> CommandName.QUEUE "create" -> CommandName.CREATE "c" -> CommandName.CREATE "delete" -> CommandName.DELETE "d" -> CommandName.DELETE "list" -> CommandName.LIST "display" -> CommandName.LIST "l" -> CommandName.LIST "set" -> CommandName.SET "s" -> CommandName.SET "copy" -> CommandName.CLONE "clone" -> CommandName.CLONE else -> return null } return CommandResult(commandName, args) } override fun onCommand(cmd: CommandResult, e: GuildMessageReceivedEvent) { val audioGuild : AudioGuild = guilds.firstOrNull { it.id == e.guild.id } ?: AudioGuild(playerManager, e.guild).apply { guilds.add(this) } val builder = EmbedBuilder().setTitle("Result").setColor(Color.RED).setTimestamp(Instant.now()) val argsEmbed = EmbedBuilder(builder).addField("Not enough/incorrect args supplied!".toResultField()).build() val doesNotOwn = EmbedBuilder(builder).addField("This is not your playlist!".toResultField()).build() val pFmtHelper = PlaylistFmtHelper(e, e.author) when(cmd.commandName) { // Arg 0 = url 1(o) = id toggle rest is the name/id CommandName.ADD -> { if (cmd.args.size < 2) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } val arg1 =cmd.args[1] if (arg1.equals("id", true) && cmd.args.size != 3) { e.channel.sendMessageEmbeds(argsEmbed).queue() } if (!cmd.args[0].matches(Regex("https?://.+"))) { e.channel.sendMessageEmbeds(builder.addField("Invalid url supplied!".toResultField()).build()).queue() return } if (arg1.equals("id", true)) { getPlaylistFmt(cmd.args[2], pFmtHelper) } else { getPlaylistFmt(cmd.args.joinToString(1),pFmtHelper, false) }?.let { if (it.getUserID() != e.author.id) { e.channel.sendMessageEmbeds(doesNotOwn).queue() } else { addInternal(e, builder, it, cmd.args) } } } CommandName.REMOVE -> { if (cmd.args.isEmpty()) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } val idToggle =cmd.args[0].equals("id", ignoreCase = true) if ((idToggle && cmd.args.size != 3) || cmd.args.size < 2 || !cmd.args[cmd.args.size - 1].matches(Regex("\\d{1,9}"))) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } val index = cmd.args[cmd.args.size - 1].toInt() if (idToggle) { getPlaylistFmt(cmd.args[1], pFmtHelper) } else { getPlaylistFmt(Array(cmd.args.size - 1) {cmd.args[it]}.joinToString(),pFmtHelper, false) }?.let { try { it.remove(index - 1) e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN).addField("Removed track $index!".toResultField(true)).build()).queue() } catch (ex: IllegalStateException) { e.channel.sendMessageEmbeds(builder.addField("Index $index out of range!".toResultField()).build()).queue() } } } CommandName.QUEUE -> { parseOnlyPlaylist(e, cmd.args, argsEmbed)?.let { val audioManager = e.guild.audioManager val chn = e.member!!.voiceState!!.channel if (!audioManager.isConnected) { val embed = voiceChnPrecons(chn, e.guild.retrieveMember(jda!!.selfUser).complete()) if (embed != null) { e.channel.sendMessageEmbeds(embed).queue() return } } val tracks = it.getTracks() if (tracks.isEmpty()) { e.channel.sendMessageEmbeds(builder.addField("The playlist is empty!".toResultField()).build()).queue() return } if (!audioManager.isConnected) { audioManager.openAudioConnection(chn) } for (i in tracks) audioGuild.queue(i) e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN) .addField("Added ${tracks.size} tracks to queue from playlist ${it.info.name}!".toResultField(true)).build()).queue() } } CommandName.CREATE -> { val playlists = storageHandler.retrieveAllPlaylists(e.author.id) if (playlists.size >= 5) { e.channel.sendMessageEmbeds(builder.addField(("You have reached the playlist limit; " + "please delete a playlist in order to create a new one!").toResultField()).build()).queue() return } var name = "New Playlist" if (cmd.args.isNotEmpty()) { name = cmd.args.joinToString("") } val newPl = Playlist(ArrayList(), "${e.author.id}-${nextId(playlists)}", Playlist.Info(name, ""), playerManager) Executors.newSingleThreadExecutor().submit { cache.cache(newPl) storageHandler.sync(newPl) println("User ${e.author.asTag} (id = ${e.author.id}) created a new playlist with id ${newPl.id}!") e.channel .sendMessageEmbeds(builder .addField("Created playlist with name ${newPl.info.name} and id ${newPl.id}!".toResultField(true)).setColor( Color.GREEN).build()).queue() } } CommandName.SET -> { // arg 0 = id opt then arg 1 until a opt is the name/id then the rest is value for the set op if (cmd.args.isEmpty()) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } val opt : SetOpt val value: String val playlist: Playlist if (cmd.args[0].equals("id", true)) { if (cmd.args.size < 4) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } val id = cmd.args[1] playlist = getPlaylistFmt(id, pFmtHelper) ?: return opt = parseOpt(cmd.args[2]) ?: run {e.channel.sendMessageEmbeds(argsEmbed).queue(); return} value = cmd.args.joinToString(3) } else { if (cmd.args.size < 3) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } var optI = -1 for (i in cmd.args.indices) { if (parseOpt(cmd.args[i]) != null) { optI = i break } } if (optI == -1) { e.channel.sendMessageEmbeds(argsEmbed).queue() return } playlist = getPlaylistFmt(Array(optI) {cmd.args[it]}.joinToString(), pFmtHelper, false) ?: return opt = parseOpt(cmd.args[optI])!! value = cmd.args.joinToString(optI + 1) } if (opt == SetOpt.NAME) { playlist.info.name = value } else { playlist.info.description = value } e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN) .addField("Changed this playlist's ${opt.name.toLowerCase()} to `${value.esc()}`!".toResultField(true)).build()).queue() } CommandName.DELETE -> { val pl = parseOnlyPlaylist(e, cmd.args, argsEmbed) ?: return if (pl.getUserID() != e.author.id) { e.channel.sendMessageEmbeds(doesNotOwn).queue() return } e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN).addField("Deleting playlist ${pl.id}..".toResultField(true)).build()).queue() Executors.newSingleThreadExecutor().submit { cache.remove(pl) storageHandler.remove(pl) println("User ${e.author.asTag} (id = ${e.author.id}) deleted playlist with id ${pl.id}!") } } CommandName.LIST -> { parseOnlyPlaylist(e, cmd.args, argsEmbed)?.let { val tracks = it.getTracks() val res = EmbedBuilder() .setColor(Color.GREEN) .setTimestamp(Instant.now()) .setTitle("Contents") val sBuilder = StringBuilder() for (i in tracks.indices) { val t = tracks[i] sBuilder.append("${i + 1}. `${t.info.title.esc()}` | `${t.info.author.esc()}` | `${t.duration.fmtMs()}`\n") } e.channel.sendMessageEmbeds(res.addField("Contents of ${it.info.name}:", sBuilder.toString(), false).build()).queue() } } CommandName.CLONE -> { parseOnlyPlaylist(e, cmd.args, argsEmbed)?.let { val playlists = storageHandler.retrieveAllPlaylists(e.author.id) if (playlists.size >= 5) { e.channel.sendMessageEmbeds(builder.addField(("You have reached the playlist limit; " + "please delete a playlist in order to create a new one!").toResultField()).build()).queue() return } val newPl = it.clone("${e.author.id}-${nextId(playlists)}") Executors.newSingleThreadExecutor().submit { cache.cache(newPl) storageHandler.sync(newPl) println("User ${e.author.asTag} (id = ${e.author.id}) cloned an existing playlist (id ${it.id}) with id ${newPl.id}!") e.channel .sendMessageEmbeds(builder .addField(("Cloned playlist with id ${it.id} to create" + " a new playlist with name ${newPl.info.name} and id ${newPl.id}!").toResultField(true)).setColor( Color.GREEN).build()).queue() } } } } } private enum class SetOpt{ DESCRIPTION, NAME } private fun parseOpt(opt : String) : SetOpt? { return when (opt.toLowerCase()) { "d" -> SetOpt.DESCRIPTION "desc" -> SetOpt.DESCRIPTION "description" -> SetOpt.DESCRIPTION "name" -> SetOpt.NAME "n" -> SetOpt.NAME else -> return null } } private fun parseOnlyPlaylist(e: GuildMessageReceivedEvent, args: Array<String>, argsEmbed: MessageEmbed) : Playlist? { val pFmtHelper = PlaylistFmtHelper(e, e.author) // arg0 (opt) id toggle, arg1 etc name or id of playlist if (args.isEmpty()) { e.channel.sendMessageEmbeds(argsEmbed).queue() return null } val idToggle =args[0].equals("id", ignoreCase = true) if (idToggle && args.size != 2) { e.channel.sendMessageEmbeds(argsEmbed).queue() return null } return if (idToggle) { getPlaylistFmt(args[1], pFmtHelper) } else { getPlaylistFmt(args.joinToString(0),pFmtHelper, false) } } private data class PlaylistFmtHelper(val e: GuildMessageReceivedEvent, val user: User) private fun getPlaylistFmt(name: String, p: PlaylistFmtHelper, id: Boolean = true) : Playlist? { val playlist = if (id) { safeGetPlaylistId(name) } else { safeGetPlaylist(name,p.user) } if (playlist == null) { p.e.channel.sendMessageEmbeds(name.toNoPlaylistEmbed(id)).queue() } return playlist } private fun nextId(playlists:List<Playlist>) : Long { var largest = 0L for (i in playlists) { val next =i.id.split("-")[1].toLong() if (next >= largest) largest = next + 1 } return largest } private fun addInternal(e: GuildMessageReceivedEvent, builder: EmbedBuilder, playlist: Playlist, args: Array<String>) { try { val added = playlist.add(args[0]) if (added.size > 1) { e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN) .addField("Detected playlist, adding ${added.size} tracks to this playlist!".toResultField(true)).build()).queue() } else { e.channel.sendMessageEmbeds(builder.setColor(Color.GREEN) .addField("Adding `${added[0].info.title.esc()}` to this playlist!".toResultField(true)).build()).queue() } } catch (ex: InvalidTrackException) { e.channel.sendMessageEmbeds(builder .addField("Could not load track for url(s) ${ex.urls.joinToString(", ")} for playlist with id ${ex.id}!" .toResultField()).build()).queue() } } private fun String.toNoPlaylistEmbed(id: Boolean = false) : MessageEmbed { val builder = EmbedBuilder().setTitle("Result").setColor(Color.RED).setTimestamp(Instant.now()) return builder.addField("Couldn't find playlist with ${if (id) "id" else "name"} $this!".toResultField()).build() } private fun safeGetPlaylist(name: String, user: User) : Playlist? { val nameSame : (Playlist) -> Boolean= { it.info.name.equals(name, true) } cache.getPlaylist { nameSame.invoke(it) }?.let { return it } val playlists = storageHandler.retrieveAllPlaylists(user.id) return playlists.firstOrNull { nameSame.invoke(it) }.apply { this?.let{ cache.cache(this)} } } private fun safeGetPlaylistId(id: String) : Playlist? { cache.getPlaylist(id)?.let { return it } return storageHandler.retrievePlaylist(id).apply { this?.let { cache.cache(this) } } } }<file_sep>package me.zeddit.playlists import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers import java.io.File import java.sql.Connection import java.sql.DriverManager import java.sql.ResultSet // This class will block class PlaylistStorageHandler : AutoCloseable { private val file: File = File("playlists.db") private val dbPath = "jdbc:sqlite:${file.absolutePath}" private lateinit var connection: Connection private val playerManager: AudioPlayerManager = DefaultAudioPlayerManager().apply { AudioSourceManagers.registerLocalSource(this) AudioSourceManagers.registerRemoteSources(this) } // this shouldn't be called more than once! fun init() { var firstTime = false if (!file.exists()) { firstTime = true firstTimeSetup() } if (firstTime) { println("Set up playlists db for the first time!") } else { connection = DriverManager.getConnection(dbPath) } } private fun firstTimeSetup() { file.createNewFile() connection = DriverManager.getConnection(dbPath) val stmt = connection.createStatement() stmt.executeUpdate("CREATE TABLE PlaylistItems(id varchar(255), url varchar(255), i INT);") stmt.executeUpdate("CREATE TABLE PlaylistMeta(id varchar(255), uid varchar(30), pid INT, name varchar(255), description varchar(255));") stmt.close() } @Synchronized fun sync(playlist: Playlist) { syncMeta(playlist) syncTracks(playlist) } private fun syncMeta(playlist: Playlist) { var stmt = connection.prepareStatement("SELECT * FROM PlaylistMeta WHERE id = ?;") stmt.setString(1, playlist.id) val res = stmt.executeQuery() val beforeFirst = res.isBeforeFirst stmt.close() if (!beforeFirst) { stmt = connection.prepareStatement("INSERT INTO PlaylistMeta VALUES (?, ?, ?, ?, ?);") } else { stmt = connection.prepareStatement("UPDATE PlaylistMeta SET id=?, uid=?, pid=?, name=?, description=? WHERE id = ?;") stmt.setString(6, playlist.id) } stmt.setString(1, playlist.id) stmt.setString(2, playlist.getUserID()) stmt.setString(3, playlist.getPlaylistNumber()) stmt.setString(4, playlist.info.name) stmt.setString(5, playlist.info.description) stmt.executeUpdate() stmt.close() } private fun syncTracks(playlist: Playlist) { var stmt = connection.prepareStatement("DELETE FROM PlaylistItems WHERE id = ?;") stmt.setString(1, playlist.id) stmt.execute() playlist.getTrackUrls().forEachIndexed {i, it-> stmt.close() stmt = connection.prepareStatement("INSERT INTO PlaylistItems VALUES (?,?,?);") stmt.setString(1, playlist.id) stmt.setString(2, it) stmt.setInt(3, i) stmt.executeUpdate() } } //This list could be empty! @Synchronized fun retrieveAllPlaylists(uid: String) : List<Playlist> { val stmt = connection.prepareStatement("SELECT * FROM PlaylistMeta WHERE uid = ?;") stmt.setString(1, uid) val res = stmt.executeQuery() val playlists = ArrayList<Playlist>() while (res.next()) { val info = Playlist.Info(res.getString(4), res.getString(5)) val id = res.getString(1) val miniStmt = connection.prepareStatement("SELECT * FROM PlaylistItems WHERE id = ? ORDER BY i;") miniStmt.setString(1, id) val miniRes = miniStmt.executeQuery() val tracks : MutableList<String> = ArrayList() while (miniRes.next()) { tracks.add(miniRes.getString(2)) } miniStmt.close() playlists.add(Playlist(tracks, id, info, playerManager)) } stmt.close() return playlists } @Synchronized fun retrievePlaylist(id: String) : Playlist? { var stmt = connection.prepareStatement("SELECT * FROM PlaylistMeta WHERE id = ?;") stmt.setString(1, id) val res = stmt.executeQuery() if (!res.isBeforeFirst) { return null } val info = Playlist.Info(res.getString(4), res.getString(5)) stmt.close() stmt = connection.prepareStatement("SELECT * FROM PlaylistItems WHERE id = ? ORDER BY i;") stmt.setString(1,id) val miniRes = stmt.executeQuery() val tracks : MutableList<String> = ArrayList() while (miniRes.next()) { tracks.add(miniRes.getString(2)) } stmt.close() return Playlist(tracks, id, info, playerManager) } @Synchronized fun remove(playlist: Playlist) { var stmt = connection.prepareStatement("DELETE FROM PlaylistMeta WHERE id = ?") stmt.setString(1, playlist.id) stmt.execute() stmt.close() stmt = connection.prepareStatement("DELETE FROM PlaylistItems WHERE id = ?") stmt.setString(1, playlist.id) stmt.execute() stmt.close() } override fun close() { if (this::connection.isInitialized) { connection.close() } } }<file_sep>package me.zeddit.playlists class InvalidTrackException(val urls: List<String>, val id: String) : Exception() { constructor(url: String, id: String) : this(listOf(url), id) }<file_sep>package me.zeddit import com.sedmelluq.discord.lavaplayer.player.AudioPlayer import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter import com.sedmelluq.discord.lavaplayer.track.AudioTrack import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason import net.dv8tion.jda.api.entities.Guild import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque class AudioGuild(manager: AudioPlayerManager, guild: Guild) : AudioEventAdapter() { // null stops the player. private val player: AudioPlayer = manager.createPlayer().apply { addListener(this@AudioGuild) guild.audioManager.sendingHandler = AudioPlayerSendHandler(this) } private val queue: BlockingQueue<AudioTrack> = LinkedBlockingDeque() val id: String = guild.id var looping = false private var current: AudioTrack? = null var expiry: Long = -1 override fun onTrackEnd(player: AudioPlayer, track: AudioTrack, endReason: AudioTrackEndReason) { if (endReason.mayStartNext) { nextTrack() } } fun queue(track: AudioTrack) { if (!player.startTrack(track, true)) { queue.offer(track) } else { current = track.makeClone() } } fun viewQueue() : List<AudioTrack> = queue.toList() fun clearQueue() { queue.clear() current = null } fun pop() : AudioTrack? { if (queue.isEmpty()) return null return queue.last().apply { queue.remove(this) } } //true if successful fun seek(ms: Long) : Boolean { if (player.playingTrack == null) return false if (!player.playingTrack.isSeekable) return false try { player.playingTrack.position = ms } catch (e: Exception) { return false } return true } fun togglePause() { player.isPaused = !player.isPaused } fun isPaused() : Boolean { return player.isPaused } fun nextTrack(noInterrupt: Boolean = false) { if (looping) { if (current == null) { player.startTrack(null, noInterrupt) } else { player.startTrack(current, noInterrupt) current = current!!.makeClone() } } else { player.startTrack(queue.poll()?.apply { current = this.makeClone() }, noInterrupt) } } override fun equals(other: Any?): Boolean { if (other === this) return true if (other is AudioGuild) { if (other.id == id) return true } return false } override fun hashCode(): Int { return id.hashCode() } }<file_sep>package me.zeddit import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers import com.sedmelluq.discord.lavaplayer.tools.FriendlyException import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import com.sedmelluq.discord.lavaplayer.track.AudioTrack import command.Command import command.CommandResult import command.GenericCommandName import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.* import net.dv8tion.jda.api.events.guild.GenericGuildEvent import net.dv8tion.jda.api.events.guild.GuildLeaveEvent import net.dv8tion.jda.api.events.guild.UnavailableGuildLeaveEvent import net.dv8tion.jda.api.events.guild.voice.* import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import net.dv8tion.jda.api.hooks.SubscribeEvent import java.awt.Color import java.time.Instant import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit class MainCommands : Command { private val playerManager : AudioPlayerManager = DefaultAudioPlayerManager().apply { AudioSourceManagers.registerLocalSource(this) AudioSourceManagers.registerRemoteSources(this) } private fun fmtQ(q: List<AudioTrack>) : String { if (q.isEmpty()) { return "Empty!" } val builder = StringBuilder() for (i in q.indices) { val tr = q[i] builder.append("${i + 1}. `${tr.info.title.esc()}` | `${tr.info.author.esc()}` | `${tr.duration.fmtMs()}`\n") } return builder.toString().apply { if (this.length >= 1024) { return this.substring(0..1023) } } } private enum class CommandName : GenericCommandName { PLAY, PLAY_YT_S, PLAY_SC_S, SKIP, DC, Q, PAUSE, LOOP, CLEAR, SEEK, POP, HELP, } override fun parseCommand(cmd: String, e: GuildMessageReceivedEvent): CommandResult? { val splits = cmd.substring(1 until cmd.length).split(" ") when { splits[0].equals(ignoreCase = true, other = "play") || splits[0].equals(ignoreCase = true, other = "p")-> { return when { splits.size== 2 && splits[1].matches(Regex("https?://"))-> { CommandResult(CommandName.PLAY, Array(1) {splits[1]}) } splits.size < 2 -> { return null } else -> CommandResult(CommandName.PLAY_YT_S, splits.args()) } } splits[0].equals(ignoreCase = true, other = "dc") -> { return CommandResult(CommandName.DC, Array(0) {""}) } splits[0].equals(ignoreCase = true, other = "playsc") || splits[0].equals(ignoreCase = true, other = "psc") -> { return when { splits.size == 2 -> { CommandResult(CommandName.PLAY, Array(1) {splits[1]}) } splits.size < 2 -> { return null } else -> CommandResult(CommandName.PLAY_SC_S, splits.args()) } } splits[0].equals(ignoreCase = true, other = "skip") || splits[0].equals(ignoreCase = true, other = "fs") -> { return CommandResult(CommandName.SKIP, splits.args()) } splits[0].equals(ignoreCase = true, other = "queue") -> { return CommandResult(CommandName.Q, splits.args()) } splits[0].equals(ignoreCase = true, other = "loop") -> { return CommandResult(CommandName.LOOP, splits.args()) } splits[0].equals(ignoreCase = true, other = "pause") -> { return CommandResult(CommandName.PAUSE, splits.args()) } splits[0].equals(ignoreCase = true, other = "clear") -> { return CommandResult(CommandName.CLEAR, splits.args()) } splits[0].equals(ignoreCase = true, other = "seek") -> { if (splits.args().size > 1) { return null } return CommandResult(CommandName.SEEK, splits.args()) } splits[0].equals(ignoreCase = true, other = "pop") -> { return CommandResult(CommandName.POP, splits.args()) } splits[0].equals(ignoreCase = true, other = "help") -> { return CommandResult(CommandName.HELP, splits.args()) } } return null } override fun onCommand(cmd: CommandResult, e: GuildMessageReceivedEvent) { val audioGuild : AudioGuild = guilds.firstOrNull { it.id == e.guild.id } ?: AudioGuild(playerManager, e.guild).apply { guilds.add(this) } val builder = EmbedBuilder().setColor(Color.GREEN).setTitle("Result").setTimestamp(Instant.now()) when (cmd.commandName) { CommandName.PLAY, CommandName.PLAY_SC_S, CommandName.PLAY_YT_S -> { val chn = e.member!!.voiceState!!.channel val chnEmbed = voiceChnPrecons(chn, e.guild.retrieveMember(jda!!.selfUser).complete()) if (chnEmbed != null || chn == null) { e.channel.sendMessageEmbeds(chnEmbed!!).queue() return } val argsJoined = cmd.args.joinToString(" ") { it } val identifier = when (cmd.commandName) { // spaces issue CommandName.PLAY -> cmd.args[0] CommandName.PLAY_YT_S -> "ytsearch:$argsJoined" CommandName.PLAY_SC_S -> "scsearch:$argsJoined" else -> "" } playerManager.loadItemOrdered(audioGuild, identifier, object : AudioLoadResultHandler { override fun trackLoaded(track: AudioTrack) { e.channel .sendMessageEmbeds(builder.addField("Adding `${track.info.title.esc()}` to q!".toResultField(true)).build()) .queue() track.play(audioGuild, chn,e.guild.audioManager) } override fun playlistLoaded(playlist: AudioPlaylist) { if (cmd.commandName == CommandName.PLAY_YT_S || cmd.commandName == CommandName.PLAY_SC_S) { val track = playlist.tracks[0] e.channel .sendMessageEmbeds(builder.addField("Adding `${track.info.title.esc()}` to q!".toResultField(true)).build()) .queue() track.play(audioGuild, chn,e.guild.audioManager) } else { e.channel .sendMessageEmbeds(builder.addField("Detected playlist, adding ${playlist.tracks.size} tracks to q!".toResultField(true)).build()) .queue() playlist.tracks.forEach { it.play(audioGuild, chn, e.guild.audioManager) } } } override fun noMatches() { e.channel .sendMessageEmbeds(builder.addField("No matches for your query!".toResultField()) .setColor(Color.RED).build()) .queue() } override fun loadFailed(ex: FriendlyException) { ex.printStackTrace() e.channel .sendMessageEmbeds(builder.addField("Couldn't load the track(s) due to an internal error!".toResultField()) .setColor(Color.RED).build()) .queue() } }) } CommandName.SKIP -> { audioGuild.nextTrack()// Add a dj role style shitter e.channel.sendMessageEmbeds(builder.addField("Skipped!".toResultField(true)).build()).queue() } CommandName.Q -> { e.channel.sendMessageEmbeds(builder.addField("Queue contents", fmtQ(audioGuild.viewQueue()), false).build()).queue() } CommandName.DC -> { if (e.guild.audioManager.isConnected) { e.guild.audioManager.closeAudioConnection() e.channel.sendMessageEmbeds(builder.addField("Disconnected!".toResultField(true)).build()).queue() // probably dont need to clear q because event handler fn handles? } else { e.channel.sendMessageEmbeds(builder.setColor(Color.RED).addField("Not currently connected to a voice channel!".toResultField()).build()).queue() } } CommandName.LOOP -> { audioGuild.looping = !audioGuild.looping if (audioGuild.looping) { e.channel.sendMessageEmbeds(builder.addField("The player is now looping the current track!".toResultField(true)).build()).queue() } else { e.channel.sendMessageEmbeds(builder.addField("The player is no longer looping the current track!".toResultField(true)).build()).queue() } } CommandName.PAUSE -> { audioGuild.togglePause() if (audioGuild.isPaused()) { e.channel.sendMessageEmbeds(builder.addField("Paused the player!".toResultField(true)).build()).queue() } else { e.channel.sendMessageEmbeds(builder.addField("Resumed the player!".toResultField(true)).build()).queue() } } CommandName.CLEAR -> { audioGuild.clearQueue() e.channel.sendMessageEmbeds(builder.addField("Cleared the queue!".toResultField(true)).build()).queue() } CommandName.SEEK -> { val ms : Long = seekToMs(cmd.args[0]) ?: run { e.channel.sendMessageEmbeds(builder.setColor(Color.RED).addField("Could not parse seek arg!".toResultField()).build()).queue() return } if (!audioGuild.seek(ms)) { e.channel.sendMessageEmbeds(builder.setColor(Color.RED).addField("Could not seek to that position!".toResultField()).build()).queue() } else { e.channel.sendMessageEmbeds(builder.addField("Now at ${ms.fmtMs()}!".toResultField(true)).build()).queue() } } CommandName.POP -> { val pop =audioGuild.pop() if (pop == null) { e.channel.sendMessageEmbeds(builder.setColor(Color.RED).addField("Queue is empty!".toResultField()).build()).queue() } else { e.channel.sendMessageEmbeds(builder.addField("Removed `${pop.info.title.esc()}` from q!".toResultField(true)).build()).queue() } } CommandName.HELP -> { e.channel.sendMessageEmbeds(builder .addField("Available commands:", "!help- Lists available commands\n" + "!p, !play (yt search term/url)- Attempts to play audio\n" + "!psc, !playsc (sc search term/url)- Attempts to play from soundcloud (EXPERIMENTAL)\n" + "!skip, !fs- Skips the current track.\n" + "!pause- Toggles pause on the player.\n" + "!loop- Toggles loop on the player.\n" + "!queue- Displays all queued songs.\n" + "!clear- Clears the queue.\n" + "!pop- Removes the last added element to the queue.\n" + "!seek (HH:MM:SS)- Seeks to the given timestamp.\n" + "!dc- Disconnects the bot, this happens automatically if the bot is alone in " + "vc for 2 minutes. When the bot disconnects, all pause and loop options are reset and the queue is cleared.", false).build()).queue() } } } private fun seekToMs(string: String) : Long? { if (!string.matches(Regex("[:\\d]+"))) return null val splits = string.split(":") if (splits.size > 3) { return null } var multiplier = 1 var sum : Long = 0 splits.asReversed().forEach { try { sum += it.toLong() * multiplier } catch (e: NumberFormatException) { return null } multiplier *= 60 } return sum * 1000 } @SubscribeEvent fun onGuildLeave(e: GuildLeaveEvent) = guilds.removeIf { it.id == e.guild.id } @SubscribeEvent fun onUnGuildLeave(e:UnavailableGuildLeaveEvent) = guilds.removeIf { it.id == e.guildId } private val dcScheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor() @SubscribeEvent fun onVcDc(e: GuildVoiceLeaveEvent) { e.audioGuild { vcDc(e.member, it, e.channelLeft, e.guild) } } private fun vcDc(member: Member, audioGuild: AudioGuild, chn: VoiceChannel, guild: Guild) { val id = jda!!.selfUser.id if (member.id == id) { audioGuild.apply { clearQueue(); looping = false; if (isPaused()) togglePause(); nextTrack() } } else { if (chn.hasSelf()) { if (chn.members.size == 1) { scheduleDc(audioGuild, guild) } } } } @SubscribeEvent fun onVcMove(e: GuildVoiceMoveEvent) { e.audioGuild { if (e.member.id == jda!!.selfUser.id) return if (e.channelJoined.hasSelf()) { it.expiry = -1 } else if (e.channelLeft.hasSelf()) { vcDc(e.member,it, e.channelLeft, e.guild) } } } @SubscribeEvent fun onVcConnect(e: GuildVoiceJoinEvent) { e.audioGuild { if (e.channelJoined.hasSelf()) { it.expiry = -1 } } } private inline fun GenericGuildEvent.audioGuild(block : (AudioGuild) -> Unit) { val audioGuild = guilds.firstOrNull {this.guild.id == it.id} audioGuild?.let { block.invoke(it) } } private fun scheduleDc(audioGuild: AudioGuild, guild: Guild) { val delay: Long = 2000 * 60 val exp = System.currentTimeMillis() + delay audioGuild.expiry = exp dcScheduler.schedule(delay, TimeUnit.MILLISECONDS) { if (audioGuild.expiry == exp) { val manager = guild.audioManager if (manager.isConnected) { manager.closeAudioConnection() audioGuild.expiry = -1 } } } } }<file_sep>package me.zeddit.playlists import me.zeddit.firstNullable import me.zeddit.storageHandler // A LRU cache for playlists class PlaylistCache(private val maxSize : Int) { private val deque = ArrayDeque<Playlist>() @Synchronized fun cache(playlist: Playlist) { if (deque.contains(playlist)) { deque.remove(playlist) } if (deque.size >= maxSize) { storageHandler.sync(deque.first()) deque.removeFirst() } deque.addLast(playlist) } fun getPlaylist(id: String): Playlist? = getPlaylist { it.id == id } fun getPlaylist(predicate: (Playlist) -> Boolean) : Playlist? { return deque.firstNullable { predicate.invoke(it) }.apply { this?.let { deque.remove(this) deque.addLast(this) }} } fun allItems() : Array<Playlist> { val iterator = deque.iterator() return Array(deque.size) {iterator.next()} } fun remove(playlist: Playlist) { deque.remove(playlist) } }<file_sep>package command import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent interface Command { fun parseCommand(cmd: String, e: GuildMessageReceivedEvent) : CommandResult? fun onCommand(cmd: CommandResult, e: GuildMessageReceivedEvent) }<file_sep>package me.zeddit import com.google.gson.Gson import com.sedmelluq.discord.lavaplayer.track.AudioTrack import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.* import net.dv8tion.jda.api.managers.AudioManager import net.dv8tion.jda.api.utils.MarkdownSanitizer import java.awt.Color import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.time.Instant import java.util.concurrent.Future import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit fun String.esc() : String { return MarkdownSanitizer.escape(this) } fun List<String>.args() : Array<String> { return Array(this.size -1) { this[it + 1] } } fun AudioTrack.play(audioGuild: AudioGuild, chn: VoiceChannel, audioManager: AudioManager) { if (!audioManager.isConnected) { audioManager.openAudioConnection(chn) } audioGuild.queue(this) } // null result == success fun voiceChnPrecons(chn: VoiceChannel?, self: Member) : MessageEmbed? { val builder = EmbedBuilder().setColor(Color.RED).setTitle("Error").setTimestamp(Instant.now()) val wrongMsg = "Something went wrong!" return when { chn == null -> builder.addField(wrongMsg, "You are not in a voice channel!", false).build() chn.userLimit >= chn.members.size+1 -> builder.addField(wrongMsg, "The voice channel you are in is full!", false).build() !self.hasPermission(chn, Permission.VOICE_CONNECT) -> builder.addField(wrongMsg, "The bot doesn't have enough permissions to join your voice channel!", false).build() else -> null } } fun Long.fmtMs() : String { return String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(this), TimeUnit.MILLISECONDS.toMinutes(this) % TimeUnit.HOURS.toMinutes(1), TimeUnit.MILLISECONDS.toSeconds(this) % TimeUnit.MINUTES.toSeconds(1)) } fun GuildChannel.hasSelf() : Boolean = this.members.map { it.user.id }.contains(jda.selfUser.id) fun ScheduledExecutorService.schedule(delay: Long, unit: TimeUnit, block: () -> Unit) { this.schedule(block, delay, unit) } val gson = Gson() inline fun <reified T> Any.fromJson() = gson.fromJson(this.toString(), T::class.java) inline fun <reified T> ByteArray.fromJson(charset: Charset = StandardCharsets.UTF_8) = gson.fromJson(String(this, charset), T::class.java) inline fun <reified T> String.toJson() : T = gson.fromJson(this, T::class.java) fun <T> Future<T>.join() = this.get() fun eprintln(a: Any) {System.err.println(a.toString())} fun <T> List<Future<T>>.awaitAll(): List<T> { val complete = ArrayList<T>() var filtered = this.filterNot { it.isCancelled } while (filtered.isNotEmpty()) { filtered[0].get() filtered = filtered.filter { it.isDone }.onEach { complete.add(it.get()) }.toMutableList().apply { this.removeIf { it.isDone } } filtered = filtered.filterNot { it.isCancelled } } return complete // shouldnt block if they are all complete } inline fun <T> Iterable<T>.firstNullable(predicate: (T) -> Boolean) : T? { for (element in this) if (predicate(element)) return element return null } fun String.toResultField(success: Boolean = false) : MessageEmbed.Field = MessageEmbed.Field(if (success) "Success" else "Failure", this, false) fun Array<String>.joinToString(offset: Int = 0, separator: String = " ") : String = Array(this.size - offset) {this[it + offset]}.joinToString(separator) inline fun <T, R> Iterable<T>.filterMap(predicate: (T) -> Boolean, map: (T) -> R) : List<R> = this.filter(predicate).map(map)
0ef91476369532e6c1023ecb0b88901fff8571ed
[ "Kotlin" ]
13
Kotlin
orang3-juic3/megaboom3
a9262bfa7caf556eafa16468912cfad0e69522a1
6d7cf98ad00a6540a5a802b2eb5c868c015aa4b8
refs/heads/master
<repo_name>mbergal/javascript-experiments<file_sep>/async-await/asyncawait.ts var b = new Promise( function( resolve, reject ) { reject( "1" ); } ); async function a() { var first = await b; console.log( "a - " + first ); var second = first + " 2"; return second; } async function main() { try { var r = await a(); return r; } catch ( ex ) { console.log( "Exception: " + ex ); } } main().then( value=>{ console.log( value ) } ); <file_sep>/typescript/src/module1.ts // @flow export function f() : number { return 1; }<file_sep>/typescript/src/a.ts interface ISome { (n:number):ISome; } var a : ISome = null; var b = a; <file_sep>/typescript/src/index.ts // @flow ///aaaaaaaaaa import { f } from './module1' //import { install } from 'source-map-support'; var c = { a: 1, b: 2 } async function a() { throw new Error( "!!!!"); // this should point to original file } async function b() { return a(); } // install(); var ra = f(); b(); <file_sep>/flow/src/service.js // @flow // trackingService.js var trackingService = { enableIntercomTracking() { }, addons : { googleClassroom: { enabled() { }, disabled() { } }, } }; type TrackingService = typeof trackingService; // SomewhereElse.js function SomethingElse( trackingService: TrackingService ) { trackingService.enableIntercomTracking(); // trackingService.enableIntercomTracking2(); } <file_sep>/async-await/asyncawait.js var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments)).next()); }); }; var b = new Promise(function (resolve, reject) { reject("1"); }); function a() { return __awaiter(this, void 0, void 0, function* () { var first = yield b; console.log("a - " + first); var second = first + " 2"; return second; }); } function main() { return __awaiter(this, void 0, void 0, function* () { try { var r = yield a(); return r; } catch (ex) { console.log("Exception: " + ex); } }); } main().then(value => { console.log(value); }); <file_sep>/flow/src/contains.js 'use strict'; var a = 'aaaa'; console.log( a.contains('a'));
eb9c90370de137ee4cdbb9327cef881644d2ef6f
[ "JavaScript", "TypeScript" ]
7
TypeScript
mbergal/javascript-experiments
a6882bc8f6b2ebaef94a535f0f643a06658e3678
12e91801d7290caf5f610d173801b49fc396a118
refs/heads/master
<repo_name>mgiamberardino/PyLifeGame<file_sep>/src/board.py class Board(): ALIVE = 1 DEAD = 0 def __init__(self, width=8, height=8, stay=(2,3), born=(3,)): self._width = width self._height = height self._stay=stay self._born=born self.set_board(self.get_empty_board_list()) def get_empty_board_list(self): return [[self.DEAD] * self._width for _ in range(self._height)] def set_board(self, board): self._board = board; self._width = len(board[0]) self._height = len(board) def get(self): return self._board def size(self): return (self._width, self._height) def count_neighbors_alive(self, x, y): x_left = x - 1 if x > 0 else self._width-1 x_right = x + 1 if x < self._width-1 else 0 y_up = y - 1 if y > 0 else self._height-1 y_down = y + 1 if y < self._height-1 else 0 return ( self._board[y_up][x_left], self._board[y_up][x], self._board[y_up][x_right], self._board[y][x_left], self._board[y][x_right], self._board[y_down][x_left], self._board[y_down][x], self._board[y_down][x_right] ).count(self.ALIVE) def calculate_state(self, state, neighbors_alive): if ((state == self.ALIVE and neighbors_alive in self._stay) or (state == self.DEAD and neighbors_alive in self._born)): return self.ALIVE else: return self.DEAD def tick(self): board_ = self.get_empty_board_list() for i in range(self._width): for j in range(self._height): args = (self._board[j][i], self.count_neighbors_alive(i,j)) board_[j][i]=self.calculate_state(*args) self.set_board(board_) def set_alive(self, x, y): self._board[y][x] = self.ALIVE def set_dead(self, x, y): self._board[y][x] = self.DEAD def get_cells_alive(self): cells = [] for i in range(self._width): for j in range(self._height): if self._board[j][i] == self.ALIVE: cells.append((i,j)) return cells <file_sep>/src/game.py import tkinter as tk from board import Board from threading import Thread import time def print_board(board): for r in board: print(r) class LifeGame(tk.Frame): def __init__(self, board, cell_size=20): super(LifeGame, self).__init__(tk.Tk()) self.master.title('Juego de la vida') self.grid() self.board = board self.cell_size = cell_size self.create_widgets() self.draw_grid() self.cells_alive = {} self.create_events() self.running = False self.speed = 1 self.mainloop() def create_widgets(self): width, height = self.board.size() kwargs = { 'width': width * self.cell_size, 'height': height * self.cell_size, 'bg': 'white' } self.canvas = tk.Canvas(self, **kwargs) self.canvas.grid() def draw_grid(self): self.draw_vertical_lines() self.draw_horizontal_lines() def draw_vertical_lines(self, color='gray'): width, height = self.board.size() for i in range(width - 1): x = (self.cell_size * i) +self.cell_size y0 = 0 y1 = self.cell_size * height self.canvas.create_line(x,y0,x,y1, fill=color) def draw_horizontal_lines(self, color='gray'): width, height = self.board.size() for i in range(height - 1): y = (self.cell_size * i) +self.cell_size x0 = 0 x1 = self.cell_size * width self.canvas.create_line(x0,y,x1,y, fill=color) def draw_cell(self, x, y, color='black'): x0 = x * self.cell_size y0 = y * self.cell_size x1 = x0 + self.cell_size y1 = y0 + self.cell_size args = (x0, y0, x1, y1) _id = self.canvas.create_rectangle(*args, width=0, fill=color) self.cells_alive[(x, y)] = _id self.board.set_alive(x, y) def del_cell(self, x, y): self.canvas.delete(self.cells_alive[(x,y)]) del self.cells_alive[(x,y)] self.board.set_dead(x,y) def toggle_cell(self, event): x = event.x // self.cell_size y = event.y // self.cell_size if (x,y) in self.cells_alive: self.del_cell(x, y) else: self.draw_cell(x, y) def create_events(self): self.canvas.bind_all('<Button 1>', self.toggle_cell) self.canvas.bind_all('<space>', self.toggle_run) self.canvas.bind_all('a', self._accelerate) self.canvas.bind_all('z', self._deaccelerate) def _accelerate(self, event): self.speed += 1 def _deaccelerate(self, event): self.speed = self.speed -1 if self.speed > 1 else 1 def draw(self): self.clear() for cell_pos in self.board.get_cells_alive(): self.draw_cell(*cell_pos) def clear(self): for _id in self.cells_alive.values(): self.canvas.delete(_id) self.cells_alive = {} def toggle_run(self, event): if self.running: self.running = False else: self.running = True Thread(target=self.tick).start() def tick(self): while self.running: self.board.tick() self.draw() time.sleep(1/self.speed) if __name__ == '__main__': import sys args = map(lambda x: x.split(','),sys.argv[1:]) print(*args) b = Board(80, 50, (2,3), (3,6)) l = LifeGame(b, cell_size=15)
09bdab8b857a00453dd729e39352b4d2701955f8
[ "Python" ]
2
Python
mgiamberardino/PyLifeGame
b4d816e312d0702dc60066791644f989a512d5e3
04399fa5cfe11b2b21df708ecdfc6df3e72455fb
refs/heads/master
<repo_name>GuidoDipietro/UTN-DDS-modulo-stock<file_sep>/README.md # Módulo de manejo de stock y precios UTN FRBA - Cátedra de Diseño de Sistemas ## Enunciado Nos han solicitado el diseño y desarrollo de un módulo que se encargue de calcular el stock de productos de cualquier local comercial, así como también el cálculo de precios de los mismos. Se debe tener en cuenta que no solamente existen y se venden productos simples, sino que también existen combos. Un combo está formado por productos que se venden juntos. También pueden existir combos de combos. Por ejemplo, un local de motos vende motos, cascos, guantes, chalecos, pilotos, entre otros productos; pero también vende algunos combos como por ejemplo guantes + casco + chaleco. Cada producto tiene un precio en particular. El precio del combo es el resultado de la suma de los productos que contiene. Además, se debe permitir aplicar descuentos a los distintos productos/combos, los cuales podrían ser acumulables. Por último, nos han avisado que los productos/combos podrían ser vendidos con distintos packagings, cada uno de los cuales tiene un precio particular que se debería sumar al precio final del producto. ## Diagrama de clases ![Diagrama de Clases](README_img/dc.png)<file_sep>/src/main/java/producto/Combo.java package producto; import java.util.*; public class Combo extends Producto { private final List<Producto> productos; // Inits public Combo() { this.productos = new ArrayList<>(); } public Combo(Producto ...ps) { this.productos = Arrays.asList(ps); } // Metodos public Double precio() { return this.productos.stream().mapToDouble(Producto::precio).sum(); } public Integer stock() { OptionalInt stock = this.productos.stream().mapToInt(Producto::stock).min(); if (stock.isPresent()) return stock.getAsInt(); return -1; } public void agregarProducto(Producto p) { this.productos.add(p); } public void agregarProductos(Producto ...ps) { Collections.addAll(this.productos, ps); } } <file_sep>/src/main/java/decorators/Packaging.java package decorators; import producto.Producto; public class Packaging extends Decorado { private final Double precio; public Packaging(Producto producto, Double precio) { this.producto = producto; this.precio = precio; } public Double precio() { return super.producto.precio() + precio; } }
73ea6a995f7eeb66a8f248ea6b5a308a02833a43
[ "Markdown", "Java" ]
3
Markdown
GuidoDipietro/UTN-DDS-modulo-stock
f6c7015a201e6224101a4195c6ce7611d72419b6
8317586274c763ebccfab203d186d9ff2446061f
refs/heads/master
<file_sep>package com.ch.ch09.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ch.ch09.model.Board; import com.ch.ch09.service.BoardService; import com.ch.ch09.service.PagingBean; @Controller public class BoardController { @Autowired private BoardService bs; @RequestMapping("list") // 게시글을 읽어서 보내려는 목적 public String list(Board board, String pageNum, Model model) { // ++ int rowPerPage = 10; // 페이지가 지정되지 않으면 1페이지를 기본으로 보여주기 위해서 만듦 if (pageNum == null || pageNum.equals("")) { // 숫자는 null하고 비교가 안되기 때문에 String pageNum으로 선언을 해줌 // ++ pageNum = "1"; // } int currentPage = Integer.parseInt(pageNum); // String이었던 pageNum이 int 형으로 바뀐다. // ++ // 게시글이 총 몇 개인지 알아야 페이징 처리를 할 수 있기 때문에 total을 생성해준다. // int total = bs.getTotal(); int total = bs.getTotal(board); // 시작번호 = (페이지 번호 -1) * 페이지당 개수 +1 int startRow = (currentPage - 1) * rowPerPage + 1; // 끝 번호 = 시작 번호 + 페이지당 개수 - 1 int endRow = startRow + rowPerPage - 1; board.setStartRow(startRow); board.setEndRow(endRow); // List<Board> list = bs.list(startRow, endRow); // board에는 search, keyword, startRow, endRow가 들어있다. List<Board> list = bs.list(board); PagingBean pb = new PagingBean(currentPage, rowPerPage, total); // writer, subject, content라고 되어있는 것을 한글로 바꾸기 위해서 생성 String[] tit = {"작성자", "제목","내용","제목+내용"}; model.addAttribute("tit",tit); model.addAttribute("list", list); model.addAttribute("board", board); // board값을 보내줘야 페이지가 바뀌어도 유지된다. model.addAttribute("pb", pb); return "list"; } @RequestMapping("insertForm") public String insertForm(String nm, String pageNum, Model model) { // ++ // 답변용 ref, re_level, re_step int ref = 0, re_level = 0, re_step = 0, num = 0; // 답변글이 아님 if (nm != null && !nm.equals("")) { // 널도 아니고 뭐도 없다는 뜻 --> 답변글이라는 뜻임! num = Integer.parseInt(nm); // 답변 Board board = bs.select(num); // 원본글의 ref, re_level, re_step가 답변글이 아니면 // 모두 0,0,0으로 채워질텐데 답변글이면 아래와 같이 값이 채워진다. ref = board.getRef(); re_level = board.getRe_level(); re_step = board.getRe_step(); } model.addAttribute("ref", ref); model.addAttribute("re_level", re_level); model.addAttribute("re_step", re_step); model.addAttribute("num", num); model.addAttribute("pageNum", pageNum); // ++ return "insertForm"; } @RequestMapping("insert") public String insert(Board board, Model model, HttpServletRequest request, String pageNum) { // ++ board.setIp(request.getLocalAddr()); // ip setting int number = bs.maxNum(); if (board.getNum() != 0) { // 답변글 // re_step을 정리 bs.updateRe_step(board); board.setRe_level(board.getRe_level() + 1); board.setRe_step(board.getRe_step() + 1); } else { board.setRef(number); // 답변이 아닐 때는 ref와 num의 number는 같다. //board.setNum(number); == // // board.setRef(number); } board.setNum(number); int result = bs.insert(board); model.addAttribute("result", result); model.addAttribute("pageNum", pageNum); // ++ return "insert"; } @RequestMapping("view") public String view(int num, Model model, String pageNum) { // ++ bs.updateReadCount(num); Board board = bs.select(num); model.addAttribute("board", board); // 보던 페이지 그대로 유지해서 돌아가게 하기 위해서 model.addAttribute("pageNum", pageNum); // ++ return "view"; } @RequestMapping("updateForm") public String updateForm(int num, Model model, String pageNum) { // ++ Board board = bs.select(num); model.addAttribute("board", board); model.addAttribute("pageNum", pageNum); // ++ return "updateForm"; } @RequestMapping("update") public String update(Board board, String pageNum, Model model) { // ++ int result = bs.update(board); model.addAttribute("result", result); model.addAttribute("board", board); model.addAttribute("pageNum", pageNum); // ++ return "update"; } @RequestMapping("insertBoard") public String updateForm(HttpServletRequest request) { String ip = request.getLocalAddr(); for (int i = 1; i <= 230; i++) { // 자동으로 230개를 추가해준다. Board board = new Board(); board.setSubject("자동 제목 생성" + i); board.setWriter("관리자" + i); board.setEmail("admin" + i + "@<EMAIL>"); board.setPassword("<PASSWORD>"); board.setContent("자동 내용 생성" + i); board.setIp(ip); bs.insert(board); } return "insertBoard"; } @RequestMapping("deleteForm") public String deleteForm(int num, String pageNum, Model model) { // ++ Board board = bs.select(num); model.addAttribute("board", board); model.addAttribute("pageNum", pageNum); // ++ return "deleteForm"; } @RequestMapping("delete") public String delete(int num, String pageNum, Model model) { // ++ int result = bs.delete(num); model.addAttribute("result", result); model.addAttribute("pageNum", pageNum); // ++ return "delete"; } }
dd7a7933cd3ee082db75f4a5af101212fbb191ad
[ "Java" ]
1
Java
yuhuikim/ch09_20201005
e08507067af5b4d6e38cbe9d6abc43557884fb29
e556f7733d46498733f4ef4e4c7186acaacd0fe5
refs/heads/main
<file_sep>import React, { Component } from "react"; import { View, Text, TextInput, Image, Modal, KeyboardAvoidingView, StyleSheet, TouchableOpacity, Alert, ScrollView, Button, } from "react-native"; //import MyHeader from '../componenet/MyHeader' import AlgebraFinder from './AlgebraFinder' import AreaFinder from './areaFinder' import PolygonFinder from './PolygonFinder' export default class HomeScreen extends Component{ render(){ return( <View> <TouchableOpacity style={styles.button} onPress={()=>{ this.props.navigation.navigate("PolygonFinder") }} > <Text style={styles.buttontext}> POLYGON </Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={()=>{ this.props.navigation.navigate("AreaFinder") }} > <Text style={styles.buttontext}> area and perimeter </Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={()=>{ this.props.navigation.navigate("AlgebraFinder") }} > <Text style={styles.buttontext}> algebra </Text> </TouchableOpacity> </View> ) } } const styles=StyleSheet.create({ button: { marginTop : 100 , marginBottom:50, width: 300, height:50 , marginLeft : "40%" , justifyContent: "center", alignItems: "center", // borderRadius: RFValue(25), backgroundColor: "black", shadowColor: "#000", //marginBottom:RFValue(10), shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.3, shadowRadius: 10.32, elevation: 16, }, buttontext: { color: "white", fontWeight: "200", fontSize: 30, }, }) <file_sep>import React, { Component } from "react"; import { View, Text, TextInput, Image, Modal, KeyboardAvoidingView, StyleSheet, TouchableOpacity, Alert, ScrollView, } from "react-native"; export default class PolygonFinder extends Component { constructor(){ super(); this.state={ sides : 0 , angle : 0 , } } processor=()=>{ //angle = (sides-2)*180 , var sides= this.state.sides var sangle = (sides-2)*180; this.setState ({ angle:sangle }) } render(){ return( <View > <TextInput style= {styles.formTextInput} placeholder="Enter no.of sides" placeholderTextColor="gray" onChangeText={(text) => { this.setState({ sides : text, }); }} value={this.state.sides} /> <Text style={{fontSize:20,fontWeight:'bold',color:'blue', textAlign :"center",alignItems:"center",justifyContent:"center"}}> Sum of the interior angles : {this.state.angle} </Text> < TouchableOpacity style={styles.button} onPress={()=>{ this.processor()}} > <Text style={styles.buttonText}> Find </Text> </TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ button:{ width: "75%", height: 60, justifyContent: "center", alignItems: "center", borderRadius:50, backgroundColor: "#32867d", shadowColor: "#000", shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.44, shadowRadius: 10.32, elevation: 16, alignSelf:"center" , marginTop:50, } , buttonText: { color: "black", fontWeight: "200", fontSize: 20, }, formTextInput: { width: "75%", height:35, borderWidth: 1, padding: 10, alignItems:"center", alignSelf:"center", justifyContent:"center", marginTop:100, }, }) <file_sep>import React, { Component } from "react"; import { View, Text, TextInput, Image, Modal, KeyboardAvoidingView, StyleSheet, TouchableOpacity, Alert, ScrollView, } from "react-native"; import MyHeader from "../componenet/MyHeader"; export default class WelcomeScreen extends Component{ render(){ return( <View> <Text style = {styles.theoremfinder}> THEOREM FINDER </Text> <View style={{flex:0.15}}/> <View style={styles.mit}> <Image source={require('../assets/mit.png')} style={styles.mitimage} /> </View> <Text style = {styles.welcome}> WELCOME !!! </Text> <TouchableOpacity style={styles.button} onPress={() => { this.props.navigation.navigate("HomeScreen") }} > <Text style={styles.buttonText}>next</Text> </TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ mit :{ flex:0.85, justifyContent:"center", alignItems:"center", }, mitimage : { width: 150, height: 150, marginLeft: 95, alignItems:"center", }, theoremfinder:{ textAlign: 'center', fontSize: 30, fontWeight: 'bold', }, welcome : { textAlign: 'center', fontSize: 30, fontWeight: 'bold', }, button: { marginTop : 200 , width: 300, height:50 , marginLeft : "40%" , justifyContent: "center", alignItems: "center", // borderRadius: RFValue(25), backgroundColor: "black", shadowColor: "#000", //marginBottom:RFValue(10), shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.3, shadowRadius: 10.32, elevation: 16, }, buttonText: { color: "white", fontWeight: "200", fontSize: 30, }, }) <file_sep>import React, { Component } from "react"; import { View, Text, TextInput, Image, Modal, KeyboardAvoidingView, StyleSheet, TouchableOpacity, Alert, ScrollView, } from "react-native"; export default class AreaFinder extends Component { constructor(){ super(); this.state={ length: 0 , breadth : 0, area : 0 , perimeter : 0 , } } areaprocessor=()=>{ var l =this.state.length var b = this.state.breadth var area = l*b this.setState({ area:area }) } perimeterprocessor=()=>{ var l =this.state.length var b = this.state.breadth var perimeter = (l-(-b))*2 this.setState({ perimeter:perimeter }) } render(){ return( <View> <TextInput style = {styles.formTextInput} placeholder="Enter value of length" placeholderTextColor="gray" onChangeText={(text) => { this.setState({ length : text, }); }} value={this.state.length} /> <TextInput style={styles.formTextInput} placeholder="Enter value of width" placeholderTextColor="gray" onChangeText={(text) => { this.setState({ breadth : text, }); }} value={this.state.breadth} /> <Text style={{fontSize:20,fontWeight:'bold',color:'blue', textAlign :"center",alignItems:"center",justifyContent:"center"}}> area : {this.state.area} </Text> <Text style={{fontSize:20,fontWeight:'bold',color:'blue', textAlign :"center",alignItems:"center",justifyContent:"center"}}> perimeter : {this.state.perimeter} </Text> < TouchableOpacity style={styles.button} onPress={()=>{ this.areaprocessor()}} > <Text style={styles.buttonText}> Find area </Text> </TouchableOpacity> < TouchableOpacity style={styles.button} onPress={()=>{ this.perimeterprocessor()}} > <Text style={styles.buttonText}> Find perimeter </Text> </TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ button:{ width: "75%", height: 60, justifyContent: "center", alignItems: "center", borderRadius:50, backgroundColor: "#32867d", shadowColor: "#000", shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.44, shadowRadius: 10.32, elevation: 16, alignSelf:"center" , marginTop:50, } , buttonText: { color: "black", fontWeight: "200", fontSize: 20, }, formTextInput: { width: "75%", height:35, borderWidth: 1, padding: 10, alignItems:"center", alignSelf:"center", justifyContent:"center", marginTop:100, }, })<file_sep>import React, { Component } from "react"; import { View, Text, TextInput, Image, Modal, KeyboardAvoidingView, StyleSheet, TouchableOpacity, Alert, ScrollView, } from "react-native"; import { Header } from 'react-native-elements'; export default class AlgebraFinder extends Component { render(){ return( <View style={{ flex: 1}}> <View style={{ flex: 0.1}}> </View> <TextInput style={styles.formTextInput} placeholder="Enter equation" placeholderTextColor="gray" /> < TouchableOpacity style={styles.button}> <Text style = {styles.buttonText}> Find </Text> </TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ button:{ width: "75%", height: 60, justifyContent: "center", alignItems: "center", borderRadius:50, backgroundColor: "#32867d", shadowColor: "#000", shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.44, shadowRadius: 10.32, elevation: 16, alignSelf:"center" , marginTop:50, } , buttonText: { color: "black", fontWeight: "200", fontSize: 20, }, formTextInput: { width: "75%", height:35, borderWidth: 1, padding: 10, alignItems:"center", alignSelf:"center", justifyContent:"center", marginTop:100, }, })
30f5ab18d5abdc349962237d43c81c9b9f34ab66
[ "JavaScript" ]
5
JavaScript
pritishprocoder/myGame
529e143d416083104c4c4a4c5c385757c360c109
d24437268a9906f53d50dc4562ba3acb04ce4921
refs/heads/master
<repo_name>RebornGeek/guardianforge.com<file_sep>/README.md # Welcome Guardians! ## Why does this project exist? It is my mission to make sure every guardian understands how to make the most optimal build for the activities they enjoy in Destiny 2. With the help of the community, we will be building a clean, fast web application that will allow players to create, rate, & share these builds with the community in a more streamlined fashion. ## Features at launch - A complete character planner that will allow guardians to create new builds. - The ability to import all gear from your own account for use in character planning/optimizing. - Builds created can be shared and rated by the community. ## 'Nice to have' features - The ability to compare your own gear against the top rolls available on each item. - Swap out builds on demand in game with the simple click of a button.<file_sep>/config.rb require 'compass/import-once/activate' http_path = "/" css_dir = "www/assets/css/compass" sass_dir = "www/assets/sass"
3e73dd0357d6206db5189e4091ba29b87292bf41
[ "Markdown", "Ruby" ]
2
Markdown
RebornGeek/guardianforge.com
4aaa03a50ff531c25ebbd2df563ca2df7bf71c26
23619077c47bb15d51d357e0fc1a3f66a5643ce8
refs/heads/master
<file_sep># Swift Issues We are using latest development versions of Swift Toolchain and SDK for Windows. As platform support is not ready yet, bugs and regressions are our fellow companions. This collection of code samples is to keep track on issues we found, reported and keeping eye on. ## Usage Most of samples provided with `build.cmd` batch file to aid in issue demonstration. Additional instructions/steps may be available in README.md of corresponding issue. ## Requirements Swift Toolchain and SDK for Windows x64. ## Tracked Issues - Linker fails on specific code with CodeView debug info enabled\ [![SR-10671](https://img.shields.io/jira/issue/SR-10671?baseUrl=https%3A%2F%2Fbugs.swift.org&color=success&style=flat-square)](https://bugs.swift.org/browse/SR-10671) - Windows, compiling w/o speculative devirtualization produces unstable binaries\ [![SR-12179](https://img.shields.io/jira/issue/SR-12179?baseUrl=https%3A%2F%2Fbugs.swift.org&color=success&style=flat-square)](https://bugs.swift.org/browse/SR-12179) [![](https://img.shields.io/github/pulls/detail/state/apple/swift-corelibs-foundation/2748?style=flat-square)](https://github.com/apple/swift-corelibs-foundation/pull/2748) - SIL Verification failure with @objc protocol on Windows\ [![SR-13087](https://img.shields.io/jira/issue/SR-13087?baseUrl=https%3A%2F%2Fbugs.swift.org&color=critical&style=flat-square)](https://bugs.swift.org/browse/SR-13087) - Slow compilation with GuaranteedARCOpts\ [![SR-13205](https://img.shields.io/jira/issue/SR-13205?baseUrl=https%3A%2F%2Fbugs.swift.org&color=critical&style=flat-square)](https://bugs.swift.org/browse/SR-13205) - Linker fails with CodeView debug info enabled\ [![SR-13225](https://img.shields.io/jira/issue/SR-13225?baseUrl=https%3A%2F%2Fbugs.swift.org&color=critical&style=flat-square)](https://bugs.swift.org/browse/SR-13225) - Windows, Dispatch crashes after network request timeout\ [![SR-13383](https://img.shields.io/jira/issue/SR-13383?baseUrl=https%3A%2F%2Fbugs.swift.org&color=critical&style=flat-square)](https://bugs.swift.org/browse/SR-13383) - Wrong method call when binary is built with optimizations\ [![SR-13449](https://img.shields.io/jira/issue/SR-13449?baseUrl=https%3A%2F%2Fbugs.swift.org&color=critical&style=flat-square)](https://bugs.swift.org/browse/SR-13449) ## Untracked Issues - Broken synthesis of the CodingKeys\ [![](https://img.shields.io/github/pulls/detail/state/apple/swift/32824?style=flat-square)](https://github.com/apple/swift/pull/32824) <file_sep>class Root {} class Child: Root { func doSomething() { print("-- \(type(of: self)) - \(#function) - will call doHomework()") doHomework() print("-- \(type(of: self)) - \(#function) - did call doHomework()") } private func eatPopcorn() { print("-- \(type(of: self)) - \(#function)") } func playGames() { print("-- \(type(of: self)) - \(#function) - SHOULD NOT HAPPEN") eatPopcorn() } func doHomework() { print("-- \(type(of: self)) - \(#function)") } } Grandchild().doSomething() <file_sep>class Grandchild: Child {} <file_sep>struct S { func f() { let c = { while true { } } print(c) } } <file_sep>import Foundation @objc protocol BadGuy { func mhwahaha() } public class DrEvil: BadGuy { public func mhwahaha() { } } func evilLaughter() { let baddy: BadGuy = DrEvil() baddy.mhwahaha() } <file_sep>import Foundation import FoundationNetworking import XCTest class TestURLDataTask: XCTestCase { func test_timeout() { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 // Value doesn't matter, 8 is just to wait less let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let request = URLRequest(url: URL(string: "http://www.google.com:81")!) // use any host that would time out let callbackCalled = expectation(description: "Task callback called") let task = session.dataTask(with: request, completionHandler: { _, _, _ in callbackCalled.fulfill() }) task.resume() waitForExpectations(timeout: 10) Thread.sleep(forTimeInterval: 5) // as Dispatch crashes asynchronously, give it some time } static var allTests: [(String, (TestURLDataTask) -> () throws -> Void)] { return [ ("test_timeout", test_timeout), ] } } XCTMain([ testCase(TestURLDataTask.allTests), ]) <file_sep>import Foundation class TestClass {} let testObject: Any = [TestClass()] let maybeNumber = testObject as? NSNumber print("Success") <file_sep>public protocol AProto {} public class A: AProto {} public class B { public func foo(_ fooClosure: (_ fooClosureArg: A) -> Void) {} public func bar() { foo { fooClosureArg in baz(bazArg: fooClosureArg) } } private func baz(bazArg: AProto) {} } <file_sep>public func fileExtension(forMime mime: String) -> String? { // Removing .lowercased() fixes the issue. // Compiling with -Xllvm -sil-disable-pass=GuaranteedARCOpts also fixes the issue. switch mime.lowercased() { case "application/andrew-inset": return "ez" case "application/applixware": return "aw" case "application/atom+xml": return "atom" case "application/atomcat+xml": return "atomcat" case "application/atomsvc+xml": return "atomsvc" case "application/ccxml+xml": return "ccxml" case "application/cdmi-capability": return "cdmia" case "application/cdmi-container": return "cdmic" case "application/cdmi-domain": return "cdmid" case "application/cdmi-object": return "cdmio" case "application/cdmi-queue": return "cdmiq" case "application/cu-seeme": return "cu" case "application/davmount+xml": return "davmount" case "application/docbook+xml": return "dbk" case "application/dssc+der": return "dssc" case "application/dssc+xml": return "xdssc" case "application/ecmascript": return "es" case "application/emma+xml": return "emma" case "application/epub+zip": return "epub" case "application/exi": return "exi" case "application/font-tdpfr": return "pfr" case "application/gml+xml": return "gml" case "application/gpx+xml": return "gpx" case "application/gxf": return "gxf" case "application/hyperstudio": return "stk" case "application/inkml+xml": return "ink" case "application/ipfix": return "ipfix" case "application/java-archive": return "jar" case "application/java-serialized-object": return "ser" case "application/java-vm": return "class" case "application/javascript": return "js" case "application/json": return "json" case "application/jsonml+json": return "jsonml" case "application/lost+xml": return "lostxml" case "application/mac-binhex40": return "hqx" case "application/mac-compactpro": return "cpt" case "application/mads+xml": return "mads" case "application/marc": return "mrc" case "application/marcxml+xml": return "mrcx" case "application/mathematica": return "nb" case "application/mathml+xml": return "mathml" case "application/mbox": return "mbox" case "application/mediaservercontrol+xml": return "mscml" case "application/metalink+xml": return "metalink" case "application/metalink4+xml": return "meta4" case "application/mets+xml": return "mets" case "application/mods+xml": return "mods" case "application/mp21": return "m21" case "application/mp4": return "mp4s" case "application/msword": return "doc" case "application/mxf": return "mxf" case "application/octet-stream": return "bin" case "application/oda": return "oda" case "application/oebps-package+xml": return "opf" case "application/ogg": return "ogx" case "application/omdoc+xml": return "omdoc" case "application/onenote": return "one" case "application/oxps": return "oxps" case "application/patch-ops-error+xml": return "xer" case "application/pdf": return "pdf" case "application/pgp-encrypted": return "pgp" case "application/pgp-signature": return "pgp" case "application/pics-rules": return "prf" case "application/pkcs10": return "p10" case "application/pkcs7-mime": return "p7m" case "application/pkcs7-signature": return "p7s" case "application/pkcs8": return "p8" case "application/pkix-attr-cert": return "ac" case "application/pkix-cert": return "cer" case "application/pkix-crl": return "crl" case "application/pkix-pkipath": return "pkipath" case "application/pkixcmp": return "pki" case "application/pls+xml": return "pls" case "application/postscript": return "ps" case "application/prs.cww": return "cww" case "application/pskc+xml": return "pskcxml" case "application/rdf+xml": return "rdf" case "application/reginfo+xml": return "rif" case "application/relax-ng-compact-syntax": return "rnc" case "application/resource-lists+xml": return "rl" case "application/resource-lists-diff+xml": return "rld" case "application/rls-services+xml": return "rs" case "application/rpki-ghostbusters": return "gbr" case "application/rpki-manifest": return "mft" case "application/rpki-roa": return "roa" case "application/rsd+xml": return "rsd" case "application/rss+xml": return "rss" case "application/rtf": return "rtf" case "application/sbml+xml": return "sbml" case "application/scvp-cv-request": return "scq" case "application/scvp-cv-response": return "scs" case "application/scvp-vp-request": return "spq" case "application/scvp-vp-response": return "spp" case "application/sdp": return "sdp" case "application/set-payment-initiation": return "setpay" case "application/set-registration-initiation": return "setreg" case "application/shf+xml": return "shf" case "application/smil+xml": return "smi" case "application/sparql-query": return "rq" case "application/sparql-results+xml": return "srx" case "application/srgs": return "gram" case "application/srgs+xml": return "grxml" case "application/sru+xml": return "sru" case "application/ssdl+xml": return "ssdl" case "application/ssml+xml": return "ssml" case "application/tei+xml": return "tei" case "application/thraud+xml": return "tfi" case "application/timestamped-data": return "tsd" case "application/vnd.3gpp.pic-bw-large": return "plb" case "application/vnd.3gpp.pic-bw-small": return "psb" case "application/vnd.3gpp.pic-bw-var": return "pvb" case "application/vnd.3gpp2.tcap": return "tcap" case "application/vnd.3m.post-it-notes": return "pwn" case "application/vnd.accpac.simply.aso": return "aso" case "application/vnd.accpac.simply.imp": return "imp" case "application/vnd.acucobol": return "acu" case "application/vnd.acucorp": return "atc" case "application/vnd.adobe.air-application-installer-package+zip": return "air" case "application/vnd.adobe.formscentral.fcdt": return "fcdt" case "application/vnd.adobe.fxp": return "fxp" case "application/vnd.adobe.xdp+xml": return "xdp" case "application/vnd.adobe.xfdf": return "xfdf" case "application/vnd.ahead.space": return "ahead" case "application/vnd.airzip.filesecure.azf": return "azf" case "application/vnd.airzip.filesecure.azs": return "azs" case "application/vnd.amazon.ebook": return "azw" case "application/vnd.americandynamics.acc": return "acc" case "application/vnd.amiga.ami": return "ami" case "application/vnd.android.package-archive": return "apk" case "application/vnd.anser-web-certificate-issue-initiation": return "cii" case "application/vnd.anser-web-funds-transfer-initiation": return "fti" case "application/vnd.antix.game-component": return "atx" case "application/vnd.apple.installer+xml": return "mpkg" case "application/vnd.apple.mpegurl": return "m3u8" case "application/vnd.aristanetworks.swi": return "swi" case "application/vnd.astraea-software.iota": return "iota" case "application/vnd.audiograph": return "aep" case "application/vnd.blueice.multipass": return "mpm" case "application/vnd.bmi": return "bmi" case "application/vnd.businessobjects": return "rep" case "application/vnd.chemdraw+xml": return "cdxml" case "application/vnd.chipnuts.karaoke-mmd": return "mmd" case "application/vnd.cinderella": return "cdy" case "application/vnd.claymore": return "cla" case "application/vnd.cloanto.rp9": return "rp9" case "application/vnd.clonk.c4group": return "c4g" case "application/vnd.cluetrust.cartomobile-config": return "c11amc" case "application/vnd.cluetrust.cartomobile-config-pkg": return "c11amz" case "application/vnd.commonspace": return "csp" case "application/vnd.contact.cmsg": return "cdbcmsg" case "application/vnd.cosmocaller": return "cmc" case "application/vnd.crick.clicker": return "clkx" case "application/vnd.crick.clicker.keyboard": return "clkk" case "application/vnd.crick.clicker.palette": return "clkp" case "application/vnd.crick.clicker.template": return "clkt" case "application/vnd.crick.clicker.wordbank": return "clkw" case "application/vnd.criticaltools.wbs+xml": return "wbs" case "application/vnd.ctc-posml": return "pml" case "application/vnd.cups-ppd": return "ppd" case "application/vnd.curl.car": return "car" case "application/vnd.curl.pcurl": return "pcurl" case "application/vnd.dart": return "dart" case "application/vnd.data-vision.rdz": return "rdz" case "application/vnd.dece.data": return "uvf" case "application/vnd.dece.ttml+xml": return "uvt" case "application/vnd.dece.unspecified": return "uvx" case "application/vnd.dece.zip": return "uvz" case "application/vnd.denovo.fcselayout-link": return "fe_launch" case "application/vnd.dna": return "dna" case "application/vnd.dolby.mlp": return "mlp" case "application/vnd.dpgraph": return "dpg" case "application/vnd.dreamfactory": return "dfac" case "application/vnd.ds-keypoint": return "kpxx" case "application/vnd.dvb.ait": return "ait" case "application/vnd.dvb.service": return "svc" case "application/vnd.dynageo": return "geo" case "application/vnd.ecowin.chart": return "mag" case "application/vnd.enliven": return "nml" case "application/vnd.epson.esf": return "esf" case "application/vnd.epson.msf": return "msf" case "application/vnd.epson.quickanime": return "qam" case "application/vnd.epson.salt": return "slt" case "application/vnd.epson.ssf": return "ssf" case "application/vnd.eszigno3+xml": return "es3" case "application/vnd.ezpix-album": return "ez2" case "application/vnd.ezpix-package": return "ez3" case "application/vnd.fdf": return "fdf" case "application/vnd.fdsn.mseed": return "mseed" case "application/vnd.fdsn.seed": return "seed" case "application/vnd.flographit": return "gph" case "application/vnd.fluxtime.clip": return "ftc" case "application/vnd.framemaker": return "fm" case "application/vnd.frogans.fnc": return "fnc" case "application/vnd.frogans.ltf": return "ltf" case "application/vnd.fsc.weblaunch": return "fsc" case "application/vnd.fujitsu.oasys": return "oas" case "application/vnd.fujitsu.oasys2": return "oa2" case "application/vnd.fujitsu.oasys3": return "oa3" case "application/vnd.fujitsu.oasysgp": return "fg5" case "application/vnd.fujitsu.oasysprs": return "bh2" case "application/vnd.fujixerox.ddd": return "ddd" case "application/vnd.fujixerox.docuworks": return "xdw" case "application/vnd.fujixerox.docuworks.binder": return "xbd" case "application/vnd.fuzzysheet": return "fzs" case "application/vnd.genomatix.tuxedo": return "txd" case "application/vnd.geogebra.file": return "ggb" case "application/vnd.geogebra.tool": return "ggt" case "application/vnd.geometry-explorer": return "gex" case "application/vnd.geonext": return "gxt" case "application/vnd.geoplan": return "g2w" case "application/vnd.geospace": return "g3w" case "application/vnd.gmx": return "gmx" case "application/vnd.google-earth.kml+xml": return "kml" case "application/vnd.google-earth.kmz": return "kmz" case "application/vnd.grafeq": return "gqf" case "application/vnd.groove-account": return "gac" case "application/vnd.groove-help": return "ghf" case "application/vnd.groove-identity-message": return "gim" case "application/vnd.groove-injector": return "grv" case "application/vnd.groove-tool-message": return "gtm" case "application/vnd.groove-tool-template": return "tpl" case "application/vnd.groove-vcard": return "vcg" case "application/vnd.hal+xml": return "hal" case "application/vnd.handheld-entertainment+xml": return "zmm" case "application/vnd.hbci": return "hbci" case "application/vnd.hhe.lesson-player": return "les" case "application/vnd.hp-hpgl": return "hpgl" case "application/vnd.hp-hpid": return "hpid" case "application/vnd.hp-hps": return "hps" case "application/vnd.hp-jlyt": return "jlt" case "application/vnd.hp-pcl": return "pcl" case "application/vnd.hp-pclxl": return "pclxl" case "application/vnd.hydrostatix.sof-data": return "sfd-hdstx" case "application/vnd.ibm.minipay": return "mpy" case "application/vnd.ibm.modcap": return "afp" case "application/vnd.ibm.rights-management": return "irm" case "application/vnd.ibm.secure-container": return "sc" case "application/vnd.iccprofile": return "icc" case "application/vnd.igloader": return "igl" case "application/vnd.immervision-ivp": return "ivp" case "application/vnd.immervision-ivu": return "ivu" case "application/vnd.insors.igm": return "igm" case "application/vnd.intercon.formnet": return "xpw" case "application/vnd.intergeo": return "i2g" case "application/vnd.intu.qbo": return "qbo" case "application/vnd.intu.qfx": return "qfx" case "application/vnd.ipunplugged.rcprofile": return "rcprofile" case "application/vnd.irepository.package+xml": return "irp" case "application/vnd.is-xpr": return "xpr" case "application/vnd.isac.fcs": return "fcs" case "application/vnd.jam": return "jam" case "application/vnd.jcp.javame.midlet-rms": return "rms" case "application/vnd.jisp": return "jisp" case "application/vnd.joost.joda-archive": return "joda" case "application/vnd.kahootz": return "ktz" case "application/vnd.kde.karbon": return "karbon" case "application/vnd.kde.kchart": return "chrt" case "application/vnd.kde.kformula": return "kfo" case "application/vnd.kde.kivio": return "flw" case "application/vnd.kde.kontour": return "kon" case "application/vnd.kde.kpresenter": return "kpr" case "application/vnd.kde.kspread": return "ksp" case "application/vnd.kde.kword": return "kwd" case "application/vnd.kenameaapp": return "htke" case "application/vnd.kidspiration": return "kia" case "application/vnd.kinar": return "kne" case "application/vnd.koan": return "skp" case "application/vnd.kodak-descriptor": return "sse" case "application/vnd.las.las+xml": return "lasxml" case "application/vnd.llamagraphics.life-balance.desktop": return "lbd" case "application/vnd.llamagraphics.life-balance.exchange+xml": return "lbe" case "application/vnd.lotus-1-2-3": return "123" case "application/vnd.lotus-approach": return "apr" case "application/vnd.lotus-freelance": return "pre" case "application/vnd.lotus-notes": return "nsf" case "application/vnd.lotus-organizer": return "org" case "application/vnd.lotus-screencam": return "scm" case "application/vnd.lotus-wordpro": return "lwp" case "application/vnd.macports.portpkg": return "portpkg" case "application/vnd.mcd": return "mcd" case "application/vnd.medcalcdata": return "mc1" case "application/vnd.mediastation.cdkey": return "cdkey" case "application/vnd.mfer": return "mwf" case "application/vnd.mfmp": return "mfm" case "application/vnd.micrografx.flo": return "flo" case "application/vnd.micrografx.igx": return "igx" case "application/vnd.mif": return "mif" case "application/vnd.mobius.daf": return "daf" case "application/vnd.mobius.dis": return "dis" case "application/vnd.mobius.mbk": return "mbk" case "application/vnd.mobius.mqy": return "mqy" case "application/vnd.mobius.msl": return "msl" case "application/vnd.mobius.plc": return "plc" case "application/vnd.mobius.txf": return "txf" case "application/vnd.mophun.application": return "mpn" case "application/vnd.mophun.certificate": return "mpc" case "application/vnd.mozilla.xul+xml": return "xul" case "application/vnd.ms-artgalry": return "cil" case "application/vnd.ms-cab-compressed": return "cab" case "application/vnd.ms-excel": return "xls" case "application/vnd.ms-excel.addin.macroenabled.12": return "xlam" case "application/vnd.ms-excel.sheet.binary.macroenabled.12": return "xlsb" case "application/vnd.ms-excel.sheet.macroenabled.12": return "xlsm" case "application/vnd.ms-excel.template.macroenabled.12": return "xltm" case "application/vnd.ms-fontobject": return "eot" case "application/vnd.ms-htmlhelp": return "chm" case "application/vnd.ms-ims": return "ims" case "application/vnd.ms-lrm": return "lrm" case "application/vnd.ms-officetheme": return "thmx" case "application/vnd.ms-pki.seccat": return "cat" case "application/vnd.ms-pki.stl": return "stl" case "application/vnd.ms-powerpoint": return "pot" case "application/vnd.ms-powerpoint.addin.macroenabled.12": return "ppam" case "application/vnd.ms-powerpoint.presentation.macroenabled.12": return "pptm" case "application/vnd.ms-powerpoint.slide.macroenabled.12": return "sldm" case "application/vnd.ms-powerpoint.slideshow.macroenabled.12": return "ppsm" case "application/vnd.ms-powerpoint.template.macroenabled.12": return "potm" case "application/vnd.ms-project": return "mpp" case "application/vnd.ms-word.document.macroenabled.12": return "docm" case "application/vnd.ms-word.template.macroenabled.12": return "dotm" case "application/vnd.ms-works": return "wps" case "application/vnd.ms-wpl": return "wpl" case "application/vnd.ms-xpsdocument": return "xps" case "application/vnd.mseq": return "mseq" case "application/vnd.musician": return "mus" case "application/vnd.muvee.style": return "msty" case "application/vnd.mynfc": return "taglet" case "application/vnd.neurolanguage.nlu": return "nlu" case "application/vnd.nitf": return "ntf" case "application/vnd.noblenet-directory": return "nnd" case "application/vnd.noblenet-sealer": return "nns" case "application/vnd.noblenet-web": return "nnw" case "application/vnd.nokia.n-gage.data": return "ngdat" case "application/vnd.nokia.n-gage.symbian.install": return "n-gage" case "application/vnd.nokia.radio-preset": return "rpst" case "application/vnd.nokia.radio-presets": return "rpss" case "application/vnd.novadigm.edm": return "edm" case "application/vnd.novadigm.edx": return "edx" case "application/vnd.novadigm.ext": return "ext" case "application/vnd.oasis.opendocument.chart": return "odc" case "application/vnd.oasis.opendocument.chart-template": return "otc" case "application/vnd.oasis.opendocument.database": return "odb" case "application/vnd.oasis.opendocument.formula": return "odf" case "application/vnd.oasis.opendocument.formula-template": return "odft" case "application/vnd.oasis.opendocument.graphics": return "odg" case "application/vnd.oasis.opendocument.graphics-template": return "otg" case "application/vnd.oasis.opendocument.image": return "odi" case "application/vnd.oasis.opendocument.image-template": return "oti" case "application/vnd.oasis.opendocument.presentation": return "odp" case "application/vnd.oasis.opendocument.presentation-template": return "otp" case "application/vnd.oasis.opendocument.spreadsheet": return "ods" case "application/vnd.oasis.opendocument.spreadsheet-template": return "ots" case "application/vnd.oasis.opendocument.text": return "odt" case "application/vnd.oasis.opendocument.text-master": return "odm" case "application/vnd.oasis.opendocument.text-template": return "ott" case "application/vnd.oasis.opendocument.text-web": return "oth" case "application/vnd.olpc-sugar": return "xo" case "application/vnd.oma.dd2+xml": return "dd2" case "application/vnd.openofficeorg.extension": return "oxt" case "application/vnd.openxmlformats-officedocument.presentationml.presentation": return "pptx" case "application/vnd.openxmlformats-officedocument.presentationml.slide": return "sldx" case "application/vnd.openxmlformats-officedocument.presentationml.slideshow": return "ppsx" case "application/vnd.openxmlformats-officedocument.presentationml.template": return "potx" case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": return "xlsx" case "application/vnd.openxmlformats-officedocument.spreadsheetml.template": return "xltx" case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": return "docx" case "application/vnd.openxmlformats-officedocument.wordprocessingml.template": return "dotx" case "application/vnd.osgeo.mapguide.package": return "mgp" case "application/vnd.osgi.dp": return "dp" case "application/vnd.osgi.subsystem": return "esa" case "application/vnd.palm": return "pdb" case "application/vnd.pawaafile": return "paw" case "application/vnd.pg.format": return "str" case "application/vnd.pg.osasli": return "ei6" case "application/vnd.picsel": return "efif" case "application/vnd.pmi.widget": return "wg" case "application/vnd.pocketlearn": return "plf" case "application/vnd.powerbuilder6": return "pbd" case "application/vnd.previewsystems.box": return "box" case "application/vnd.proteus.magazine": return "mgz" case "application/vnd.publishare-delta-tree": return "qps" case "application/vnd.pvi.ptid1": return "ptid" case "application/vnd.quark.quarkxpress": return "qxd" case "application/vnd.realvnc.bed": return "bed" case "application/vnd.recordare.musicxml": return "mxl" case "application/vnd.recordare.musicxml+xml": return "musicxml" case "application/vnd.rig.cryptonote": return "cryptonote" case "application/vnd.rim.cod": return "cod" case "application/vnd.rn-realmedia": return "rm" case "application/vnd.rn-realmedia-vbr": return "rmvb" case "application/vnd.route66.link66+xml": return "link66" case "application/vnd.sailingtracker.track": return "st" case "application/vnd.seemail": return "see" case "application/vnd.sema": return "sema" case "application/vnd.semd": return "semd" case "application/vnd.semf": return "semf" case "application/vnd.shana.informed.formdata": return "ifm" case "application/vnd.shana.informed.formtemplate": return "itp" case "application/vnd.shana.informed.interchange": return "iif" case "application/vnd.shana.informed.package": return "ipk" case "application/vnd.simtech-mindmapper": return "twd" case "application/vnd.smaf": return "mmf" case "application/vnd.smart.teacher": return "teacher" case "application/vnd.solent.sdkm+xml": return "sdkm" case "application/vnd.spotfire.dxp": return "dxp" case "application/vnd.spotfire.sfs": return "sfs" case "application/vnd.stardivision.calc": return "sdc" case "application/vnd.stardivision.draw": return "sda" case "application/vnd.stardivision.impress": return "sdp" case "application/vnd.stardivision.math": return "sdf" case "application/vnd.stardivision.writer": return "vor" case "application/vnd.stardivision.writer-global": return "sgl" case "application/vnd.stepmania.package": return "smzip" case "application/vnd.stepmania.stepchart": return "sm" case "application/vnd.sun.xml.calc": return "sxc" case "application/vnd.sun.xml.calc.template": return "stc" case "application/vnd.sun.xml.draw": return "sxd" case "application/vnd.sun.xml.draw.template": return "std" case "application/vnd.sun.xml.impress": return "sxi" case "application/vnd.sun.xml.impress.template": return "sti" case "application/vnd.sun.xml.math": return "sxm" case "application/vnd.sun.xml.writer": return "sxw" case "application/vnd.sun.xml.writer.global": return "sxg" case "application/vnd.sun.xml.writer.template": return "stw" case "application/vnd.sus-calendar": return "sus" case "application/vnd.svd": return "svd" case "application/vnd.symbian.install": return "sis" case "application/vnd.syncml+xml": return "xsm" case "application/vnd.syncml.dm+wbxml": return "bdm" case "application/vnd.syncml.dm+xml": return "xdm" case "application/vnd.tao.intent-module-archive": return "tao" case "application/vnd.tcpdump.pcap": return "cap" case "application/vnd.tmobile-livetv": return "tmo" case "application/vnd.trid.tpt": return "tpt" case "application/vnd.triscape.mxs": return "mxs" case "application/vnd.trueapp": return "tra" case "application/vnd.ufdl": return "ufd" case "application/vnd.uiq.theme": return "utz" case "application/vnd.umajin": return "umj" case "application/vnd.unity": return "unityweb" case "application/vnd.uoml+xml": return "uoml" case "application/vnd.vcx": return "vcx" case "application/vnd.visio": return "vsd" case "application/vnd.visionary": return "vis" case "application/vnd.vsf": return "vsf" case "application/vnd.wap.wbxml": return "wbxml" case "application/vnd.wap.wmlc": return "wmlc" case "application/vnd.wap.wmlscriptc": return "wmlsc" case "application/vnd.webturbo": return "wtb" case "application/vnd.wolfram.player": return "nbp" case "application/vnd.wordperfect": return "wpd" case "application/vnd.wqd": return "wqd" case "application/vnd.wt.stf": return "stf" case "application/vnd.xara": return "xar" case "application/vnd.xfdl": return "xfdl" case "application/vnd.yamaha.hv-dic": return "hvd" case "application/vnd.yamaha.hv-script": return "hvs" case "application/vnd.yamaha.hv-voice": return "hvp" case "application/vnd.yamaha.openscoreformat": return "osf" case "application/vnd.yamaha.openscoreformat.osfpvg+xml": return "osfpvg" case "application/vnd.yamaha.smaf-audio": return "saf" case "application/vnd.yamaha.smaf-phrase": return "spf" case "application/vnd.yellowriver-custom-menu": return "cmp" case "application/vnd.zul": return "zir" case "application/vnd.zzazz.deck+xml": return "zaz" case "application/voicexml+xml": return "vxml" case "application/widget": return "wgt" case "application/winhlp": return "hlp" case "application/wsdl+xml": return "wsdl" case "application/wspolicy+xml": return "wspolicy" case "application/x-7z-compressed": return "7z" case "application/x-abiword": return "abw" case "application/x-ace-compressed": return "ace" case "application/x-apple-diskimage": return "dmg" case "application/x-authorware-bin": return "aab" case "application/x-authorware-map": return "aam" case "application/x-authorware-seg": return "aas" case "application/x-bcpio": return "bcpio" case "application/x-bittorrent": return "torrent" case "application/x-blorb": return "blb" case "application/x-bzip": return "bz" case "application/x-bzip2": return "bz2" case "application/x-cbr": return "cbr" case "application/x-cdlink": return "vcd" case "application/x-cfs-compressed": return "cfs" case "application/x-chat": return "chat" case "application/x-chess-pgn": return "pgn" case "application/x-conference": return "nsc" case "application/x-cpio": return "cpio" case "application/x-csh": return "csh" case "application/x-debian-package": return "deb" case "application/x-dgc-compressed": return "dgc" case "application/x-director": return "dcr" case "application/x-doom": return "wad" case "application/x-dtbncx+xml": return "ncx" case "application/x-dtbook+xml": return "dtb" case "application/x-dtbresource+xml": return "res" case "application/x-dvi": return "dvi" case "application/x-envoy": return "evy" case "application/x-eva": return "eva" case "application/x-font-bdf": return "bdf" case "application/x-font-ghostscript": return "gsf" case "application/x-font-linux-psf": return "psf" case "application/x-font-pcf": return "pcf" case "application/x-font-snf": return "snf" case "application/x-font-type1": return "pfa" case "application/x-freearc": return "arc" case "application/x-futuresplash": return "spl" case "application/x-gca-compressed": return "gca" case "application/x-glulx": return "ulx" case "application/x-gnumeric": return "gnumeric" case "application/x-gramps-xml": return "gramps" case "application/x-gtar": return "gtar" case "application/x-hdf": return "hdf" case "application/x-install-instructions": return "install" case "application/x-iso9660-image": return "iso" case "application/x-java-jnlp-file": return "jnlp" case "application/x-latex": return "latex" case "application/x-lzh-compressed": return "lzh" case "application/x-mie": return "mie" case "application/x-mobipocket-ebook": return "prc" case "application/x-ms-application": return "application" case "application/x-ms-shortcut": return "lnk" case "application/x-ms-wmd": return "wmd" case "application/x-ms-wmz": return "wmz" case "application/x-ms-xbap": return "xbap" case "application/x-msaccess": return "mdb" case "application/x-msbinder": return "obd" case "application/x-mscardfile": return "crd" case "application/x-msclip": return "clp" case "application/x-msdownload": return "exe" case "application/x-msmediaview": return "mvb" case "application/x-msmetafile": return "wmf" case "application/x-msmoney": return "mny" case "application/x-mspublisher": return "pub" case "application/x-msschedule": return "scd" case "application/x-msterminal": return "trm" case "application/x-mswrite": return "wri" case "application/x-netcdf": return "nc" case "application/x-nzb": return "nzb" case "application/x-pkcs12": return "p12" case "application/x-pkcs7-certificates": return "p7b" case "application/x-pkcs7-certreqresp": return "p7r" case "application/x-rar-compressed": return "rar" case "application/x-research-info-systems": return "ris" case "application/x-sh": return "sh" case "application/x-shar": return "shar" case "application/x-shockwave-flash": return "swf" case "application/x-silverlight-app": return "xap" case "application/x-sql": return "sql" case "application/x-stuffit": return "sit" case "application/x-stuffitx": return "sitx" case "application/x-subrip": return "srt" case "application/x-sv4cpio": return "sv4cpio" case "application/x-sv4crc": return "sv4crc" case "application/x-t3vm-image": return "t3" case "application/x-tads": return "gam" case "application/x-tar": return "tar" case "application/x-tcl": return "tcl" case "application/x-tex": return "tex" case "application/x-tex-tfm": return "tfm" case "application/x-texinfo": return "texinfo" case "application/x-tgif": return "obj" case "application/x-ustar": return "ustar" case "application/x-wais-source": return "src" case "application/x-x509-ca-cert": return "crt" case "application/x-xfig": return "fig" case "application/x-xliff+xml": return "xlf" case "application/x-xpinstall": return "xpi" case "application/x-xz": return "xz" case "application/x-zmachine": return "z1" case "application/xaml+xml": return "xaml" case "application/xcap-diff+xml": return "xdf" case "application/xenc+xml": return "xenc" case "application/xhtml+xml": return "xhtml" case "application/xml": return "xml" case "application/xml-dtd": return "dtd" case "application/xop+xml": return "xop" case "application/xproc+xml": return "xpl" case "application/xslt+xml": return "xsl" case "application/xspf+xml": return "xspf" case "application/xv+xml": return "mxml" case "application/yang": return "yang" case "application/yin+xml": return "yin" case "application/zip": return "zip" case "audio/adpcm": return "adp" case "audio/basic": return "snd" case "audio/midi": return "rtx" case "audio/mp4": return "m4a" case "audio/mpeg": return "mp3" case "audio/ogg": return "oga" case "audio/s3m": return "s3m" case "audio/silk": return "sil" case "audio/vnd.dece.audio": return "uva" case "audio/vnd.digital-winds": return "eol" case "audio/vnd.dra": return "dra" case "audio/vnd.dts": return "dts" case "audio/vnd.dts.hd": return "dtshd" case "audio/vnd.lucent.voice": return "lvp" case "audio/vnd.ms-playready.media.pya": return "pya" case "audio/vnd.nuera.ecelp4800": return "ecelp4800" case "audio/vnd.nuera.ecelp7470": return "ecelp7470" case "audio/vnd.nuera.ecelp9600": return "ecelp9600" case "audio/vnd.rip": return "rip" case "audio/webm": return "weba" case "audio/x-aac": return "aac" case "audio/x-aiff": return "aif" case "audio/x-caf": return "caf" case "audio/x-flac": return "flac" case "audio/x-matroska": return "mka" case "audio/x-mpegurl": return "m3u" case "audio/x-ms-wax": return "wax" case "audio/x-ms-wma": return "wma" case "audio/x-pn-realaudio": return "ra" case "audio/x-pn-realaudio-plugin": return "rmp" case "audio/x-wav": return "wav" case "audio/xm": return "xm" case "chemical/x-cdx": return "cdx" case "chemical/x-cif": return "cif" case "chemical/x-cmdf": return "cmdf" case "chemical/x-cml": return "cml" case "chemical/x-csml": return "csml" case "chemical/x-xyz": return "xyz" case "font/collection": return "ttc" case "font/otf": return "ttf" case "font/ttf": return "ttf" case "font/woff": return "woff" case "font/woff2": return "woff2" case "image/bmp": return "bmp" case "image/cgm": return "cgm" case "image/g3fax": return "g3" case "image/gif": return "gif" case "image/ief": return "ief" case "image/jpeg": return "jpg" case "image/ktx": return "ktx" case "image/png": return "png" case "image/prs.btif": return "btif" case "image/sgi": return "sgi" case "image/svg+xml": return "svg" case "image/tiff": return "tiff" case "image/vnd.adobe.photoshop": return "psd" case "image/vnd.dece.graphic": return "uvi" case "image/vnd.djvu": return "djvu" case "image/vnd.dvb.subtitle": return "sub" case "image/vnd.dwg": return "dwg" case "image/vnd.dxf": return "dxf" case "image/vnd.fastbidsheet": return "fbs" case "image/vnd.fpx": return "fpx" case "image/vnd.fst": return "fst" case "image/vnd.fujixerox.edmics-mmr": return "mmr" case "image/vnd.fujixerox.edmics-rlc": return "rlc" case "image/vnd.ms-modi": return "mdi" case "image/vnd.ms-photo": return "wdp" case "image/vnd.net-fpx": return "npx" case "image/vnd.wap.wbmp": return "wbmp" case "image/vnd.xiff": return "xif" case "image/webp": return "webp" case "image/x-3ds": return "3ds" case "image/x-cmu-raster": return "ras" case "image/x-cmx": return "cmx" case "image/x-freehand": return "fh" case "image/x-icon": return "ico" case "image/x-mrsid-image": return "sid" case "image/x-pcx": return "pcx" case "image/x-pict": return "pic" case "image/x-portable-anymap": return "pnm" case "image/x-portable-bitmap": return "pbm" case "image/x-portable-graymap": return "pgm" case "image/x-portable-pixmap": return "ppm" case "image/x-rgb": return "rgb" case "image/x-tga": return "tga" case "image/x-xbitmap": return "xbm" case "image/x-xpixmap": return "xpm" case "image/x-xwindowdump": return "xwd" case "message/rfc822": return "eml" case "model/iges": return "igs" case "model/mesh": return "msh" case "model/vnd.collada+xml": return "dae" case "model/vnd.dwf": return "dwf" case "model/vnd.gdl": return "gdl" case "model/vnd.gtw": return "gtw" case "model/vnd.mts": return "mts" case "model/vnd.vtu": return "vtu" case "model/vrml": return "wrl" case "model/x3d+binary": return "x3db" case "model/x3d+vrml": return "x3dv" case "model/x3d+xml": return "x3d" case "text/cache-manifest": return "appcache" case "text/calendar": return "ics" case "text/css": return "css" case "text/csv": return "csv" case "text/html": return "html" case "text/n3": return "n3" case "text/plain": return "txt" case "text/prs.lines.tag": return "dsc" case "text/richtext": return "rtx" case "text/sgml": return "sgml" case "text/tab-separated-values": return "tsv" case "text/troff": return "t" case "text/turtle": return "ttl" case "text/uri-list": return "uri" case "text/vcard": return "vcf" case "text/vnd.curl": return "curl" case "text/vnd.curl.dcurl": return "dcurl" case "text/vnd.curl.mcurl": return "mcurl" case "text/vnd.curl.scurl": return "scurl" case "text/vnd.dvb.subtitle": return "sub" case "text/vnd.fly": return "fly" case "text/vnd.fmi.flexstor": return "flx" case "text/vnd.graphviz": return "gv" case "text/vnd.in3d.3dml": return "3dml" case "text/vnd.in3d.spot": return "spot" case "text/vnd.sun.j2me.app-descriptor": return "jad" case "text/vnd.wap.wml": return "wml" case "text/vnd.wap.wmlscript": return "wmls" case "text/x-asm": return "s" case "text/x-c": return "c" case "text/x-fortran": return "f" case "text/x-java-source": return "java" case "text/x-nfo": return "nfo" case "text/x-opml": return "opml" case "text/x-pascal": return "p" case "text/x-setext": return "etx" case "text/x-sfv": return "sfv" case "text/x-uuencode": return "uu" case "text/x-vcalendar": return "vcs" case "text/x-vcard": return "vcf" case "video/3gpp": return "3gpp" case "video/3gpp2": return "3gpp2" case "video/h261": return "h261" case "video/h263": return "h263" case "video/h264": return "h264" case "video/jpeg": return "jpgv" case "video/jpm": return "jpm" case "video/mj2": return "mj2" case "video/mp4": return "mp4" case "video/mpeg": return "mpeg" case "video/ogg": return "ogv" case "video/quicktime": return "mov" case "video/vnd.dece.hd": return "uvh" case "video/vnd.dece.mobile": return "uvm" case "video/vnd.dece.pd": return "uvp" case "video/vnd.dece.sd": return "uvs" case "video/vnd.dece.video": return "uvv" case "video/vnd.dvb.file": return "dvb" case "video/vnd.fvt": return "fvt" case "video/vnd.mpegurl": return "mxu" case "video/vnd.ms-playready.media.pyv": return "pyv" case "video/vnd.uvvu.mp4": return "uvu" case "video/vnd.vivo": return "viv" case "video/webm": return "webm" case "video/x-f4v": return "f4v" case "video/x-fli": return "fli" case "video/x-flv": return "flv" case "video/x-m4v": return "m4v" case "video/x-matroska": return "mkv" case "video/x-mng": return "mng" case "video/x-ms-asf": return "asf" case "video/x-ms-vob": return "vob" case "video/x-ms-wm": return "wm" case "video/x-ms-wmv": return "wmv" case "video/x-ms-wmx": return "wmx" case "video/x-ms-wvx": return "wvx" case "video/x-msvideo": return "avi" case "video/x-sgi-movie": return "movie" case "video/x-smv": return "smv" case "x-conference/x-cooltalk": return "ice" case "application/annodex": return "anx" case "application/atomserv+xml": return "atomsrv" case "application/bbolin": return "lin" case "application/dicom": return "dcm" case "application/dsptype": return "tsp" case "application/font-sfnt": return "otf" case "application/font-woff": return "woff" case "application/futuresplash": return "spl" case "application/gzip": return "gz" case "application/hta": return "hta" case "application/m3g": return "m3g" case "application/msaccess": return "mdb" case "application/pgp-keys": return "key" case "application/rar": return "rar" case "application/sla": return "stl" case "application/vnd.debian.binary-package": return "deb" case "application/vnd.font-fontforge-sfd": return "sfd" case "application/vnd.stardivision.chart": return "sds" case "application/vnd.wordperfect5.1": return "wp5" case "application/x-123": return "wk" case "application/x-cab": return "cab" case "application/x-cbz": return "cbz" case "application/x-cdf": return "cdf" case "application/x-comsol": return "mph" case "application/x-dms": return "dms" case "application/x-font": return "pcf" case "application/x-freemind": return "mm" case "application/x-ganttproject": return "gan" case "application/x-go-sgf": return "sgf" case "application/x-graphing-calculator": return "gcf" case "application/x-gtar-compressed": return "tgz" case "application/x-hwp": return "hwp" case "application/x-ica": return "ica" case "application/x-info": return "info" case "application/x-internet-signup": return "ins" case "application/x-iphone": return "iii" case "application/x-jam": return "jam" case "application/x-jmol": return "jmz" case "application/x-kchart": return "chrt" case "application/x-killustrator": return "kil" case "application/x-koan": return "skp" case "application/x-kpresenter": return "kpr" case "application/x-kspread": return "ksp" case "application/x-kword": return "kwd" case "application/x-lha": return "lha" case "application/x-lyx": return "lyx" case "application/x-lzh": return "lzh" case "application/x-lzx": return "lzx" case "application/x-maker": return "frm" case "application/x-mif": return "mif" case "application/x-mpegurl": return "m3u" case "application/x-ms-manifest": return "manifest" case "application/x-msdos-program": return "com" case "application/x-msi": return "msi" case "application/x-ns-proxy-autoconfig": return "pac" case "application/x-nwc": return "nwc" case "application/x-object": return "o" case "application/x-oz-application": return "oza" case "application/x-pkcs7-crl": return "crl" case "application/x-python-code": return "pyc" case "application/x-qgis": return "qgs" case "application/x-quicktimeplayer": return "qtl" case "application/x-rdp": return "rdp" case "application/x-redhat-package-manager": return "rpm" case "application/x-rss+xml": return "rss" case "application/x-ruby": return "rb" case "application/x-scilab": return "sci" case "application/x-scilab-xcos": return "xcos" case "application/x-silverlight": return "scr" case "application/x-tex-gf": return "gf" case "application/x-tex-pk": return "pk" case "application/x-trash": return "~" case "application/x-troff": return "t" case "application/x-troff-man": return "man" case "application/x-troff-me": return "me" case "application/x-troff-ms": return "ms" case "application/x-wingz": return "wz" case "application/x-xcf": return "xcf" case "audio/amr": return "amr" case "audio/amr-wb": return "awb" case "audio/annodex": return "axa" case "audio/csound": return "csd" case "audio/flac": return "flac" case "audio/mpegurl": return "m3u" case "audio/prs.sid": return "sid" case "audio/x-gsm": return "gsm" case "audio/x-realaudio": return "ra" case "audio/x-scpls": return "pls" case "audio/x-sd2": return "sd2" case "chemical/x-alchemy": return "alc" case "chemical/x-cache": return "cac" case "chemical/x-cache-csf": return "csf" case "chemical/x-cactvs-binary": return "cbin" case "chemical/x-cerius": return "cer" case "chemical/x-chem3d": return "c3d" case "chemical/x-chemdraw": return "chm" case "chemical/x-compass": return "cpa" case "chemical/x-crossfire": return "bsd" case "chemical/x-ctx": return "ctx" case "chemical/x-cxf": return "cxf" case "chemical/x-embl-dl-nucleotide": return "emb" case "chemical/x-galactic-spc": return "spc" case "chemical/x-gamess-input": return "inp" case "chemical/x-gaussian-checkpoint": return "fch" case "chemical/x-gaussian-cube": return "cub" case "chemical/x-gaussian-input": return "gau" case "chemical/x-gaussian-log": return "gal" case "chemical/x-gcg8-sequence": return "gcg" case "chemical/x-genbank": return "gen" case "chemical/x-hin": return "hin" case "chemical/x-isostar": return "istr" case "chemical/x-jcamp-dx": return "jdx" case "chemical/x-kinemage": return "kin" case "chemical/x-macmolecule": return "mcm" case "chemical/x-macromodel-input": return "mmd" case "chemical/x-mdl-molfile": return "mol" case "chemical/x-mdl-rdfile": return "rd" case "chemical/x-mdl-rxnfile": return "rxn" case "chemical/x-mdl-sdfile": return "sd" case "chemical/x-mdl-tgf": return "tgf" case "chemical/x-mmcif": return "mcif" case "chemical/x-mol2": return "mol2" case "chemical/x-molconn-z": return "b" case "chemical/x-mopac-graph": return "gpt" case "chemical/x-mopac-input": return "mop" case "chemical/x-mopac-out": return "moo" case "chemical/x-mopac-vib": return "mvb" case "chemical/x-ncbi-asn1": return "asn" case "chemical/x-ncbi-asn1-ascii": return "prt" case "chemical/x-ncbi-asn1-binary": return "val" case "chemical/x-ncbi-asn1-spec": return "asn" case "chemical/x-pdb": return "pdb" case "chemical/x-rosdal": return "ros" case "chemical/x-swissprot": return "sw" case "chemical/x-vamas-iso14976": return "vms" case "chemical/x-vmd": return "vmd" case "chemical/x-xtel": return "xtel" case "font/sfnt": return "ttf" case "image/jp2": return "jp2" case "image/jpm": return "jpm" case "image/jpx": return "jpx" case "image/pcx": return "pcx" case "image/vnd.microsoft.icon": return "ico" case "image/x-canon-cr2": return "cr2" case "image/x-canon-crw": return "crw" case "image/x-coreldraw": return "cdr" case "image/x-coreldrawpattern": return "pat" case "image/x-coreldrawtemplate": return "cdt" case "image/x-corelphotopaint": return "cpt" case "image/x-epson-erf": return "erf" case "image/x-jg": return "art" case "image/x-jng": return "jng" case "image/x-ms-bmp": return "bmp" case "image/x-nikon-nef": return "nef" case "image/x-olympus-orf": return "orf" case "image/x-photoshop": return "psd" case "text/h323": return "323" case "text/iuls": return "uls" case "text/mathml": return "mml" case "text/markdown": return "md" case "text/scriptlet": return "sct" case "text/texmacs": return "tm" case "text/x-bibtex": return "bib" case "text/x-boo": return "boo" case "text/x-c++hdr": return "hpp" case "text/x-c++src": return "cpp" case "text/x-chdr": return "h" case "text/x-component": return "htc" case "text/x-csh": return "csh" case "text/x-csrc": return "c" case "text/x-dsrc": return "d" case "text/x-diff": return "diff" case "text/x-haskell": return "hs" case "text/x-java": return "java" case "text/x-lilypond": return "ly" case "text/x-literate-haskell": return "lhs" case "text/x-moc": return "moc" case "text/x-pcs-gcd": return "gcd" case "text/x-perl": return "pl" case "text/x-python": return "py" case "text/x-scala": return "scala" case "text/x-sh": return "sh" case "text/x-tcl": return "tcl" case "text/x-tex": return "tex" case "video/annodex": return "axv" case "video/dl": return "dl" case "video/dv": return "dif" case "video/fli": return "fli" case "video/gl": return "gl" case "video/mp2t": return "ts" case "video/x-la-asf": return "lsf" case "x-epoc/x-sisx-app": return "sisx" case "x-world/x-vrml": return "vrm" case "application/vnd.youtube.yt": return "yt" case "application/x-android-drm-fl": return "fl" case "application/x-flac": return "flac" case "application/x-pem-file": return "pem" case "application/x-webarchive": return "webarchive" case "application/x-webarchive-xml": return "webarchivexml" case "application/x-x509-server-cert": return "crt" case "application/x-x509-user-cert": return "crt" case "audio/3gpp": return "3gpp" case "audio/aac-adts": return "aac" case "audio/imelody": return "imy" case "audio/mobile-xmf": return "mxmf" case "audio/sp-midi": return "smf" case "image/heic": return "heic" case "image/heic-sequence": return "heics" case "image/heif": return "heif" case "image/heif-sequence": return "heifs" case "image/ico": return "cur" case "image/x-adobe-dng": return "dng" case "image/x-fuji-raf": return "raf" case "image/x-nikon-nrw": return "nrw" case "image/x-panasonic-rw2": return "rw2" case "image/x-pentax-pef": return "pef" case "image/x-samsung-srw": return "srw" case "image/x-sony-arw": return "arw" case "text/comma-separated-values": return "csv" case "text/rtf": return "rtf" case "text/text": return "phps" case "text/xml": return "xml" case "video/avi": return "avi" case "video/m4v": return "m4v" case "video/mp2p": return "mpeg" case "video/mp2ts": return "ts" case "video/x-webex": return "wrf" case "audio/aac": return "aac" default: return nil } } <file_sep>public class SomeClass { } extension SomeClass: Encodable { } <file_sep>func foo() { func closureStub(a: Int) { var b = a b = b + 1 } let x: (Int) -> Void = { (a: Int) in closureStub(a: a) } }
e6243c01aca84698bfcb870724fb0392e162b878
[ "Markdown", "Swift" ]
11
Markdown
readdle/swift-issues
a63d9c84d4816a6a439f87b16d354aeb1b5db315
9fac8b1759687ae91e83c949974d8b138c661d78
refs/heads/master
<repo_name>ericpinera/consulmed<file_sep>/citas/migrations/0003_cita_paciente.py # Generated by Django 2.0.7 on 2019-08-05 21:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pacientes', '0004_auto_20190805_1615'), ('citas', '0002_auto_20190805_1629'), ] operations = [ migrations.AddField( model_name='cita', name='paciente', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='pacientes.Paciente'), ), ] <file_sep>/citas/models.py from django.db import models from pacientes.models import Paciente # Create your models here. class Cita(models.Model): horario_opciones = ( ('turno_1', '8:00 - 9:00'), ('turno_2', '9:00 - 10:00'), ('turno_3', '10:00 - 11:00'), ('turno_4', '11:00 - 12:00'), ('turno_5', '12:00 - 13:00'), ('turno_6', '13:00 - 14:00'), ('turno_7', '14:00 - 15:00'), ('turno_8', '15:00 - 16:00'), ('turno_9', ' 16:00 - 17:00'), ('turno_10', '17:00 - 18:00'), ('turno_11', '18:00 - 19:00'), ('turno_12', '19:00 - 20:00'), ('turno_13', '20:00 - 21:00'), ('turno_14', ' 21:00 - 22:00') ) estado_opciones = ( ('pendiente', 'Pendiente'), ('finalizada', 'Finalizada'), ('anulada', 'Anulada') ) fecha = models.DateField('Fecha', auto_now_add=False) horario = models.CharField('Horario', max_length=20, choices = horario_opciones, default="Seleccionar") estado = models.CharField('Estado', max_length=20, choices = estado_opciones, default='pendiente') paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, null=True) <file_sep>/pacientes/models.py from django.db import models # Create your models here. class Paciente(models.Model): tipo_identificacion_opciones = ( ('cedula', 'Cédula'), ('pasaporte', 'Pasaporte') ) sexo_opciones = ( ('masculino', 'Masculino'), ('femenino', 'Femenino'), ('otro', 'Otro') ) primerNombre = models.CharField('Primer nombre', max_length=250) segundoNombre = models.CharField('Segundo nombre', max_length=250) primerApellido = models.CharField('Primer apellido', max_length=250) segundoApellido = models.CharField('Segundo apellido', max_length=250) tipo_identificacion = models.CharField('Tipo identificacion', max_length=20, choices = tipo_identificacion_opciones, default='cedula') identificacion = models.CharField('Identificación', max_length=50, null=True) sexo = models.CharField('Sexo', max_length=20, choices = sexo_opciones, default='femenino') direccion = models.TextField('Dirección', null=True) telefono = models.CharField('Teléfono', max_length=100, null=True) correo = models.EmailField('Email', null=True) <file_sep>/pacientes/migrations/0003_auto_20190805_1532.py # Generated by Django 2.0.7 on 2019-08-05 20:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pacientes', '0002_auto_20190805_1241'), ] operations = [ migrations.AddField( model_name='paciente', name='correo', field=models.CharField(max_length=200, null=True, verbose_name='Email'), ), migrations.AddField( model_name='paciente', name='direccion', field=models.TextField(null=True, verbose_name='Dirección'), ), migrations.AddField( model_name='paciente', name='identificacion', field=models.CharField(max_length=50, null=True, verbose_name='Identificación'), ), migrations.AddField( model_name='paciente', name='sexo', field=models.CharField(choices=[('masculino', 'Masculino'), ('femenino', 'Femenino'), ('otro', 'Otro')], default='femenino', max_length=20, verbose_name='Sexo'), ), migrations.AddField( model_name='paciente', name='telefono', field=models.CharField(max_length=100, null=True, verbose_name='Teléfono'), ), ] <file_sep>/citas/migrations/0002_auto_20190805_1629.py # Generated by Django 2.0.7 on 2019-08-05 21:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('citas', '0001_initial'), ] operations = [ migrations.AddField( model_name='cita', name='estado', field=models.CharField(choices=[('pendiente', 'Pendiente'), ('finalizada', 'Finalizada'), ('anulada', 'Anulada')], default='pendiente', max_length=20, verbose_name='Estado'), ), migrations.AddField( model_name='cita', name='horario', field=models.CharField(choices=[('turno_1', '8:00 - 9:00'), ('turno_2', '9:00 - 10:00'), ('turno_3', '10:00 - 11:00'), ('turno_4', '11:00 - 12:00'), ('turno_5', '12:00 - 13:00'), ('turno_6', '13:00 - 14:00'), ('turno_7', '14:00 - 15:00'), ('turno_8', '15:00 - 16:00'), ('turno_9', ' 16:00 - 17:00'), ('turno_10', '17:00 - 18:00'), ('turno_11', '18:00 - 19:00'), ('turno_12', '19:00 - 20:00'), ('turno_13', '20:00 - 21:00'), ('turno_14', ' 21:00 - 22:00')], default='Seleccionar', max_length=20, verbose_name='Horario'), ), migrations.AlterField( model_name='cita', name='fecha', field=models.DateField(verbose_name='Fecha'), ), ] <file_sep>/pacientes/views.py from django.shortcuts import render # Create your views here. def vista_pacientes(request): contexto ={} return render(request, "vista_pacientes.html", contexto) <file_sep>/pacientes/migrations/0002_auto_20190805_1241.py # Generated by Django 2.0.7 on 2019-08-05 17:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pacientes', '0001_initial'), ] operations = [ migrations.AddField( model_name='paciente', name='tipo_identificacion', field=models.CharField(choices=[('cedula', 'Cédula'), ('pasaporte', 'Pasaporte')], default='cedula', max_length=20, verbose_name='Tipo identificacion'), ), migrations.AlterField( model_name='paciente', name='primerApellido', field=models.CharField(max_length=250, verbose_name='Primer apellido'), ), migrations.AlterField( model_name='paciente', name='primerNombre', field=models.CharField(max_length=250, verbose_name='Primer nombre'), ), migrations.AlterField( model_name='paciente', name='segundoApellido', field=models.CharField(max_length=250, verbose_name='Segundo apellido'), ), migrations.AlterField( model_name='paciente', name='segundoNombre', field=models.CharField(max_length=250, verbose_name='Segundo nombre'), ), ] <file_sep>/pacientes/migrations/0004_auto_20190805_1615.py # Generated by Django 2.0.7 on 2019-08-05 21:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pacientes', '0003_auto_20190805_1532'), ] operations = [ migrations.AlterField( model_name='paciente', name='correo', field=models.EmailField(max_length=254, null=True, verbose_name='Email'), ), ]
175282bff8d134b62032f53ca9e07b311a9f5dd6
[ "Python" ]
8
Python
ericpinera/consulmed
3cc6ae1739a5e87993b3cc7d587db6d8b7e06b17
cc5c1113ef96ff8c65e91d371b59380656a65a08
refs/heads/main
<file_sep>#pragma once #include <../rapidjson/include/rapidjson/document.h> #include <vector> #include <graphics\sprite.h> #include <graphics\texture.h> #include <maths/matrix33.h> #define M_PI 3.14159265358979323846264338327950288 class Armature { public: struct Animation { float duration; std::string name; std::vector<int> displayFrame; }; struct Bone { std::string name; std::string parent; gef::Matrix33 transform; gef::Matrix33 worldTransform; }; struct Slot { std::string name; std::string parent; }; struct SkinSlot { std::string name; std::string displayName; gef::Matrix33 spriteOffsetTransform; }; struct Skin { std::vector<SkinSlot> skinSlots; }; Armature(); ~Armature(); static Armature* ReadArmatureFromJSON(const rapidjson::Document & arm_document); static Bone* ReadBoneFromJSON(const rapidjson::Value & bone_value, Armature * armature); static Slot* ReadSlotFromJSON(const rapidjson::Value & slot_value); static Skin* ReadSkinFromJSON(const rapidjson::Value & skin_value); static SkinSlot* ReadSkinSlotFromJSON(const rapidjson::Value & skinslot_value); static Animation* ReadAnimationFromJSON(const rapidjson::Value & anim_value); static gef::Matrix33 GetWorldBoneTransform(Bone* bone, Armature* armature); static Bone GetBoneFromName(std::string name, Armature* armature); static SkinSlot GetSkinSlotFromName(std::string name, Skin* skin); float frameRate; std::string name; std::vector<Bone> bones; std::vector<Slot> slots; Skin skin; std::vector<Animation> animations; }; <file_sep>#include "scene_app.h" #include <system/platform.h> #include <graphics/sprite_renderer.h> #include <graphics/font.h> #include <system/debug_log.h> #include <graphics/renderer_3d.h> #include <graphics/mesh.h> #include <maths/math_utils.h> #include <input/sony_controller_input_manager.h> #include <graphics/sprite.h> #include "load_texture.h" #include "load_json.h" #include "../rapidjson/include/rapidjson/document.h" SceneApp::SceneApp(gef::Platform& platform) : Application(platform), sprite_renderer_(NULL), input_manager_(NULL), font_(NULL), sprite_texture_(NULL), json_file_(NULL) { } void SceneApp::Init() { sprite_renderer_ = gef::SpriteRenderer::Create(platform_); InitFont(); // initialise input manager input_manager_ = gef::InputManager::Create(platform_); //char* tex_json = LoadJSON("boy-attack_tex.json"); //char* ske_json = LoadJSON("boy-attack_ske.json"); char* tex_json = LoadJSON("Dragon_tex.json"); char* ske_json = LoadJSON("Dragon_ske.json"); rapidjson::Document tex_document; tex_document.Parse(tex_json); rapidjson::Document ske_document; ske_document.Parse(ske_json); texture_atlas_ = TextureAtlas::ReadTextureAtlasFromJSON(tex_document, platform_); std::string image_filename = tex_document["imagePath"].GetString(); armature_ = Armature::ReadArmatureFromJSON(ske_document); free(tex_json); free(ske_json); frame = 0; frame_counter = 0; sprite_texture_ = CreateTextureFromPNG(image_filename.data(), platform_); sprite_.set_texture(sprite_texture_); } void SceneApp::CleanUp() { delete sprite_texture_; sprite_texture_ = NULL; delete input_manager_; input_manager_ = NULL; CleanUpFont(); delete sprite_renderer_; sprite_renderer_ = NULL; } bool SceneApp::Update(float frame_time) { fps_ = 1.0f / frame_time; /*if (frame >= (int)armature_->animation->displayFrame.size()) { frame = 0; }*/ //int currentFrame = armature_->animation->displayFrame[frame]; //TextureAtlas::Subtexture currentSubText = TextureAtlas::GetSubtextureFromName(armature_->skin->name[currentFrame], texture_atlas_); //TextureAtlas::GetSpritePositionFromSubtexture(sprite_, currentSubText, sprite_pos_.x, sprite_pos_.y); //TextureAtlas::GetSpriteSizeFromSubtexture(sprite_, currentSubText); input_manager_->Update(); /*if (frame_counter < (int)armature_->animation->duration) { frame_counter++; } else { frame_counter = 0; frame++; }*/ return true; } void SceneApp::Render() { sprite_renderer_->Begin(); // Render button icon //sprite_renderer_->DrawSprite(sprite_); for (int i = 0; i < armature_->slots.size(); i++) { Armature::SkinSlot currentSkinSlot = Armature::GetSkinSlotFromName(armature_->slots[i].name, &armature_->skin); Armature::Bone currentBone = Armature::GetBoneFromName(armature_->slots[i].parent, armature_); TextureAtlas::Subtexture currentSubTexture = TextureAtlas::GetSubtextureFromName(currentSkinSlot.displayName, texture_atlas_); TextureAtlas::GetSpriteTextureFromSubtexture(sprite_, currentSubTexture, texture_atlas_); gef::Matrix33 finalTransform; finalTransform.SetIdentity(); finalTransform = currentSubTexture.sub_tex_transform * currentSkinSlot.spriteOffsetTransform * currentBone.worldTransform * texture_atlas_->transform; sprite_renderer_->DrawSprite(sprite_, finalTransform); } DrawHUD(); sprite_renderer_->End(); } void SceneApp::InitFont() { font_ = new gef::Font(platform_); font_->Load("comic_sans"); } void SceneApp::CleanUpFont() { delete font_; font_ = NULL; } void SceneApp::DrawHUD() { if(font_) { // display frame rate font_->RenderText(sprite_renderer_, gef::Vector4(850.0f, 510.0f, -0.9f), 1.0f, 0xffffffff, gef::TJ_LEFT, "FPS: %.1f", fps_); } } <file_sep>#include "texture_atlas.h" #include "load_texture.h" TextureAtlas::TextureAtlas() { } TextureAtlas * TextureAtlas::ReadTextureAtlasFromJSON(rapidjson::Document & tex_document, gef::Platform& platform_) { TextureAtlas* texture_atlas = new TextureAtlas(); texture_atlas->name = tex_document["name"].GetString(); texture_atlas->width = tex_document["width"].GetFloat(); texture_atlas->height = tex_document["height"].GetFloat(); gef::Matrix33 scaleMatrix; gef::Matrix33 translationMatrix; scaleMatrix.Scale(gef::Vector2(0.25f, 0.25f)); translationMatrix.SetIdentity(); translationMatrix.SetTranslation(gef::Vector2(platform_.width() * 0.5f, platform_.height() * 0.5f)); texture_atlas->transform = scaleMatrix * translationMatrix; const rapidjson::Value& subtexture_array = tex_document["SubTexture"]; for (int subtex_num = 0; subtex_num < (int)subtexture_array.Size(); ++subtex_num) { Subtexture* subtexture = ReadSubTextureFromJSON(subtexture_array[subtex_num]); texture_atlas->sub_textures.push_back(*subtexture); delete subtexture; } return texture_atlas; } TextureAtlas::Subtexture* TextureAtlas::ReadSubTextureFromJSON(const rapidjson::Value & subtex_value) { Subtexture* subtexture = new Subtexture(); if(subtex_value.HasMember("name")) subtexture->name = subtex_value["name"].GetString(); if (subtex_value.HasMember("x")) subtexture->x = subtex_value["x"].GetFloat(); else subtexture->x = 0; if (subtex_value.HasMember("y")) subtexture->y = subtex_value["y"].GetFloat(); else subtexture->y = 0; if (subtex_value.HasMember("width")) subtexture->width = subtex_value["width"].GetFloat(); else subtexture->width = 0; if (subtex_value.HasMember("height")) subtexture->height = subtex_value["height"].GetFloat(); else subtexture->height = 0; if (subtex_value.HasMember("frameX")) subtexture->frameX = subtex_value["frameX"].GetFloat(); else subtexture->frameX = 0; if (subtex_value.HasMember("frameY")) subtexture->frameY = subtex_value["frameY"].GetFloat(); else subtexture->frameY = 0; if (subtex_value.HasMember("frameWidth")) subtexture->frameWidth = subtex_value["frameWidth"].GetFloat(); else subtexture->frameWidth = 0; if (subtex_value.HasMember("frameHeight")) subtexture->frameHeight = subtex_value["frameHeight"].GetFloat(); else subtexture->frameHeight = 0; subtexture->sub_tex_transform.SetIdentity(); gef::Matrix33 scaleMatrix; gef::Matrix33 translationMatrix; scaleMatrix.Scale(gef::Vector2(subtexture->width, subtexture->height)); translationMatrix.SetIdentity(); translationMatrix.SetTranslation(gef::Vector2(((subtexture->width* 0.5f) - (subtexture->frameWidth* 0.5f + subtexture->frameX)), ((subtexture->height* 0.5f) - (subtexture->frameHeight* 0.5f + subtexture->frameY)))); subtexture->sub_tex_transform = scaleMatrix * translationMatrix; return subtexture; } void TextureAtlas::GetSpriteSizeFromSubtexture(gef::Sprite &sprite, Subtexture & subtexture) { sprite.set_width(subtexture.width); sprite.set_height(subtexture.height); } void TextureAtlas::GetSpritePositionFromSubtexture(gef::Sprite &sprite, const Subtexture & subtexture, float x, float y) { gef::Vector2 offset = gef::Vector2(subtexture.width*0.5 - (subtexture.frameWidth*0.5 + subtexture.frameX), subtexture.height*0.5 - (subtexture.frameHeight*0.5 + subtexture.frameY)); sprite.set_position(gef::Vector4(x + offset.x, y + offset.y, 0)); } void TextureAtlas::GetSpriteTextureFromSubtexture(gef::Sprite &sprite, const Subtexture & subtexture, TextureAtlas* textureAtlas) { float uv_width; float uv_height; gef::Vector2 uv_pos; uv_pos = gef::Vector2(subtexture.x / textureAtlas->width, subtexture.y / textureAtlas->height); uv_width = subtexture.width / textureAtlas->width; uv_height = subtexture.height / textureAtlas->height; sprite.set_uv_position(uv_pos); sprite.set_uv_width(uv_width); sprite.set_uv_height(uv_height); } TextureAtlas::Subtexture TextureAtlas::GetSubtextureFromName(std::string name, TextureAtlas * textureAtlas) { for (int i = 0; i < textureAtlas->sub_textures.size(); i++) { if (textureAtlas->sub_textures[i].name == name) { return textureAtlas->sub_textures[i]; } }; return Subtexture(); } <file_sep>#include <string> #include <system/file.h> char* LoadJSON(const char* filename) { std::string json_filename(filename); char* json_file_data = NULL; Int32 file_size = 0; gef::File* file = gef::File::Create(); bool success = true; success = file->Open(json_filename.c_str()); if (success) { success = file->GetSize(file_size); if (success) { // going to allocate an extra byte so we can NULL terminate the string json_file_data = (char*)malloc(file_size+1); success = json_file_data != NULL; if (success) { Int32 bytes_read; success = file->Read(json_file_data, file_size, bytes_read); if (success) success = bytes_read == file_size; } } file->Close(); delete file; file = NULL; } // NULL terminate the JSON string if (success && (file_size > 0) && json_file_data) json_file_data[file_size] = 0; return json_file_data; }<file_sep>gef-abertay was not created by me. It was supplied by Abertay University. This program requires rapidjson<file_sep>#include "Armature.h" Armature::Armature() { } Armature * Armature::ReadArmatureFromJSON(const rapidjson::Document & arm_document) { Armature* armature = new Armature(); armature->frameRate = arm_document["armature"][0]["frameRate"].GetFloat(); armature->name = arm_document["armature"][0]["name"].GetString(); const rapidjson::Value& bone_val = arm_document["armature"][0]["bone"]; for (int bone_num = 0; bone_num < (int)bone_val.Size(); bone_num++) { Bone* bone = ReadBoneFromJSON(bone_val[bone_num], armature); armature->bones.push_back(*bone); delete bone; } const rapidjson::Value& slot_val = arm_document["armature"][0]["slot"]; for (int slot_num = 0; slot_num < (int)slot_val.Size(); slot_num++) { Slot* slot = ReadSlotFromJSON(slot_val[slot_num]); armature->slots.push_back(*slot); delete slot; } const rapidjson::Value& skin_val = arm_document["armature"][0]["skin"][0]; armature->skin = *ReadSkinFromJSON(skin_val); const rapidjson::Value& anim_val = arm_document["armature"][0]["animation"]; for (int anim_num = 0; anim_num < (int)anim_val.Size(); ++anim_num) { Animation* animation = ReadAnimationFromJSON(anim_val[anim_num]); armature->animations.push_back(*animation); delete animation; } return armature; } Armature::Bone * Armature::ReadBoneFromJSON(const rapidjson::Value & bone_value, Armature* armature) { Bone* bone = new Bone(); if (bone_value.HasMember("name")) bone->name = bone_value["name"].GetString(); else bone->name = ""; if (bone_value.HasMember("parent")) bone->parent = bone_value["parent"].GetString(); else bone->parent = ""; if (bone_value.HasMember("transform")) { gef::Matrix33 translationMatrix; gef::Matrix33 rotationMatrix; translationMatrix.SetIdentity(); translationMatrix.SetTranslation(gef::Vector2(bone_value["transform"]["x"].GetFloat(), bone_value["transform"]["y"].GetFloat())); float rotRadians = (bone_value["transform"]["skY"].GetFloat() * M_PI) / 180; rotationMatrix.Rotate(rotRadians); bone->transform = rotationMatrix * translationMatrix; bone->worldTransform = GetWorldBoneTransform(bone, armature); } else { bone->transform.SetIdentity(); bone->worldTransform.SetIdentity(); } return bone; } Armature::Slot * Armature::ReadSlotFromJSON(const rapidjson::Value & slot_value) { Slot* slot = new Slot(); if (slot_value.HasMember("name")) slot->name = slot_value["name"].GetString(); else slot->name = ""; if (slot_value.HasMember("parent")) slot->parent = slot_value["parent"].GetString(); else slot->parent = ""; return slot; } Armature::Skin * Armature::ReadSkinFromJSON(const rapidjson::Value & skin_value) { Skin* skin = new Skin(); if (skin_value.HasMember("slot")) { for (int slot_num = 0; slot_num < skin_value["slot"].Size(); slot_num++) { SkinSlot* skinslot = new SkinSlot(); skinslot = ReadSkinSlotFromJSON(skin_value["slot"][slot_num]); skin->skinSlots.push_back(*skinslot); delete skinslot; } } return skin; } Armature::SkinSlot * Armature::ReadSkinSlotFromJSON(const rapidjson::Value & skinslot_value) { SkinSlot* skinslot = new SkinSlot(); if (skinslot_value.HasMember("name")) skinslot->name = skinslot_value["name"].GetString(); else skinslot->name = ""; if (skinslot_value.HasMember("display")) { if (skinslot_value["display"][0].HasMember("name")) { skinslot->displayName = skinslot_value["display"][0]["name"].GetString(); } else { skinslot->displayName = ""; } gef::Matrix33 translationMatrix; gef::Matrix33 rotationMatrix; translationMatrix.SetIdentity(); rotationMatrix.SetIdentity(); if (skinslot_value["display"][0].HasMember("transform")) { if (skinslot_value["display"][0]["transform"].HasMember("x") && skinslot_value["display"][0]["transform"].HasMember("y")) { float spriteX = skinslot_value["display"][0]["transform"]["x"].GetFloat(); float spriteY = skinslot_value["display"][0]["transform"]["y"].GetFloat(); translationMatrix.SetTranslation(gef::Vector2(spriteX, spriteY)); } if (skinslot_value["display"][0]["transform"].HasMember("skY")) { float rotRadians = (skinslot_value["display"][0]["transform"]["skY"].GetFloat() * M_PI) / 180; rotationMatrix.Rotate(rotRadians); } } skinslot->spriteOffsetTransform = rotationMatrix * translationMatrix; } else { skinslot->displayName = ""; skinslot->spriteOffsetTransform.SetIdentity(); } return skinslot; } Armature::Animation * Armature::ReadAnimationFromJSON(const rapidjson::Value & anim_value) { Animation* animation = new Animation(); animation->duration = anim_value["duration"].GetFloat(); animation->name = anim_value["name"].GetString(); if (anim_value.HasMember("slot")) { for (int slot_num = 0; slot_num < (int)anim_value["slot"].Size(); slot_num++) { for (int frame_num = 0; frame_num < (int)anim_value["slot"][slot_num]["displayFrame"].Size(); frame_num++) { if (anim_value["slot"][slot_num]["displayFrame"][frame_num].HasMember("value")) { animation->displayFrame.push_back(anim_value["slot"][slot_num]["displayFrame"][frame_num]["value"].GetInt()); } } } } //if(anim_value.HasMember("")) return animation; } gef::Matrix33 Armature::GetWorldBoneTransform(Bone* bone, Armature* armature) { gef::Matrix33 worldBoneTransform; worldBoneTransform.SetIdentity(); worldBoneTransform = bone->transform; if (bone->parent != "") { worldBoneTransform = worldBoneTransform * GetBoneFromName(bone->parent, armature).worldTransform; } return worldBoneTransform; } Armature::Bone Armature::GetBoneFromName(std::string name, Armature* armature) { Bone bone; for (int bone_num = 0; bone_num < armature->bones.size(); bone_num++) { if (armature->bones[bone_num].name == name) { bone = armature->bones[bone_num]; } } return bone; } Armature::SkinSlot Armature::GetSkinSlotFromName(std::string name, Skin * skin) { SkinSlot skinSlot; for (int slot_num = 0; slot_num < skin->skinSlots.size(); slot_num++) { if (skin->skinSlots[slot_num].name == name) { skinSlot = skin->skinSlots[slot_num]; } } return skinSlot; } <file_sep>/* * default_sprite_shader.cpp * * Created on: 28 Jan 2015 * Author: grant */ #include <graphics/default_sprite_shader.h> #include <graphics/shader_interface.h> #include <system/file.h> #include <system/platform.h> #include <system/debug_log.h> #include <string> #include <graphics/sprite.h> #include <math.h> #include <maths/matrix33.h> #ifdef _WIN32 #include <platform/d3d11/graphics/shader_interface_d3d11.h> #endif namespace gef { DefaultSpriteShader::DefaultSpriteShader(const Platform& platform) :Shader(platform) ,sprite_data_variable_index_(-1) ,projection_matrix_variable_index_(-1) ,texture_sampler_index_(-1) { bool success = true; // load vertex shader source in from a file char* vs_shader_source = NULL; Int32 vs_shader_source_length = 0; success = LoadShader("default_sprite_shader_vs", "shaders/gef", &vs_shader_source, vs_shader_source_length, platform); char* ps_shader_source = NULL; Int32 ps_shader_source_length = 0; success = LoadShader("default_sprite_shader_ps", "shaders/gef", &ps_shader_source, ps_shader_source_length, platform); device_interface_->SetVertexShaderSource(vs_shader_source, vs_shader_source_length); device_interface_->SetPixelShaderSource(ps_shader_source, ps_shader_source_length); delete[] vs_shader_source; vs_shader_source = NULL; delete[] ps_shader_source; ps_shader_source = NULL; projection_matrix_variable_index_ = device_interface_->AddVertexShaderVariable("proj_matrix", ShaderInterface::kMatrix44); sprite_data_variable_index_ = device_interface_->AddVertexShaderVariable("sprite_data", ShaderInterface::kMatrix44); texture_sampler_index_ = device_interface_->AddTextureSampler("texture_sampler"); device_interface_->AddVertexParameter("position", ShaderInterface::kVector3, 0, "POSITION", 0); device_interface_->set_vertex_size(12); device_interface_->CreateVertexFormat(); #ifdef _WIN32 gef::ShaderInterfaceD3D11* shader_interface_d3d11 = static_cast<gef::ShaderInterfaceD3D11*>(device_interface_); // Create a texture sampler state description. D3D11_SAMPLER_DESC sampler_desc; sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; sampler_desc.MipLODBias = 0.0f; sampler_desc.MaxAnisotropy = 1; sampler_desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; sampler_desc.BorderColor[0] = 0; sampler_desc.BorderColor[1] = 0; sampler_desc.BorderColor[2] = 0; sampler_desc.BorderColor[3] = 0; sampler_desc.MinLOD = 0; sampler_desc.MaxLOD = D3D11_FLOAT32_MAX; shader_interface_d3d11->AddSamplerState(sampler_desc); #endif success = device_interface_->CreateProgram(); } DefaultSpriteShader::~DefaultSpriteShader() { } DefaultSpriteShader::DefaultSpriteShader() : sprite_data_variable_index_(-1) , projection_matrix_variable_index_(-1) , texture_sampler_index_(-1) { } void DefaultSpriteShader::SetSceneData(const Matrix44& projection_matrix) { Matrix44 projectionT; projectionT.Transpose(projection_matrix); device_interface_->SetVertexShaderVariable(projection_matrix_variable_index_, &projectionT); // device_interface_->SetVertexShaderVariable(projection_matrix_variable_index_, &projection_matrix); } void DefaultSpriteShader::SetSpriteData(const Sprite& sprite, const gef::Matrix33& transform, const Texture* texture) { Matrix44 sprite_data; BuildSpriteShaderData(sprite, transform, sprite_data); device_interface_->SetVertexShaderVariable(sprite_data_variable_index_, &sprite_data); device_interface_->SetTextureSampler(texture_sampler_index_, texture); } void DefaultSpriteShader::BuildSpriteShaderData(const Sprite& sprite, const gef::Matrix33& transform, Matrix44& sprite_data) { Vector2 sprite_origin(0.5f, 0.5f); Vector2 sprite_uv_origin(0.0f, 0.0f); Vector2 sprite_uv_size(1.0f, 1.0f); sprite_data.set_m(2, 0, transform.m[2][0]); sprite_data.set_m(2, 1, transform.m[2][1]); // origin ( not going to pass origin in so we can use for something else // sprite_data.set_m(2,2, sprite_origin.x); // sprite_data.set_m(2,3, sprite_origin.y); // depth sprite_data.set_m(2, 2, sprite.position().z()); // scale*rotation sprite_data.set_m(0, 0, transform.m[0][0]); sprite_data.set_m(0, 1, transform.m[0][1]); sprite_data.set_m(1, 0, transform.m[1][0]); sprite_data.set_m(1, 1, transform.m[1][1]); // Source rectangle sprite_data.set_m(0, 2, sprite.uv_position().x); sprite_data.set_m(0, 3, sprite.uv_position().y); sprite_data.set_m(1, 2, sprite.uv_width()); sprite_data.set_m(1, 3, sprite.uv_height()); Colour colour; colour.SetFromAGBR(sprite.colour()); sprite_data.set_m(3, 0, colour.r); sprite_data.set_m(3, 1, colour.g); sprite_data.set_m(3, 2, colour.b); sprite_data.set_m(3, 3, colour.a); } void DefaultSpriteShader::BuildSpriteTransform(const Sprite& sprite, gef::Matrix33& transform) { // scale*rotation if (sprite.rotation() == 0) { transform.m[0][0] = sprite.width(); transform.m[0][1] = 0.0f; transform.m[1][0] = 0.0f; transform.m[1][1] = sprite.height(); } else { transform.m[0][0] = cosf(sprite.rotation())*sprite.width(); transform.m[0][1] = sinf(sprite.rotation())*sprite.width(); transform.m[1][0] = -sinf(sprite.rotation())*sprite.height(); transform.m[1][1] = cosf(sprite.rotation())*sprite.height(); } transform.m[0][2] = 0.0f; transform.m[1][2] = 0.0f; gef::Vector4 position = sprite.position(); transform.m[2][0] = position.x(); transform.m[2][1] = position.y(); transform.m[2][2] = 1.0f; } } <file_sep>#ifndef _JSON_H #define _JSON_H char* LoadJSON(const char* filename); #endif // _JSON_H<file_sep>#ifndef _TEXTURE_ATLAS_H #define _TEXTURE_ATLAS_H #include <../rapidjson/include/rapidjson/document.h> #include <vector> #include <graphics\sprite.h> #include <graphics\texture.h> #include <maths/matrix33.h> class TextureAtlas { public: struct Subtexture { std::string name; float x; float y; float width; float height; float frameY; float frameX; float frameWidth; float frameHeight; gef::Matrix33 sub_tex_transform; }; TextureAtlas(); static TextureAtlas* ReadTextureAtlasFromJSON(rapidjson::Document& tex_document, gef::Platform& platform_); static Subtexture* ReadSubTextureFromJSON(const rapidjson::Value& subtex_value); static void GetSpriteSizeFromSubtexture(gef::Sprite &sprite, Subtexture &subtexture); static void GetSpritePositionFromSubtexture(gef::Sprite &sprite, const Subtexture &subtexture, float x, float y); static void GetSpriteTextureFromSubtexture(gef::Sprite &sprite, const Subtexture &subtexture, TextureAtlas* textureAtlas); static Subtexture GetSubtextureFromName(std::string name, TextureAtlas* textureAtlas); std::vector<Subtexture> sub_textures; gef::Matrix33 transform; protected: std::string name; float width; float height; }; #endif
5f2720560c50042f115cdfb9201728958d241893
[ "C", "Text", "C++" ]
9
C++
Skelebags/AnimationSystem
105a5c0978dcfc3ef75527c262ce2037015a1915
0757171a3f813bee11449241652f87454a71b23b
refs/heads/main
<repo_name>TJ-Yads/Dominion<file_sep>/TJGameController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class TJGameController : MonoBehaviour//primary game controller to manage various aspects of the game { //data for general variables public int wood, stone, gold, food, WoodMax, StoneMax, GoldMax, FoodMax, BaseLimit, BonusGeneration; public Text WoodCount, StoneCount, GoldCount, FoodCount, PopulationCounter, BuildingHealth, BuildingInfo, Wave, GameOverText; public RaycastHit hit, target; public GameObject Buildable, BuildingRim, BuildingInfoFull, ButtonBackground, GameOverUI; public Vector3 HitEnd; public int PopuationLimit, CurrentPopulation, GatherValue, DMGValue = 0, Health = 0; public bool PlacingBuilding, GameOver; public float CollectionTimer = 3f; private DifficultyManager DifficultyOBJ; public int WaveValue; //data for barracks public GameObject BarracksButtons; //data for castle public GameObject CaslteButtons, ResearchBuildButton, CastleRime; //data for store house public int StorehouseCount; public GameObject SHouseButtons; //data for research center public GameObject RCButtons; public int PopulationBonus, GenerationBonus; public bool ActiveResearchBuild; //data for houses public GameObject HouseButtons; public int HouseCount; //data for watch towers public GameObject WTButtons; //data for deposit points public GameObject DepositButtons; public int LumberCount, MiningCount, MillCount; private int fingerID = -1; // Start is called before the first frame update void Start()//set the difficulty values based on what was changed in the main menu { Time.timeScale = 1; GameObject gameControllerObject = GameObject.FindWithTag("Difficulty"); DifficultyOBJ = gameControllerObject.GetComponent<DifficultyManager>(); if (DifficultyOBJ.DifficultyValue == 1) { Health = 1; DMGValue = 1; GatherValue = GatherValue + 2; } if (DifficultyOBJ.DifficultyValue == 3) { Health = -1; GatherValue = GatherValue - 2; } Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); UpdateResources(); UpdatePopulation(); } // Update is called once per frame void Update() { if (GameOver == true) { GameFailed(); } if (EventSystem.current.IsPointerOverGameObject(fingerID)) { return; } Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//fire a ray from mouse to track what the player is pointing at Physics.Raycast(ray, out target); HitEnd = (hit.point); Buildable.transform.position = HitEnd; //&& hit.transform.tag != "UI" if (Physics.Raycast(ray, out hit) && Input.GetButton("Fire1") && PlacingBuilding == false && hit.transform.tag != "UI") { if (hit.transform.tag == "Barracks")//if the player clicks the barracks then the game opens up the menu popups for that barracks and sets refrence data to that barracks { ClearButtons(); BarracksButtons.SetActive(true); ButtonBackground.SetActive(true); BarracksMechanics Master = hit.collider.GetComponentInParent<BarracksMechanics>(); BarracksSpawnPoint Child = hit.collider.GetComponent<BarracksSpawnPoint>(); Master.ArchBut.SetActive(false); Master.HorseBut.SetActive(false); Master.TroopUnlockBut.SetActive(true); Master.TroopUnlock = 0; BuildingInfoFull.SetActive(true); if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.SpawnPoint = Child.SpawnPoint; Master.ActiveBuilding = Child.Building; if (Child.TroopUnlock == 1) { Master.TroopUnlock = 1; Master.ArchBut.SetActive(true); } if (Child.TroopUnlock == 2) { Master.TroopUnlock = 2; Master.HorseBut.SetActive(true); Master.TroopUnlockBut.SetActive(false); } } } if (hit.transform.tag == "Castle")//if the player clicks the castle then the game opens up the menu popups for that castle sets refrence data to that caslte { ClearButtons(); CaslteButtons.SetActive(true); ButtonBackground.SetActive(true); ResearchBuildButton.SetActive(true); BuildingRim = CastleRime; BuildingRim.SetActive(true); BuildingInfoFull.SetActive(true); if (ActiveResearchBuild == true) { ResearchBuildButton.SetActive(false); } } if (hit.transform.tag == "StoreHouse")//if the player clicks the StoreHouse then the game opens up the menu popups for that StoreHouse and sets refrence data to that StoreHouse { ClearButtons(); SHouseButtons.SetActive(true); ButtonBackground.SetActive(true); StoreHouseMaster Master = hit.collider.GetComponentInParent<StoreHouseMaster>(); StoreHouseMechanics Child = hit.collider.GetComponent<StoreHouseMechanics>(); if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.StoreHouseUpgraded = false; Master.ActiveBuilding = Child.Building; BuildingInfoFull.SetActive(true); if (Child.IncreasedStorage == true) { Master.StoreHouseUpgraded = true; } if (Child.IncreasedHealth == true) { Master.HealthIncreased = true; } else { Master.HealthIncreased = false; } } } if (hit.transform.tag == "House")//if the player clicks the House then the game opens up the menu popups for that House and sets refrence data to that House { ClearButtons(); HouseButtons.SetActive(true); ButtonBackground.SetActive(true); HouseMaster Master = hit.collider.GetComponentInParent<HouseMaster>(); HouseMechanics Child = hit.collider.GetComponent<HouseMechanics>(); if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.HouseUpgraded = false; Master.ActiveBuilding = Child.Building; BuildingInfoFull.SetActive(true); Master.SpawnPoint = Child.SpawnPoint; if (Child.IncreasedStorage == true) { Master.HouseUpgraded = true; } if (Child.IncreasedHealth == true) { Master.HealthIncreased = true; } else { Master.HealthIncreased = false; } } } if (hit.transform.tag == "ResearchCenter")//if the player clicks the ResearchCenter then the game opens up the menu popups for that ResearchCenter and sets refrence data to that ResearchCenter { ClearButtons(); RCButtons.SetActive(true); ButtonBackground.SetActive(true); ResearchMaster Master = hit.collider.GetComponentInParent<ResearchMaster>(); ResearchMechanics Child = hit.collider.GetComponent<ResearchMechanics>(); if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.ActiveBuilding = Child.Building; BuildingInfoFull.SetActive(true); } } if (hit.transform.tag == "WatchTower")//if the player clicks the WatchTower then the game opens up the menu popups for that WatchTower and sets refrence data to that WatchTower { ClearButtons(); WTButtons.SetActive(true); ButtonBackground.SetActive(true); WatchTowerMaster Master = hit.collider.GetComponentInParent<WatchTowerMaster>(); WatchTowerMechanics Child = hit.collider.GetComponent<WatchTowerMechanics>(); if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.ActiveBuilding = Child.Building; BuildingInfoFull.SetActive(true); } } if (hit.transform.tag == "Quary" || hit.transform.tag == "LumberYard" || hit.transform.tag == "Mill")//if the player clicks a deposit point then the game opens up the menu popups for that deposit point and sets refrence data to that deposit point { ClearButtons(); DepositButtons.SetActive(true); ButtonBackground.SetActive(true); DepositPointMaster Master = hit.collider.GetComponentInParent<DepositPointMaster>(); DepositPointMechanics Child = hit.collider.GetComponent<DepositPointMechanics>(); Master.LumberActive = false; Master.MiningActive = false; Master.MillActive = false; Master.StoreHouseUpgraded = false; if (Master != null) { BuildingRim = Child.BuildingRime; BuildingRim.SetActive(true); Master.ActiveBuilding = Child.Building; BuildingInfoFull.SetActive(true); if (Child.Wood == true) { Master.LumberActive = true; } if (Child.Stone == true) { Master.MiningActive = true; } if (Child.Food == true) { Master.MillActive = true; } if (Child.IncreasedStorage == true) { Master.StoreHouseUpgraded = true; } } } } if (Input.GetButton("Fire2") && PlacingBuilding == false)// if the player uses right click then the menu popups are hidden { ClearButtons(); } } public void ClearButtons()//hides all menu popups when activated { BarracksButtons.SetActive(false); CaslteButtons.SetActive(false); SHouseButtons.SetActive(false); HouseButtons.SetActive(false); RCButtons.SetActive(false); WTButtons.SetActive(false); BuildingInfoFull.SetActive(false); ButtonBackground.SetActive(false); DepositButtons.SetActive(false); if (BuildingRim != null) { BuildingRim.SetActive(false); } } public void GameFailed()//when you lose the game ends and tells you the wave counter { GameOverText.text = "The enemy was able to destroy your castle. You made it to " + WaveValue + "Waves, Perhaps try a lower difficulty"; Time.timeScale = 0; GameOverUI.SetActive(true); } public void UpdateResources()//update the players resource counters including the resource limit and current amount the player has { WoodMax = (StorehouseCount * 200) + BaseLimit + (200 * LumberCount); StoneMax = (StorehouseCount * 200) + BaseLimit + (200 * MiningCount); GoldMax = (StorehouseCount * 200) + BaseLimit + (200 * MiningCount); FoodMax = (StorehouseCount * 200) + BaseLimit + (200 * MillCount); if (wood > WoodMax) { wood = WoodMax; } if (stone > StoneMax) { stone = StoneMax; } if (gold > GoldMax) { gold = GoldMax; } if (food > FoodMax) { food = FoodMax; } WoodCount.text = "" + wood + "/" + WoodMax; StoneCount.text = "" + stone + "/" + StoneMax; GoldCount.text = "" + gold + "/" + GoldMax; FoodCount.text = "" + food + "/" + FoodMax; } public void UpdatePopulation()//update the population counter including the max population and limit { PopuationLimit = (HouseCount + 1) * (5 + PopulationBonus) + 5; PopulationCounter.text = "Population: " + CurrentPopulation + "/" + PopuationLimit; } public void UpdateWave()//update wave text with the current wave { Wave.text = "Wave: " + WaveValue; } } <file_sep>/HouseMaster.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class HouseMaster : MonoBehaviour//mechanics for the house building which allows for resource gatherers { private TJGameController gamecontroller; private HouseMechanics Child; public GameObject ActiveBuilding, Farmer, Lumberjack, Miner; public int HouseCount; public Transform SpawnPoint; public bool HouseUpgraded, HealthIncreased; public GameObject UpgradeButton, HealthButton; // Start is called before the first frame update void Start() { GameObject gameControllerObject = GameObject.FindWithTag("GameController"); gamecontroller = gameControllerObject.GetComponent<TJGameController>(); } // Update is called once per frame void Update()//update refrence data { if (ActiveBuilding != null && gamecontroller.HouseButtons.activeInHierarchy == true) { GameObject TargetedHouse = ActiveBuilding; Child = TargetedHouse.GetComponent<HouseMechanics>(); gamecontroller.BuildingHealth.text = "Health: " + Child.Health; gamecontroller.BuildingInfo.text = "This building increases the population of your kingdom by " + Child.TotalPopBonus + "."; } if (HouseUpgraded == false) { UpgradeButton.SetActive(true); } else UpgradeButton.SetActive(false); if (HealthIncreased == false) { HealthButton.SetActive(false); } else HealthButton.SetActive(false); } public void SpawnFarmer()//spawn a farmer unit and update resources and population { if (gamecontroller.stone > 10 && gamecontroller.wood > 10 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.stone -= 10; gamecontroller.wood -= 10; Instantiate(Farmer, SpawnPoint); gamecontroller.UpdateResources(); } } public void SpawnMiner()//spawn a miner unit and update resources and population { if (gamecontroller.food > 10 && gamecontroller.wood > 10 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.food -= 10; gamecontroller.wood -= 10; Instantiate(Miner, SpawnPoint); gamecontroller.UpdateResources(); } } public void SpawnLumberjack()//spawn a lumberjack unit and update resources and population { if (gamecontroller.food > 10 && gamecontroller.stone > 10 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.food -= 10; gamecontroller.stone -= 10; Instantiate(Lumberjack, SpawnPoint); gamecontroller.UpdateResources(); } } public void SellBuilding()//destroy building and reduce population max { gamecontroller.wood += 10; gamecontroller.stone += 10; gamecontroller.food += 10; HouseCount -= 1; if (HouseUpgraded == true) { HouseCount -= 1; HouseUpgraded = false; } Destroy(ActiveBuilding); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } public void UpgradeCapcity()//increase the population max { if (HouseUpgraded == false && gamecontroller.food > 8 && gamecontroller.wood > 8 && gamecontroller.stone > 8) { gamecontroller.wood -= 8; gamecontroller.stone -= 8; gamecontroller.food -= 8; HouseUpgraded = true; Child.CapacityUp(); gamecontroller.UpdateResources(); } } public void IncreaseHealth()//increase building health { if (HealthIncreased == false) { Child.HealthUp(); } HealthIncreased = true; } public void PopulationUpdater() { gamecontroller.HouseCount = HouseCount; gamecontroller.UpdatePopulation(); } } <file_sep>/ResearchMaster.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ResearchMaster : MonoBehaviour//mechanics attached to the research facility in game { private TJGameController gamecontroller; public int PopulationBonus, GenerationBonus; public GameObject ActiveBuilding; public int IncPop, IncGen, ToHe, ToDmg, GenTime; private ResearchMechanics Child; public Text IncPopCost, IncGenCost, ToHeCost, ToDmgCost, GenTimeCost; // Start is called before the first frame update void Start() { GameObject gameControllerObject = GameObject.FindWithTag("GameController"); gamecontroller = gameControllerObject.GetComponent<TJGameController>(); } // Update is called once per frame void Update()//update refrence data { if (ActiveBuilding != null && gamecontroller.RCButtons.activeInHierarchy == true) { GameObject TargetedHouse = ActiveBuilding; Child = TargetedHouse.GetComponent<ResearchMechanics>(); gamecontroller.BuildingHealth.text = "Health: " + Child.Health; gamecontroller.BuildingInfo.text = "This building allows for various upgrades to your kingdom."; } gamecontroller.PopulationBonus = PopulationBonus; gamecontroller.GenerationBonus = GenerationBonus; IncPopCost.text = "G: -" + IncPop; IncGenCost.text = "G: -" + IncGen; ToHeCost.text = "F: -" + ToHe; ToDmgCost.text = "W: -" + ToDmg; GenTimeCost.text = "G: -" + GenTime; } public void IncreasePopulation()//increase population max and increase upgrade cost { if (gamecontroller.gold > IncPop) { gamecontroller.gold -= IncPop; PopulationBonus += 1; IncPop = IncPop + IncPop - 20; gamecontroller.UpdateResources(); gamecontroller.UpdatePopulation(); } } public void IncreaseGeneration()//increase gold generation and upgrade cost { if (gamecontroller.gold > IncGen) { gamecontroller.gold -= IncGen; GenerationBonus += 1; IncGen = IncGen + IncGen - 15; gamecontroller.UpdateResources(); } } public void TroopHealth()//increase troop health and upgrade cost { if (gamecontroller.food > ToHe) { gamecontroller.Health += 1; gamecontroller.food -= ToHe; ToHe = ToHe + ToHe - 5; gamecontroller.UpdateResources(); } } public void TroopDamage()//increase troop damage and upgrade cost { if (gamecontroller.wood > ToDmg) { gamecontroller.DMGValue += 1; gamecontroller.wood -= ToDmg; ToDmg = ToDmg + ToDmg - 5; gamecontroller.UpdateResources(); } } public void GenerationTime()//reduce the time to gain gold and increase upgrade cost { if (gamecontroller.gold > GenTime) { gamecontroller.gold -= GenTime; gamecontroller.CollectionTimer -= .3f; GenTime = GenTime + GenTime - 10; gamecontroller.UpdateResources(); } } public void SellBuilding()//destroy building and gain resources equal to half the cost { gamecontroller.wood += 25; gamecontroller.stone += 25; gamecontroller.gold += 25; gamecontroller.food += 50; gamecontroller.ActiveResearchBuild = false; Destroy(ActiveBuilding); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } <file_sep>/CastleMechanics.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CastleMechanics : MonoBehaviour//mechanics for the castle { public GameObject BuildableEmpty, TextPopUp; private TJGameController gamecontroller; private ResourceCost CostList; public int Health; public Text BuildingHealth; private DifficultyManager DifficultyOBJ; // Start is called before the first frame update void Start() { GameObject DiffcultlyOject = GameObject.FindWithTag("Difficulty"); DifficultyOBJ = DiffcultlyOject.GetComponent<DifficultyManager>(); GameObject gameControllerObject = GameObject.FindWithTag("GameController"); gamecontroller = gameControllerObject.GetComponent<TJGameController>(); CostList = gameControllerObject.GetComponent<ResourceCost>(); if (DifficultyOBJ.DifficultyValue == 3) { Health = Health - 5; } } // Update is called once per frame void Update()//update refrence data { BuildingHealth.text = "Castle health: " + Health; if (gamecontroller.CaslteButtons.activeInHierarchy == true) { gamecontroller.BuildingHealth.text = "Health: " + Health; gamecontroller.BuildingInfo.text = "This building allows for the construction of other buildings."; } if (Health <= 0) { gamecontroller.GameOver = true; } } public void BuildBarracks(GameObject BuildingName)//build a barracks building if the player has the resources-- make troops { CostList.BarracksCost();//find cost if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food)//check cost and resource count { //reduce player resources gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName;//set name of building to barracks Instantiate(BuildableEmpty, gamecontroller.Buildable.transform);//create the barracks and attach it to the player mouse gamecontroller.ClearButtons();//clear menu popups gamecontroller.UpdateResources();// reduce resources } } public void BuildFarm(GameObject BuildingName)//build a farm-- gain food { CostList.FarmCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildMill(GameObject BuildingName)//build a mill--increase food storage { CostList.Mill(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildRC(GameObject BuildingName)//build a research center-- upgrade various values { CostList.ResearchCenterCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildLY(GameObject BuildingName)// build a lumber yard-- wood storage { CostList.LumberYardCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildMC(GameObject BuildingName)// build a mining camp-- stone storage { CostList.MiningCampCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildWT(GameObject BuildingName)//build a watch tower-- defense building { CostList.WatchtowerCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } public void BuildHouse(GameObject BuildingName)//build a house-- population and gatherers { CostList.HouseCost(); if (gamecontroller.wood >= CostList.Wood && gamecontroller.stone >= CostList.Stone && gamecontroller.gold >= CostList.Gold && gamecontroller.food >= CostList.Food) { gamecontroller.wood -= CostList.Wood; gamecontroller.stone -= CostList.Stone; gamecontroller.gold -= CostList.Gold; gamecontroller.food -= CostList.Food; BuildableEmpty = BuildingName; Instantiate(BuildableEmpty, gamecontroller.Buildable.transform); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } } <file_sep>/README.md # Dominion TJ Game Controller: This script controls the primary game aspects such as difficulty, UI, losing, what buildings the player is clicking on and updating resource, population and waves. Castle Mechanics: This script controls the castle and its UI which allows for buying the buildings in game and its health that can cause a game over. Building Follower: This script connects a building to the mouse when it is bought and allows the player to cancel the purchase or place it down, if the building is on another one the the building turns red and cannot be placed. House Master: This script controls the houses in game and can increase population and allow the creation of gatherers to find resources for the player. Research Master: This script controls the research center and allows for various in game upgrades such more gold or stronger troops. Barracks Mechanics: This script allows the player to spawn troops for protection, each troop has diffrent costs and troops must be unlocked to be spawned. Watch Tower Firing: This script controls the watch tower and allows it to fire at the nearest enemy in range. <file_sep>/BuildingFollower.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuildingFollower : MonoBehaviour//used when placing a building-- buildings follow the mouse and change color based on placement { private TJGameController gamecontroller; public GameObject BuildingEmpty, Building, BuildingGreen, BuildingRed; public Transform ObjSize; // Start is called before the first frame update void Start() { GameObject gameControllerObject = GameObject.FindWithTag("GameController"); gamecontroller = gameControllerObject.GetComponent<TJGameController>(); gamecontroller.PlacingBuilding = true; } // Update is called once per frame void Update()//while attempting to place the building it will follow the mouse and search for the floor { BuildingEmpty.transform.position = gamecontroller.HitEnd; if (Input.GetButtonUp("Fire1") && gamecontroller.hit.transform.tag == "Floor")//if the building is on the floor then it will build and deduct resource { gamecontroller.PlacingBuilding = false; Destroy(gameObject); Instantiate(Building, gamecontroller.Buildable.transform); } if (Input.GetButtonUp("Fire2"))//if the player cancels the build then it will be deleted { gamecontroller.PlacingBuilding = false; Destroy(gameObject); } if (gamecontroller.hit.transform.tag != "Floor")//when the cursor is not on the floor the building cannot be place and the building turns red to notify the player { BuildingGreen.SetActive(false); BuildingRed.SetActive(true); } else { BuildingGreen.SetActive(true); BuildingRed.SetActive(false); } } } <file_sep>/BarracksMechanics.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BarracksMechanics : MonoBehaviour//the barracks building allows the player to spawn various troops for protection { public GameObject Soldier, Archer, Horsemen, ArchBut, HorseBut, TroopUnlockBut, ActiveBuilding; public Transform SpawnPoint; private TJGameController gamecontroller; private BarracksSpawnPoint Child; public int TroopUnlock; // Start is called before the first frame update void Start() { GameObject gameControllerObject = GameObject.FindWithTag("GameController"); gamecontroller = gameControllerObject.GetComponent<TJGameController>(); } // Update is called once per frame void Update() { if (ActiveBuilding != null && gamecontroller.BarracksButtons.activeInHierarchy == true)//when clicked this building will display its tooltip on the bottom { GameObject TargetedHouse = ActiveBuilding; Child = TargetedHouse.GetComponent<BarracksSpawnPoint>(); gamecontroller.BuildingHealth.text = "Health: " + Child.Health; gamecontroller.BuildingInfo.text = "This building allows you to train and upgrade various troops."; } if (TroopUnlock == 1) { ArchBut.SetActive(true); } if (TroopUnlock == 2) { ArchBut.SetActive(true); HorseBut.SetActive(true); TroopUnlockBut.SetActive(false); } if (TroopUnlock == 0) { ArchBut.SetActive(false); HorseBut.SetActive(false); } } public void UnlockTroops()//unlock new troops to spawn from the building { if (gamecontroller.gold > 50) { gamecontroller.gold -= 50; gamecontroller.UpdateResources(); if (Child.TroopUnlock < 2) { Child.TroopUnlock += 1; Child.TroopUnlocked(); } } } //spawn methods: each on will check resources and then make the purchase if you have enough and deduct resources from game controller public void SpawnSoldiers()//spawn a footsolider-- basic solider with melee combat { if (gamecontroller.food > 15 && gamecontroller.wood > 15 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.food -= 15; gamecontroller.wood -= 15; Instantiate(Soldier, SpawnPoint); gamecontroller.UpdateResources(); } } public void SpawnArchers()//spawn an archer-- ranged fighter { if (gamecontroller.food > 35 && gamecontroller.wood > 35 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.food -= 35; gamecontroller.wood -= 35; Instantiate(Archer, SpawnPoint); gamecontroller.UpdateResources(); } } public void SpawnHorsemen()//spawn a horsemen-- direct upgrade of footsoldier { if (gamecontroller.food > 60 && gamecontroller.wood > 60 && gamecontroller.gold > 30 && gamecontroller.PopuationLimit > gamecontroller.CurrentPopulation) { gamecontroller.food -= 30; gamecontroller.wood -= 30; gamecontroller.gold -= 30; Instantiate(Horsemen, SpawnPoint); gamecontroller.UpdateResources(); } } public void SellBuilding()//remove the building and increase the resource counter by half the building cost { gamecontroller.wood += 12; gamecontroller.stone += 18; gamecontroller.gold += 12; gamecontroller.food += 7; Destroy(ActiveBuilding); gamecontroller.ClearButtons(); gamecontroller.UpdateResources(); } } <file_sep>/WatchTowerFiring.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class WatchTowerFiring : MonoBehaviour//watchtower behavior to make it fire a nearby enemies { public GameObject Projectile, closestEnemy; public Transform ProjectileSpawn; public int Health; public float AttackSpeed, nextHit; public GameObject[] Enemies; // Start is called before the first frame update // Update is called once per frame void Update() { //create an array of enemies and check there distances //if the enemy is in range then fire at the enemy //if the watchtower takes to much damage then it will be destroyed Enemies = GameObject.FindGameObjectsWithTag("Enemy"); float enemyDistance = Mathf.Infinity; Vector3 position = transform.position; foreach (GameObject enemy in Enemies) { Vector3 diff = enemy.transform.position - position; float curDistance = diff.sqrMagnitude; if (curDistance < enemyDistance && enemy.GetComponent<EnemyController>().isTarget == false) { closestEnemy = enemy; enemyDistance = curDistance; } } if (closestEnemy != null) { ProjectileSpawn.transform.LookAt(closestEnemy.transform); } if (Health <= 0) { Destroy(gameObject); } } private void OnTriggerStay(Collider other)//fire at enemies while in range, fires at the closest target { if (other.tag == "Enemy") { if (Time.time > nextHit) { Debug.Log("fired"); Instantiate(Projectile, ProjectileSpawn.position, ProjectileSpawn.rotation); nextHit = Time.time + AttackSpeed; } } } }
fa0da275c5cb9478c4985f84a3b213046c816e16
[ "Markdown", "C#" ]
8
C#
TJ-Yads/Dominion
f8e97eaf6f15f399020e28a00e085ecabfb28e6b
99676dc92d0ef79a6bb281041e9ad8c87428b076
refs/heads/master
<file_sep>package com.au.me.service; import com.au.me.model.Transaction; import com.au.me.model.TransactionType; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.au.me.util.Utils.DATE_TIME_FORMATTER; public class CsvFileReaderServiceImpl implements CsvFileReaderService { public static final String TRANSACTIONS_CSV_FILE_PATH = "transaction.csv"; private static final Logger LOGGER = Logger.getLogger(CsvFileReaderServiceImpl.class.getName()); @Override public List<Transaction> processInput() { List<Transaction> transactions = new ArrayList<>(); List<List<String>> records = new ArrayList<>(); ClassLoader classLoader = this.getClass().getClassLoader(); try (FileReader fr = new FileReader(classLoader.getResource(TRANSACTIONS_CSV_FILE_PATH).getFile())) { String line = ""; try (BufferedReader br = new BufferedReader(fr)) { while ((line = br.readLine()) != null) { String[] values = line.split(","); records.add(Arrays.asList(values)); } } } catch (IOException e) { LOGGER.log(Level.SEVERE, "File not available in resource path"); } for (List<String> lineRecord : records) { transactions.add(convertStringToTransaction(lineRecord)); } return transactions; } private Transaction convertStringToTransaction(final List<String> line) { return Transaction.builder() .transactionId(line.get(0).trim()) .fromAccount(line.get(1).trim()) .toAccount(line.get(2).trim()) .createdAt(LocalDateTime.parse(line.get(3).trim(), DATE_TIME_FORMATTER)) .amount(new BigDecimal(line.get(4).trim())) .transactionType(TransactionType.valueOf(line.get(5).trim())).build(); } } <file_sep>package com.au.me.service; import com.au.me.model.Transaction; import java.util.List; public interface CsvFileReaderService { List<Transaction> processInput(); } <file_sep>package com.au.me.service; import com.au.me.model.Transaction; import com.au.me.model.TransactionType; import org.javatuples.Pair; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class AccountBalanceServiceImpl implements AccountBalanceService { @Override public Pair<BigDecimal, Integer> getAccountBalance( final List<Transaction> transactions, final String accountId, final LocalDateTime fromDate, final LocalDateTime toDate) { transactions.sort((t1, t2) -> { if (t1.getCreatedAt().isAfter(t2.getCreatedAt())) { return 1; } //two transactions for an account can never have same createdAt ignoring equals return -1; }); final List<Transaction> transactionsInBetween = new ArrayList<>(); transactions.stream().forEach(transaction -> { if (transaction.getFromAccount().contentEquals(accountId) || transaction.getToAccount().contentEquals(accountId)) { if ((transaction.getCreatedAt().isAfter(fromDate) || transaction.getCreatedAt().isEqual(fromDate)) && (transaction.getCreatedAt().isBefore(toDate) || transaction.getCreatedAt().isEqual(toDate))) { transactionsInBetween.add(transaction); } } }); Pair<BigDecimal, Integer> balanceTuple = Pair.with(getBalance(transactionsInBetween, accountId), transactionsInBetween.size()); return balanceTuple; } private BigDecimal getBalance(List<Transaction> transactions, final String accountId) { BigDecimal balance = new BigDecimal("0"); for(Transaction transaction : transactions) { if (transaction.getFromAccount().contentEquals(accountId)) { if (transaction.getTransactionType() == TransactionType.PAYMENT) { balance = balance.add(transaction.getAmount().negate()); } else { balance = balance.add(transaction.getAmount()); } } else { if (transaction.getTransactionType() == TransactionType.REVERSAL) { balance = balance.add(transaction.getAmount()); } else { balance = balance.add(transaction.getAmount().negate()); } } } return balance; } } <file_sep>package com.au.me.service; import com.au.me.model.Transaction; import com.au.me.util.Utils; import org.javatuples.Pair; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; public class AccountBalanceServiceImplTest { AccountBalanceService accountBalanceService; CsvFileReaderService csvFileReaderService; List<Transaction> transactions; @Before public void setUp() { accountBalanceService = new AccountBalanceServiceImpl(); csvFileReaderService = new CsvFileReaderServiceImpl(); transactions = csvFileReaderService.processInput(); } @Test public void testAccountBalance() { Pair<BigDecimal, Integer> balancePair = accountBalanceService.getAccountBalance(transactions,"ACC334455", LocalDateTime.parse("20/10/2018 12:00:00", Utils.DATE_TIME_FORMATTER), LocalDateTime.parse("20/10/2018 19:00:00", Utils.DATE_TIME_FORMATTER)); Assert.assertEquals(java.util.Optional.of(2), java.util.Optional.of(balancePair.getValue1())); Assert.assertEquals(java.util.Optional.of(new BigDecimal("35.50").negate()), java.util.Optional.of(balancePair.getValue0())); } @Test public void testNoAccountBalance() { Pair<BigDecimal, Integer> balancePair = accountBalanceService.getAccountBalance(transactions,"ACC334455", LocalDateTime.parse("21/10/2018 12:00:00", Utils.DATE_TIME_FORMATTER), LocalDateTime.parse("22/10/2018 19:00:00", Utils.DATE_TIME_FORMATTER)); Assert.assertEquals(java.util.Optional.of(0), java.util.Optional.of(balancePair.getValue1())); Assert.assertEquals(java.util.Optional.of(new BigDecimal("0").negate()), java.util.Optional.of(balancePair.getValue0())); } @Test public void testReversalAccountBalance() { Pair<BigDecimal, Integer> balancePair = accountBalanceService.getAccountBalance(transactions, "ACC334455", LocalDateTime.parse("20/10/2018 12:00:00", Utils.DATE_TIME_FORMATTER), LocalDateTime.parse("20/10/2018 20:00:00", Utils.DATE_TIME_FORMATTER)); Assert.assertEquals(java.util.Optional.of(3), java.util.Optional.of(balancePair.getValue1())); Assert.assertEquals(java.util.Optional.of(new BigDecimal("25.00").negate()), java.util.Optional.of(balancePair.getValue0())); } } <file_sep>Run application with Main class in com.au.me package. Question has some mistake as AccountID: ACC334455 has 2 transactions in between 20/10/2018 12:00:00 and 20/10/2018 19:00:00 and the relative balance will be different what has mentioned in the question.
c9871b35b9d8603fc0c16c71f2ec27d662754e91
[ "Markdown", "Java" ]
5
Java
MadanHar/transaction
7ab412a11efac44e35759c7f907efd8ae28f26c8
80bf17086469a1b79e913833e4ac743c0c4f9e07
refs/heads/master
<file_sep>package tech.bedev.discordsrvutils.utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class PlayerUtil { public static void sendToAuthorizedPlayers(String msg) { for (Player p : Bukkit.getOnlinePlayers()) { if (p.hasPermission("discordsrvutils.log")) { p.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } } } } <file_sep># DiscordSRVUtils Here is the source code! feel free to make pull requests! Download: https://www.spigotmc.org/resources/discordsrvutils.85958/ <file_sep>package tech.bedev.discordsrvutils.events; import github.scarsz.discordsrv.DiscordSRV; import github.scarsz.discordsrv.dependencies.jda.api.JDA; import github.scarsz.discordsrv.dependencies.jda.api.entities.Role; import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.manager.TimeManager; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import tech.bedev.discordsrvutils.DiscordSRVUtils; import tech.bedev.discordsrvutils.utils.PlayerUtil; public class AdvancedBanListener implements Listener { private final DiscordSRVUtils core; public static JDA getJda() { return DiscordSRV.getPlugin().getJda(); } public AdvancedBanListener(DiscordSRVUtils core) { this.core = core; } @EventHandler public void onPlayerPunished(PunishmentEvent event) { Bukkit.getScheduler().runTask(core, () -> { String userId = DiscordSRV.getPlugin().getAccountLinkManager().getDiscordId(Bukkit.getOfflinePlayer(event.getPunishment().getName()).getUniqueId()); PunishmentType type = event.getPunishment().getType(); switch (type) { case BAN: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (!(userId == null)) { if (!(DiscordSRV.getPlugin().getMainGuild().getMemberById(userId) == null)) { DiscordSRV.getPlugin().getMainGuild().ban(userId, 0, "DiscordSRVUtils banned by advancedban").queue(); } } } if (core.getConfig().getBoolean("advancedban_ban_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_ban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) ).queue(); } break; } case MUTE: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (userId != null) { if (!(DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")) == null)) { DiscordSRV.getPlugin().getMainGuild().addRoleToMember(userId, DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role"))).queue(); } else { if (core.getConfig().getLong("muted_role") == 000000000000000000) { PlayerUtil.sendToAuthorizedPlayers("&CError: &eCould not give muted role to muted player because role is in it's default stats (000000000000000000)"); } else { PlayerUtil.sendToAuthorizedPlayers("&cError: &eMuted role id not found on the main guild."); } } } } if (core.getConfig().getBoolean("advancedban_mute_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_mute_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) ).queue(); } break; } case KICK: { break; } case TEMP_MUTE: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (!(userId == null)) { Role mutedRole = DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")); if (mutedRole != null) { DiscordSRV.getPlugin().getMainGuild().addRoleToMember(userId, mutedRole).queue(); } else { if (core.getConfig().getLong("muted_role") == 000000000000000000) { PlayerUtil.sendToAuthorizedPlayers("&cError: &eCould not give muted role to muted player because role is in its default state (000000000000000000)"); } else { PlayerUtil.sendToAuthorizedPlayers("&cError: &eMuted role id not found on the main guild."); } } } } if (core.getConfig().getBoolean("advancedban_temp_mute_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_temp_mute_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) .replace("[Duration]", event.getPunishment().getDuration(true)) ).queue(); } break; } case TEMP_BAN: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (userId != null) { if (!(DiscordSRV.getPlugin().getMainGuild().getMemberById(userId) == null)) { DiscordSRV.getPlugin().getMainGuild().ban(userId, 0, "DiscordSRVUtils banned by advancedban").queue(); } } } if (core.getConfig().getBoolean("advancedban_temp_ban_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_temp_ban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) .replace("[Duration]", event.getPunishment().getDuration(true)) ).queue(); } break; } case IP_BAN: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (userId != null) { if (!(DiscordSRV.getPlugin().getMainGuild().getMemberById(userId) == null)) { DiscordSRV.getPlugin().getMainGuild().ban(userId, 0, "DiscordSRVUtils banned by advancedban").queue(); } } } if (core.getConfig().getBoolean("advancedban_ip_ban_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_ip_ban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) ).queue(); } break; } case TEMP_IP_BAN: { if (core.getConfig().getBoolean("advancedban_punishments_to_discord")) { if (!(userId == null)) { if (!(DiscordSRV.getPlugin().getMainGuild().getMemberById(userId) == null)) { DiscordSRV.getPlugin().getMainGuild().ban(userId, 0, "DiscordSRVUtils banned by advancedban").queue(); } } } if (core.getConfig().getBoolean("advancedban_temp_ip_ban_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_temp_ip_ban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) .replace("[Duration]", event.getPunishment().getDuration(true)) ).queue(); } break; } } }); } @EventHandler public void onPlayerUnpunish(RevokePunishmentEvent event) { Bukkit.getScheduler().runTask(core, () -> { String userId = DiscordSRV.getPlugin().getAccountLinkManager().getDiscordId(Bukkit.getOfflinePlayer(event.getPunishment().getName()).getUniqueId()); PunishmentType type = event.getPunishment().getType(); Role muted = DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")); switch (type) { case BAN: { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } if (core.getConfig().getBoolean("advancedban_unban_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_unban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) ).queue(); } break; } case TEMP_BAN: { if (TimeManager.getTime() >= event.getPunishment().getEnd()) { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } } else { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } if (core.getConfig().getBoolean("advancedban_untempban_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_untempban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) .replace("[Reason]", event.getPunishment().getReason()) ).queue(); } } break; } case IP_BAN: { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } if (core.getConfig().getBoolean("advancedban_unipban_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_unipban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) ).queue(); } break; } case TEMP_IP_BAN: { if (TimeManager.getTime() >= event.getPunishment().getEnd()) { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } } else { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (userId != null) { DiscordSRV.getPlugin().getMainGuild().unban(userId).queue(); } } if (core.getConfig().getBoolean("advancedban_untempipban_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_untempipban_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) ).queue(); } } break; } case MUTE: if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")) == null) { PlayerUtil.sendToAuthorizedPlayers("&cError: &eCould not remove role from unmuted player because muted_role is not found on the guild."); } else { if (!(userId == null)) { DiscordSRV.getPlugin().getMainGuild().removeRoleFromMember(userId, muted).queue(); } } } if (core.getConfig().getBoolean("advancedban_unmute_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_unmute_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) ).queue(); } break; case TEMP_MUTE: if (TimeManager.getTime() >= event.getPunishment().getEnd()) { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")) == null) { PlayerUtil.sendToAuthorizedPlayers("&cError: &eCould not remove role from unmuted player because muted_role is not found on the guild."); } else { if (!(userId == null)) { DiscordSRV.getPlugin().getMainGuild().removeRoleFromMember(userId, DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role"))).queue(); } } } } else { if (core.getConfig().getBoolean("advancedban_unpunishments_to_discord")) { if (DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role")) == null) { PlayerUtil.sendToAuthorizedPlayers("&cError: &eCould not remove role from unmuted player because muted_role is not found on the guild."); } else { if (!(userId == null)) { DiscordSRV.getPlugin().getMainGuild().removeRoleFromMember(userId, DiscordSRV.getPlugin().getMainGuild().getRoleById(core.getConfig().getLong("muted_role"))).queue(); } } } if (core.getConfig().getBoolean("advancedban_untempmute_message_to_discord")) { DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(core.getConfig().getString("chat_channel")).sendMessage(String.join("\n", core.getConfig().getStringList("advancedban_untempmute_message")) .replace("[Player]", event.getPunishment().getName()) .replace("[Operator]", event.getPunishment().getOperator()) ).queue(); } } break; } }); } }
f8ed8792aa1d78775323036c398f101fd9e68887
[ "Markdown", "Java" ]
3
Java
Tominous/DiscordSRVUtils
9b5601623f7149392217d297395dfad95cbfbc7e
f002a69bf3402aa234abc5016c1a6af51345ffac
refs/heads/master
<file_sep>const temp = require('vue-template-compiler') const div = '<div>{{age}}</div>' console.log(temp.compile(div)) /* { ast: { type: 1, tag: 'div', attrsList: [], attrsMap: {}, rawAttrsMap: {}, parent: undefined, children: [ [Object] ], plain: true, static: false, staticRoot: false }, render: "with(this){return _c('div',[_v(_s(age))])}", staticRenderFns: [], errors: [], tips: [] } */<file_sep>主要还是基于染陌大佬的vue注释,然后自己看了一遍,自己做一些标志。 [染陌大佬的gitHub](https://github.com/answershuto)
c873317c35b3142cd1e7863df732ba37d8a50dcc
[ "JavaScript", "Markdown" ]
2
JavaScript
abstain23/learnVueResource
e3c1844a313fd0740bbeacc18ed8a86c3c5f5f51
6ed763de342d6c3934fe66d6e387b7b602f5166d
refs/heads/master
<repo_name>League-level3-student/level3-module0-Lonedragon513<file_sep>/src/_00_IntroToArrays/_01_RobotRace.java package _00_IntroToArrays; import java.util.Random; import javax.swing.JOptionPane; import org.jointheleague.graphical.robot.Robot; public class _01_RobotRace { //1. make a main method public static void main(String[] args) { //2. create an array of 5 robots. Robot[] Bb = new Robot[5]; //3. use a for loop to initialize the robots. for (int i = 0; i < Bb.length; i++) { Bb[i]= new Robot(); Bb[i].setSpeed(10000); Bb[i].miniaturize(); } //4. make each robot start at the bottom of the screen, side by side, facing up for (int i = 0; i < Bb.length; i++) { Bb[i].setX(100); Bb[i].setY(200); } //5. use another for loop to iterate through the array and make each robot move // a random amount less than 50. boolean isRacing=true; int FCYGVHBJB = 0; while (isRacing) { Random ran = new Random(); for (int i = 0; i < Bb.length; i++) { // Bb[i].move(ran.nextInt(49)+1); for (int j = 0; j < ran.nextInt(49)+1; j++) { Bb[i].move(1); Bb[i].turn(1); if(Bb[i].getY()==200&&Bb[i].getX()==100) { isRacing=false; FCYGVHBJB=i+1;break; } } //if(Bb[i].getY()<0) { } } //6. use a while loop to repeat step 5 until a robot has reached the top of the screen. //√ //7. declare that robot the winner and throw it a party! System.out.println("robot "+ FCYGVHBJB + " have won. yah."); //8. try different races with different amounts of robots. //9. make the robots race around a circular track. } }
bc3081dc7ed34100807e86b1bb54a78fcb4709f7
[ "Java" ]
1
Java
League-level3-student/level3-module0-Lonedragon513
db3565f7a082bfb982a0ca70868b17096b0007d9
073aeba952caa813a1a9a18e8d7319bb80c91e5d
refs/heads/master
<repo_name>NamLuu199/QlBanHang<file_sep>/QuanLyBanHang/CTHDNhap.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; namespace QuanLyBanHang { public partial class CTHDNhap : Form { public CTHDNhap() { InitializeComponent(); } DataClasses3DataContext db = new DataClasses3DataContext(); private void CTHDNhap_Load(object sender, EventArgs e) { textBox1.Text = Admin.maHD; var data = db.NhapKhos.Select(p => new { p.MaSP, p.TenSP, p.NCC, p.MaDV }); dataGridView1.DataSource = data; } private void button5_Click(object sender, EventArgs e) { var row = dataGridView1.CurrentRow; dataGridView2.Rows.Add(row.Cells[0].Value.ToString()); // add row } private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.Cancel) { MessageBox.Show("Done"); } } private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow dr in dataGridView2.Rows) { try { ChiTiet_HDNhap ct = new ChiTiet_HDNhap(); ct.MaHDB = textBox1.Text; ct.MaSP = dr.Cells[0].Value.ToString(); ct.GiaNhap = Convert.ToInt32(dr.Cells[1].Value.ToString()); ct.SoLuongNhap = Convert.ToInt32(dr.Cells[2].Value.ToString()); DateTime formatDate = DateTime.Parse(dr.Cells[3].Value.ToString()); // get date ct.NgayHetHan = formatDate; db.ChiTiet_HDNhaps.InsertOnSubmit(ct); db.SubmitChanges(); } catch(NullReferenceException) { // check ngoại lệ trường null } } MessageBox.Show("Thêm hóa đơn thành công"); this.Close(); } private void label1_Click(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { textBox1.Text = Admin.maHD; string ten = textBox5.Text; var data = db.NhapKhos.Where(x => x.TenSP.Contains(ten) || x.MaSP.Contains(ten) ).Select(p => new { p.MaSP, p.TenSP, p.NCC, p.MaDV }); dataGridView1.DataSource = data; } private void button6_Click(object sender, EventArgs e) { int selectedCount = dataGridView2.SelectedRows.Count; while (selectedCount > 0) { if (!dataGridView2.SelectedRows[0].IsNewRow) dataGridView2.Rows.RemoveAt(dataGridView2.SelectedRows[0].Index); selectedCount--; } } } } <file_sep>/QuanLyBanHang/CTHD_Ban.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 app = Microsoft.Office.Interop.Excel.Application; using style = Microsoft.Office.Interop.Excel.Workbook; namespace QuanLyBanHang { public partial class CTHD_Ban : Form { public CTHD_Ban() { InitializeComponent(); } DataClasses3DataContext db = new DataClasses3DataContext(); DataClasses3DataContext db2 = new DataClasses3DataContext(); private void CTHD_Ban_Load(object sender, EventArgs e) { textBox1.Text = Admin.maHD; var q5 = from xk in db.XuatKhos join nk in db.NhapKhos on xk.MaSP equals nk.MaSP select new { xk.MaSP,xk.MaQuay, xk.TenQuay, nk.TenSP, nk.GiaBan, xk.SoLuongXuat }; dataGridView1.DataSource = q5; } private void button5_Click(object sender, EventArgs e) { var row = dataGridView1.CurrentRow; dataGridView2.Rows.Add(row.Cells[0].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[4].Value.ToString()); // add row } private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow dr in dataGridView2.Rows) { try { ChiTiet_HDBan ct = new ChiTiet_HDBan(); ct.MaHD = textBox1.Text; ct.MaSP = dr.Cells[0].Value.ToString(); ct.SoLuong = Convert.ToInt32(dr.Cells[3].Value.ToString()); ct.GiaBan = Convert.ToInt32(dr.Cells[2].Value.ToString()); ct.ThanhTien = Convert.ToInt32(dr.Cells[4].Value.ToString()); db.ChiTiet_HDBans.InsertOnSubmit(ct); db.SubmitChanges(); } catch (NullReferenceException) { // check ngoại lệ trường null } } MessageBox.Show("Thêm hóa đơn thành công"); this.Close(); } private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { int sum = 0; foreach (DataGridViewRow item in dataGridView2.Rows) { int n = item.Index; dataGridView2.Rows[n].Cells[4].Value = ( int.Parse(dataGridView2.Rows[n].Cells[2].Value.ToString()) * int.Parse(dataGridView2.Rows[n].Cells[3].Value.ToString())).ToString(); sum += Convert.ToInt32(dataGridView2.Rows[n].Cells[4].Value.ToString()); textBox2.Text = sum.ToString(); } } catch(NullReferenceException) { } catch(FormatException) { MessageBox.Show("Nhập sai kiểu dữ liệu"); } } private void textBox5_TextChanged(object sender, EventArgs e) { string text = textBox5.Text; var q5 = from xk in db.XuatKhos join nk in db.NhapKhos on xk.MaSP equals nk.MaSP where nk.MaSP.Contains(text) || nk.TenSP.Contains(text) select new { xk.MaQuay, xk.TenQuay, xk.MaSP, nk.TenSP, nk.GiaBan, xk.SoLuongXuat }; dataGridView1.DataSource = q5; } private void button2_Click(object sender, EventArgs e) { app obj = new app(); obj.Application.Workbooks.Add(Type.Missing); obj.Columns.ColumnWidth = 25; // get header text colmumns obj.Cells[1, 1] = "Hóa Đơn bán hàng"; obj.Cells[2, 1] = "Tên khách hàng: "; obj.Cells[2, 2] = Admin.TenKH; obj.Cells[2, 3] = "Ngày: "; obj.Cells[2, 4] = Convert.ToDateTime(Admin.date).ToString("dd/MM/yyyy"); int dem = 5; Microsoft.Office.Interop.Excel.Worksheet x = obj.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet; x.Range[obj.Cells[1, 1], obj.Cells[1, 4]].Merge(); for (int i = 2; i < dataGridView2.Columns.Count; i++) { obj.Cells[3, i - 1] = dataGridView2.Columns[i - 1].HeaderText; } for (int i = 0; i < dataGridView2.Rows.Count; i++) { for (int j = 1; j < dataGridView2.Columns.Count - 1; j++) { if (dataGridView2.Rows[i].Cells[j].Value != null) { obj.Cells[i + 4, j] = dataGridView2.Rows[i].Cells[j].Value.ToString(); dem += i; } } } obj.Cells[dem, 1] = "Tổng tiền: "; obj.Cells[dem, 2] = string.Format("{0:#,##0}", textBox2.Text) + " VNĐ"; obj.Columns.AutoFit(); obj.Visible = true; } private void button6_Click(object sender, EventArgs e) { int selectedCount = dataGridView2.SelectedRows.Count; while (selectedCount > 0) { if (!dataGridView2.SelectedRows[0].IsNewRow) dataGridView2.Rows.RemoveAt(dataGridView2.SelectedRows[0].Index); selectedCount--; } } } } <file_sep>/QuanLyBanHang/dangnhap.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; namespace QuanLyBanHang { public partial class dangnhap : Form { public static string SetValueForText1 = ""; public static string checkQuyen =""; public static string MaNV = ""; public dangnhap() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Bạn chưa nhập đủ username và password"); }else { DataClasses3DataContext data = new DataClasses3DataContext(); var admin = data.NhanViens.Where(p => p.username.Contains(textBox1.Text) && p.password.Contains(textBox2.Text)).Select(p => new {p.MaNV, p.TenNhanVien,p.username, p.password, p.MaQuyen }); if (admin.Any()) { Admin ad = new Admin(); foreach(var item in admin) { SetValueForText1 = item.TenNhanVien; MaNV = item.MaNV; checkQuyen = item.MaQuyen; } ad.Show(); this.Hide(); } if(!admin.Any()) { MessageBox.Show("Kiểm tra lại username và password"); } } } private void dangnhap_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { } } } <file_sep>/QuanLyBanHang/XemHD_Nhap.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; namespace QuanLyBanHang { public partial class XemHD_Nhap : Form { public XemHD_Nhap() { InitializeComponent(); } string id; DataClasses3DataContext db = new DataClasses3DataContext(); private void XemHD_Nhap_Load(object sender, EventArgs e) { load_ct(); } private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { } public void load_ct() { var q1 = from nt in db.ChiTiet_HDNhaps join nk in db.NhapKhos on nt.MaSP equals nk.MaSP where nt.MaHDB == Admin.maHD select new { nk.MaSP, nk.TenSP, nt.GiaNhap, nt.SoLuongNhap, nt.NgayHetHan, nt.ID }; dataGridView1.DataSource = q1; dataGridView1.Columns[5].Visible = false; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; textBox1.Text = row.Cells[0].Value.ToString(); textBox2.Text = row.Cells[2].Value.ToString(); textBox4.Text = row.Cells[3].Value.ToString(); id = row.Cells[5].Value.ToString(); DateTime formatDate = DateTime.Parse(row.Cells[4].Value.ToString()); // get date dateTimePicker1.Value = formatDate; } } private void button1_Click(object sender, EventArgs e) { DateTime formatDate = DateTime.Parse(dateTimePicker1.Text); // get date var nk = db.ChiTiet_HDNhaps.Single(p => p.ID == Convert.ToInt32(id)); nk.MaSP = textBox1.Text; nk.GiaNhap = Convert.ToInt32(textBox2.Text); nk.SoLuongNhap = Convert.ToInt32(textBox4.Text); nk.NgayHetHan = formatDate; db.SubmitChanges(); load_ct(); } private void button2_Click(object sender, EventArgs e) { } } } <file_sep>/QuanLyBanHang/Admin.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QuanLyBanHang { public partial class Admin : Form { public static string maHD = ""; public static string TenKH = ""; public static string date = ""; public Admin() { InitializeComponent(); } DataClasses3DataContext db = new DataClasses3DataContext(); private void tabPage1_Click(object sender, EventArgs e) { } private void Admin_Load(object sender, EventArgs e) { textBox13.Text = textBox6.Text = dangnhap.SetValueForText1; // Lấy tên nhân viên textBox6.Enabled = textBox13.Enabled = false; var load_quyen = db.Quyens.Select(p => new { p.MaQuyen, p.TenQuyen }); comboBox1.DataSource = load_quyen; comboBox1.DisplayMember = "TenQuyen"; comboBox1.ValueMember = "MaQuyen"; // Show data nhanvien var q = db.NhanViens.Select(p => new { p.MaNV, p.TenNhanVien, p.DiaChi, p.SoDienThoai, p.MaQuyen, p.username, p.password }); dataGridView4.DataSource = q; // Show data NCC var q2 = db.NCCs.Select(p => new { p.MaNCC, p.TenNCC, p.SoDienThoai, p.DiaChi }); dataGridView5.DataSource = q2; // Show data Donvi var q3 = db.DonVis.Select(p => new { p.MaDV, p.TenDV }); dataGridView6.DataSource = q3; // Show kho sp var q4 = from nk in db.NhapKhos join ncc in db.NCCs on nk.MaNCC equals ncc.MaNCC join dv in db.DonVis on nk.MaDV equals dv.MaDV select new { nk.MaSP, nk.TenSP, dv.TenDV, nk.GiaBan, ncc.TenNCC }; dataGridView1.DataSource = q4; comboBox3.DataSource = q3; comboBox3.DisplayMember = "TenDV"; comboBox3.ValueMember = "MaDV"; comboBox2.DataSource = q2; comboBox2.DisplayMember = "TenNCC"; comboBox2.ValueMember = "MaNCC"; // Show khi sp xuất var q6 = from hd in db.HDNhaps join nv in db.NhanViens on hd.MaNV equals nv.MaNV select new { hd.MaHDB, nv.TenNhanVien, hd.NgayNhap }; dataGridView7.DataSource = q6; var q5 = from xk in db.XuatKhos join nk in db.NhapKhos on xk.MaSP equals nk.MaSP select new { xk.MaQuay, xk.TenQuay, xk.MaSP,nk.TenSP,nk.GiaBan, xk.SoLuongXuat }; dataGridView2.DataSource = q5; // show hd bán var q7 = from hd in db.HDBans join nv in db.NhanViens on hd.MaNV equals nv.MaNV select new { hd.MaHD, nv.TenNhanVien, hd.TenKhachHang, hd.date }; dataGridView3.DataSource = q7; // show sản phẩm đã nhập var q8 = from ct in db.ChiTiet_HDNhaps join nk in db.NhapKhos on ct.MaSP equals nk.MaSP select new { ct.MaHDB, nk.TenSP, ct.GiaNhap, ct.SoLuongNhap, ct.NgayHetHan }; dataGridView8.DataSource = q8; // show tổng số lượng theo mặt hàng var q9 = from ct in db.ChiTiet_HDNhaps join nk in db.NhapKhos on ct.MaSP equals nk.MaSP group ct by new { nk.TenSP,nk.MaSP,ct.GiaNhap } into kq select new { MaSP= kq.Key.MaSP, TenSP=kq.Key.TenSP,GiaNhap= kq.Key.GiaNhap, TongSL=kq.Sum(t=>t.SoLuongNhap) }; dataGridView9.DataSource = q9; // Custom layout with permission int convertInt = Convert.ToInt32(dangnhap.checkQuyen); if(convertInt == 1) { tabControl1.TabPages.Remove(tabPage4); tabControl1.TabPages.Remove(tabPage5); tabControl1.TabPages.Remove(tabPage7); } } private void tabPage4_Click(object sender, EventArgs e) { } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { } private void dataGridView4_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { } private void button21_Click(object sender, EventArgs e) { } public void load_ncc() { var q2 = db.NCCs.Select(p => new { p.MaNCC, p.TenNCC, p.SoDienThoai, p.DiaChi }); dataGridView5.DataSource = q2; } private void button16_Click(object sender, EventArgs e) { NCC ncc = new NCC(); ncc.MaNCC = textBox27.Text; ncc.TenNCC = textBox26.Text; ncc.SoDienThoai = textBox25.Text; ncc.DiaChi = textBox24.Text; db.NCCs.InsertOnSubmit(ncc); db.SubmitChanges(); load_ncc(); } private void button15_Click(object sender, EventArgs e) { NCC ncc = db.NCCs.Single(p => p.MaNCC == textBox27.Text); db.NCCs.DeleteOnSubmit(ncc); db.SubmitChanges(); } private void tabControl1_TabIndexChanged(object sender, EventArgs e) { var q = db.NCCs.Select(p => new { p.MaNCC, p.TenNCC, p.SoDienThoai, p.DiaChi }); dataGridView5.DataSource = q; } private void tabPage3_Click(object sender, EventArgs e) { } private void button20_Click(object sender, EventArgs e) { ChiTietHoaDon ct = new ChiTietHoaDon(); ct.Show(); } public void loadnv() { var nv = db.NhanViens.Select(p => new { p.MaNV, p.TenNhanVien, p.DiaChi, p.SoDienThoai, p.MaQuyen, p.username, p.password }); dataGridView4.DataSource = nv; } private void button14_Click(object sender, EventArgs e) { comboBox1.ValueMember = "MaQuyen"; // lọc lại giá trị nhận về NhanVien nv = new NhanVien(); nv.MaNV = textBox19.Text; nv.TenNhanVien = textBox18.Text; nv.DiaChi = textBox17.Text; nv.SoDienThoai = textBox16.Text; nv.username = textBox20.Text; nv.password = <PASSWORD>; nv.MaQuyen = comboBox1.SelectedValue.ToString(); db.NhanViens.InsertOnSubmit(nv); db.SubmitChanges(); loadnv(); } private void button13_Click(object sender, EventArgs e) { var nv = db.NhanViens.Single(p => p.MaNV == textBox19.Text); nv.TenNhanVien = textBox18.Text; nv.DiaChi = textBox17.Text; nv.SoDienThoai = textBox16.Text; nv.username = textBox20.Text; nv.password = <PASSWORD>; nv.MaQuyen = comboBox1.SelectedValue.ToString(); db.SubmitChanges(); loadnv(); } private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView4.Rows[e.RowIndex]; textBox19.Text = row.Cells[0].Value.ToString(); textBox18.Text = row.Cells[1].Value.ToString(); textBox17.Text = row.Cells[2].Value.ToString(); textBox16.Text = row.Cells[3].Value.ToString(); textBox20.Text = row.Cells[5].Value.ToString(); textBox15.Text = row.Cells[6].Value.ToString(); } } private void button12_Click(object sender, EventArgs e) { var nv = db.NhanViens.Single(p => p.MaNV == textBox19.Text); db.NhanViens.DeleteOnSubmit(nv); db.SubmitChanges(); loadnv(); } private void button11_Click(object sender, EventArgs e) { var ncc = db.NCCs.Single(p => p.MaNCC == textBox27.Text); db.NCCs.DeleteOnSubmit(ncc); db.SubmitChanges(); load_ncc(); } private void dataGridView5_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView5.Rows[e.RowIndex]; textBox27.Text = row.Cells[0].Value.ToString(); textBox26.Text = row.Cells[1].Value.ToString(); textBox25.Text = row.Cells[2].Value.ToString(); textBox24.Text = row.Cells[3].Value.ToString(); } } public void load_dv() { var q3 = db.DonVis.Select(p => new { p.MaDV, p.TenDV }); dataGridView6.DataSource = q3; } private void button19_Click(object sender, EventArgs e) { DonVi dv = new DonVi(); dv.MaDV = textBox30.Text; dv.TenDV = textBox29.Text; db.DonVis.InsertOnSubmit(dv); db.SubmitChanges(); load_dv(); } private void dataGridView6_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView6.Rows[e.RowIndex]; textBox30.Text = row.Cells[0].Value.ToString(); textBox29.Text = row.Cells[1].Value.ToString(); } } private void button18_Click(object sender, EventArgs e) { var dv = db.DonVis.Single(p => p.MaDV == textBox30.Text); dv.MaDV = textBox30.Text; dv.TenDV = textBox29.Text; db.SubmitChanges(); load_dv(); } private void button17_Click(object sender, EventArgs e) { var dv = db.DonVis.Single(p => p.MaDV == textBox30.Text); db.DonVis.DeleteOnSubmit(dv); db.SubmitChanges(); load_dv(); } public void loadkho() { var q4 = from nk in db.NhapKhos join ncc in db.NCCs on nk.MaNCC equals ncc.MaNCC join dv in db.DonVis on nk.MaDV equals dv.MaDV select new { nk.MaSP, nk.TenSP, dv.TenDV, nk.GiaBan, ncc.TenNCC }; dataGridView1.DataSource = q4; } private void button1_Click(object sender, EventArgs e) { try { comboBox3.ValueMember = "MaDV"; // lọc lại giá trị nhận về comboBox2.ValueMember = "MaNCC"; // lọc lại giá trị nhận về NhapKho nk = new NhapKho(); nk.MaSP = textBox1.Text; nk.TenSP = textBox2.Text; nk.GiaBan = Convert.ToInt32(textBox4.Text); nk.MaDV = comboBox3.SelectedValue.ToString(); nk.MaNCC = comboBox2.SelectedValue.ToString(); db.NhapKhos.InsertOnSubmit(nk); db.SubmitChanges(); loadkho(); } catch(SqlException) { MessageBox.Show("Khóa chính đã tồn tại"); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; textBox1.Text = row.Cells[0].Value.ToString(); textBox2.Text = row.Cells[1].Value.ToString(); comboBox3.Text = row.Cells[2].Value.ToString(); comboBox2.Text = row.Cells[4].Value.ToString(); textBox4.Text = row.Cells[3].Value.ToString(); } } private void button2_Click(object sender, EventArgs e) { comboBox3.ValueMember = "MaDV"; // lọc lại giá trị nhận về comboBox2.ValueMember = "MaNCC"; // lọc lại giá trị nhận về var nk = db.NhapKhos.Single(p => p.MaSP == textBox1.Text); nk.MaSP = textBox1.Text; nk.TenSP = textBox2.Text; nk.GiaBan = Convert.ToInt32(textBox4.Text); nk.MaDV = comboBox3.SelectedValue.ToString(); nk.MaNCC = comboBox2.SelectedValue.ToString(); db.SubmitChanges(); loadkho(); } private void button3_Click(object sender, EventArgs e) { var nk = db.NhapKhos.Single(p => p.MaSP == textBox1.Text); db.NhapKhos.DeleteOnSubmit(nk); db.SubmitChanges(); loadkho(); } private void button4_Click(object sender, EventArgs e) { tabControl1.SelectedTab = tabPage2; var row = dataGridView1.CurrentRow; textBox8.Text = row.Cells[0].Value.ToString(); } private void tabPage2_Click(object sender, EventArgs e) { } public void xuatkho() { var q5 = from xk in db.XuatKhos join nk in db.NhapKhos on xk.MaSP equals nk.MaSP select new { xk.MaQuay, xk.TenQuay, xk.MaSP, nk.TenSP, nk.GiaBan, xk.SoLuongXuat }; dataGridView2.DataSource = q5; } private void button7_Click(object sender, EventArgs e) { try { int number = Convert.ToInt32(textBox22.Text); XuatKho xk = new XuatKho(); xk.MaQuay = textBox10.Text; xk.TenQuay = textBox9.Text; xk.MaSP = textBox8.Text; xk.SoLuongXuat = number; db.XuatKhos.InsertOnSubmit(xk); db.SubmitChanges(); xuatkho(); // Update số lượng kho // DataClasses3DataContext db2 = new DataClasses3DataContext(); //var update = db2.NhapKhos.Single(p => p.MaSP == textBox8.Text); // update.SoLuongNhap = update.SoLuongNhap - number; // db2.SubmitChanges(); //loadkho(); } catch(SqlException ex) { if (ex.Number == 2627) { MessageBox.Show("Mã SP đã tồn tại"); } if (ex.Number == 2601) // Cannot insert duplicate key row in object error { MessageBox.Show("Mã SP đã tồn tại"); // handle duplicate key error return; } } } private void label32_Click(object sender, EventArgs e) { } private void textBox22_TextChanged(object sender, EventArgs e) { } private void button6_Click(object sender, EventArgs e) { var xk = db.XuatKhos.Single(p => p.MaQuay == textBox10.Text); xk.MaQuay = textBox10.Text; xk.TenQuay = textBox9.Text; xk.MaSP = textBox8.Text; xk.SoLuongXuat = Convert.ToInt32(textBox22.Text); db.SubmitChanges(); xuatkho(); } private void button5_Click(object sender, EventArgs e) { var xk = db.XuatKhos.Single(p => p.MaQuay == textBox10.Text); db.XuatKhos.DeleteOnSubmit(xk); db.SubmitChanges(); xuatkho(); } private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView2.Rows[e.RowIndex]; textBox10.Text = row.Cells[0].Value.ToString(); textBox9.Text = row.Cells[1].Value.ToString(); textBox8.Text = row.Cells[2].Value.ToString(); textBox22.Text = row.Cells[5].Value.ToString(); } } private void button10_Click(object sender, EventArgs e) { DateTime formatDate = DateTime.Parse(dateTimePicker2.Text); // get date HDBan hd = new HDBan(); hd.MaHD = maHD = textBox14.Text; hd.date = formatDate; date = formatDate.ToString(); hd.MaNV = dangnhap.MaNV; hd.TenKhachHang = TenKH = textBox12.Text; db.HDBans.InsertOnSubmit(hd); db.SubmitChanges(); CTHD_Ban ct = new CTHD_Ban(); ct.Show(); } private void button24_Click(object sender, EventArgs e) { try { DateTime formatDate = DateTime.Parse(dateTimePicker1.Text); // get date HDNhap hd = new HDNhap(); hd.MaHDB = maHD = textBox7.Text; hd.MaNV = dangnhap.MaNV; hd.NgayNhap = formatDate; db.HDNhaps.InsertOnSubmit(hd); db.SubmitChanges(); CTHDNhap ct = new CTHDNhap(); ct.Show(); } catch(SqlException) { MessageBox.Show("Mã Hóa Đơn đã tồn tại"); } } private void dataGridView7_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button21_Click_1(object sender, EventArgs e) { XemHD_Nhap view = new XemHD_Nhap(); view.Show(); } private void dataGridView7_MouseClick(object sender, MouseEventArgs e) { } private void dataGridView7_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView7.Rows[e.RowIndex]; maHD = row.Cells[0].Value.ToString(); } } private void dataGridView3_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView3.Rows[e.RowIndex]; maHD = row.Cells[0].Value.ToString(); TenKH = row.Cells[2].Value.ToString(); date = row.Cells[3].Value.ToString(); } } private void tabControl2_DrawItem(object sender, DrawItemEventArgs e) { Graphics g = e.Graphics; Brush _textBrush; // Get the item from the collection. TabPage _tabPage = tabControl2.TabPages[e.Index]; // Get the real bounds for the tab rectangle. Rectangle _tabBounds = tabControl2.GetTabRect(e.Index); if (e.State == DrawItemState.Selected) { // Draw a different background color, and don't paint a focus rectangle. _textBrush = new SolidBrush(Color.Black); g.FillRectangle(Brushes.Gray, e.Bounds); } else { _textBrush = new System.Drawing.SolidBrush(e.ForeColor); e.DrawBackground(); } // Use our own font. Font _tabFont = new Font("Arial", (float)10.0, FontStyle.Bold, GraphicsUnit.Pixel); // Draw string. Center the text. StringFormat _stringFlags = new StringFormat(); _stringFlags.Alignment = StringAlignment.Center; _stringFlags.LineAlignment = StringAlignment.Center; g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags)); } private void label38_Click(object sender, EventArgs e) { } private void textBox5_KeyUp(object sender, KeyEventArgs e) { string Name = textBox5.Text; string codeSP = Name; var q4 = from nk in db.NhapKhos join ncc in db.NCCs on nk.MaNCC equals ncc.MaNCC join dv in db.DonVis on nk.MaDV equals dv.MaDV where nk.TenSP.Contains(Name) || nk.MaSP.Contains(codeSP) select new { nk.MaSP, nk.TenSP, dv.TenDV, nk.GiaBan, ncc.TenNCC }; dataGridView1.DataSource = q4; } public void load_HDBan() { var q7 = from hd in db.HDBans join nv in db.NhanViens on hd.MaNV equals nv.MaNV select new { hd.MaHD, nv.TenNhanVien, hd.TenKhachHang, hd.date }; dataGridView3.DataSource = q7; } private void button8_Click(object sender, EventArgs e) { var nk = db.HDBans.Single(p => p.MaHD == maHD); db.HDBans.DeleteOnSubmit(nk); db.SubmitChanges(); load_HDBan(); } public void load_HDNhap() { DateTime formatDate = DateTime.Parse(dateTimePicker1.Text); // get date var q6 = from hd in db.HDNhaps join nv in db.NhanViens on hd.MaNV equals nv.MaNV select new { hd.MaHDB, nv.TenNhanVien, hd.NgayNhap }; dataGridView7.DataSource = q6; } private void button22_Click(object sender, EventArgs e) { var nk = db.HDNhaps.Single(p => p.MaHDB == maHD); // xóa hd; db.HDNhaps.DeleteOnSubmit(nk); db.SubmitChanges(); load_HDNhap(); } private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button26_Click(object sender, EventArgs e) { DateTime startDate = DateTime.Parse(dateTimePicker3.Text); // get date DateTime endDate = DateTime.Parse(dateTimePicker4.Text); // get date var q1 = from nt in db.ChiTiet_HDBans join nk in db.NhapKhos on nt.MaSP equals nk.MaSP join hd in db.HDBans on nt.MaHD equals hd.MaHD join hdn in db.ChiTiet_HDNhaps on nt.MaSP equals hdn.MaSP where hd.date >= startDate && hd.date <= endDate select new { nk.TenSP,hdn.GiaNhap,nt.GiaBan, nt.SoLuong, nt.ThanhTien }; dataGridView10.DataSource = q1; int sumTotal =0; int sumCapital = 0; int sumReal = 0; foreach (DataGridViewRow item in dataGridView10.Rows) { int n = item.Index; sumTotal += Convert.ToInt32(dataGridView10.Rows[n].Cells[4].Value.ToString()); sumCapital += Convert.ToInt32(dataGridView10.Rows[n].Cells[1].Value.ToString())* Convert.ToInt32(dataGridView10.Rows[n].Cells[3].Value.ToString()); } sumReal = sumTotal - sumCapital; label45.Text = string.Format("{0:#,##0}", sumTotal)+ " VNĐ"; label46.Text = string.Format("{0:#,##0}", sumCapital) + " VNĐ"; label47.Text = string.Format("{0:#,##0}", sumReal) + " VNĐ"; } } } <file_sep>/QuanLyBanHang/ChiTietHoaDon.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 app = Microsoft.Office.Interop.Excel.Application; using style = Microsoft.Office.Interop.Excel.Workbook; namespace QuanLyBanHang { public partial class ChiTietHoaDon : Form { public ChiTietHoaDon() { InitializeComponent(); } string id; private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; textBox1.Text = row.Cells[0].Value.ToString(); textBox4.Text = row.Cells[2].Value.ToString(); textBox6.Text = row.Cells[3].Value.ToString(); id = row.Cells[5].Value.ToString(); } } private void button1_Click(object sender, EventArgs e) { } DataClasses3DataContext db = new DataClasses3DataContext(); private void ChiTietHoaDon_Load(object sender, EventArgs e) { load_bliss(); try { int sum = 0; foreach (DataGridViewRow item in dataGridView1.Rows) { int n = item.Index; dataGridView1.Rows[n].Cells[4].Value = ( int.Parse(dataGridView1.Rows[n].Cells[2].Value.ToString()) * int.Parse(dataGridView1.Rows[n].Cells[3].Value.ToString())).ToString(); sum += Convert.ToInt32(dataGridView1.Rows[n].Cells[4].Value.ToString()); } label5.Text = string.Format("{0:#,##0}", sum) + " VNĐ"; } catch (NullReferenceException) { } } public void load_bliss() { var q1 = from nt in db.ChiTiet_HDBans join nk in db.NhapKhos on nt.MaSP equals nk.MaSP where nt.MaHD == Admin.maHD select new { nk.MaSP, nk.TenSP, nt.GiaBan, nt.SoLuong, nt.ThanhTien,nt.ID }; dataGridView1.DataSource = q1; dataGridView1.Columns[5].Visible = false; } private void button4_Click(object sender, EventArgs e) { app obj = new app(); obj.Application.Workbooks.Add(Type.Missing); obj.Columns.ColumnWidth = 25; // get header text colmumns obj.Cells[1, 1] = "<NAME>"; obj.Cells[2, 1] = "Tên khách hàng: "; obj.Cells[2, 2] = Admin.TenKH; obj.Cells[2, 3] = "Ngày: "; obj.Cells[2, 4] = Convert.ToDateTime(Admin.date).ToString("dd/MM/yyyy"); int dem = 2; Microsoft.Office.Interop.Excel.Worksheet x = obj.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet; x.Range[obj.Cells[1, 1], obj.Cells[1, 4]].Merge(); for (int i = 2; i < dataGridView1.Columns.Count; i++) { obj.Cells[3, i - 1] = dataGridView1.Columns[i - 1].HeaderText; } for (int i = 0; i < dataGridView1.Rows.Count ; i++) { for (int j = 1; j < dataGridView1.Columns.Count - 1; j++) { if (dataGridView1.Rows[i].Cells[j].Value != null) { obj.Cells[i + 4, j] = dataGridView1.Rows[i].Cells[j].Value.ToString(); dem += i; } } } obj.Cells[dem, 1] = "Tổng tiền: "; obj.Cells[dem,2] = label5.Text; obj.Columns.AutoFit(); obj.Visible = true; } private void button2_Click(object sender, EventArgs e) { var nk = db.ChiTiet_HDBans.Single(p => p.ID == Convert.ToInt32(id)); nk.MaSP = textBox1.Text; nk.GiaBan = Convert.ToInt32(textBox4.Text); nk.SoLuong = Convert.ToInt32(textBox6.Text); int thanhtien = Convert.ToInt32(textBox4.Text) * Convert.ToInt32(textBox6.Text); nk.ThanhTien = thanhtien; db.SubmitChanges(); load_bliss(); } private void button3_Click(object sender, EventArgs e) { var nk = db.ChiTiet_HDBans.Single(p => p.ID == Convert.ToInt32(id)); db.ChiTiet_HDBans.DeleteOnSubmit(nk); db.SubmitChanges(); load_bliss(); } } }
2d0329d2b4eb5306720b2821f01d1a2f0ea3d4d7
[ "C#" ]
6
C#
NamLuu199/QlBanHang
8305a7a0c64ff63d1591d221f617e01c8ab1edfb
855b07b5d13be5cd3e71b1c5d5c01af65a2aab22
refs/heads/master
<repo_name>bildr-org/e-paper<file_sep>/ePaper/ePaper.h #ifndef ePaper_h #define ePaper_h // Include the standard types #include <Arduino.h> // Define the Shifter class class ePaper { public: // Constructor ePaper(int EIO1pin, int XCKpin, int LATCHpin, int SLEEPBpin, int DI0pin); void writeDisplay(); void writeBottom(char * characterData); void writeTop(char * characterData); void writeNumberBottom(long input); void writeNumberTop(long input); private: void clock(); void latch(); void print(char * displayTop, char * displayBottom, int bw, int com); void flipData(char * characterData); void createData(char * characterData, char * toDisplay); char topData[160]; char bottomData[160]; char bottomInput[10]; int _EIO; int _XCK; int _LATCH; int _SLPB; int _DI0; }; #endif //Shifter_h<file_sep>/ePaper/ePaper.cpp // Include the standard types #include <Arduino.h> #include <ePaper.h> #define BLACK_BG 1 #define WHITE_BG 0 unsigned int chars[95] = { // abcdefgh ijklmnop (B00000000 << 8) + B00000000, // (space) (B00000001 << 8) + B00000001, // ! (B00000001 << 8) + B00010000, // " (B10111011 << 8) + B11011101, // # (B10011011 << 8) + B11011001, // $ (B01011011 << 8) + B11011010, // % (B00010101 << 8) + B11011101, // & (B00000001 << 8) + B00000000, // ` (B10000011 << 8) + B10000000, // ( (B00000001 << 8) + B11000001, // ) (B01010101 << 8) + B10101010, // * (B00010001 << 8) + B10001000, // + (B00000000 << 8) + B00000010, // , (B00010000 << 8) + B00001000, // - (B00000000 << 8) + B00000001, // . (B01000000 << 8) + B00000010, // / // abcdefgh ijklmnop (B10101010 << 8) + B01010101, // 0 (B01101000 << 8) + B00000000, // 1 (B10110010 << 8) + B01001101, // 2 (B10111010 << 8) + B01000001, // 3 (B00111000 << 8) + B00011000, // 4 (B10000110 << 8) + B01011001, // 5 (B10011010 << 8) + B01011101, // 6 (B11000000 << 8) + B01000010, // 7 (B10111010 << 8) + B01011101, // 8 (B10111010 << 8) + B01011001, // 9 (B00000000 << 8) + B01001000, // : (B00000000 << 8) + B01001010, // ; (B01000100 << 8) + B00000000, // < (B00010010 << 8) + B00001001, // = (B00000000 << 8) + B00100010, // > (B10110000 << 8) + B11000000, // ? (B10111010 << 8) + B11010101, // @ // abcdefgh ijklmnop (B10111000 << 8) + B01011100, // A (B10111011 << 8) + B11000001, // B (B10000010 << 8) + B01010101, // C (B10101011 << 8) + B11000001, // D (B10000010 << 8) + B01011101, // E (B10000000 << 8) + B01011100, // F (B10011010 << 8) + B01010101, // G (B00111000 << 8) + B00011100, // H (B10000011 << 8) + B11000001, // I (B00101010 << 8) + B00000101, // J (B01000100 << 8) + B00011100, // K (B00000010 << 8) + B00010101, // L (B01101000 << 8) + B00110100, // M (B00101100 << 8) + B00110100, // N (B10101010 << 8) + B01010101, // O (B10110000 << 8) + B01011100, // P (B10101110 << 8) + B01010101, // Q (B10110100 << 8) + B01011100, // R (B10011010 << 8) + B01011001, // S (B10000001 << 8) + B11000000, // T (B00101010 << 8) + B00010101, // U (B01000000 << 8) + B00010110, // V (B00101100 << 8) + B00010110, // W (B01000100 << 8) + B00100010, // X (B01000000 << 8) + B10100000, // Y (B11000010 << 8) + B01000011, // Z (B10000010 << 8) + B01010101, // [ (B00000100 << 8) + B00100000, // (B10101010 << 8) + B01000001, // ] (B00000100 << 8) + B00000010, // ^ (B00000010 << 8) + B00000001, // _ (B00000001 << 8) + B00000000, // ` // abcdefgh ijklmnop (B00000010 << 8) + B10001101, // a (B00000000 << 8) + B10011101, // b (B00000000 << 8) + B00001101, // c (B00000001 << 8) + B10001101, // d (B00000000 << 8) + B00001111, // e (B10010001 << 8) + B10001000, // f (B00000001 << 8) + B11011001, // g (B00000000 << 8) + B10011100, // h (B10000000 << 8) + B10000000, // i (B00000001 << 8) + B10000001, // j (B00010101 << 8) + B10000000, // k (B00000001 << 8) + B10000000, // l (B00011000 << 8) + B10001100, // m (B00011000 << 8) + B10001000, // n (B00000000 << 8) + B10001101, // o (B00000001 << 8) + B01011100, // p (B00000011 << 8) + B11011000, // q (B00010000 << 8) + B10000000, // r (B00010110 << 8) + B00000000, // s (B00010001 << 8) + B10001000, // t (B00000010 << 8) + B10000101, // u (B00000000 << 8) + B00000110, // v (B00001010 << 8) + B10000101, // w (B01000100 << 8) + B00100010, // x (B00000001 << 8) + B10011001, // y (B00000000 << 8) + B00001011, // z (B00000000 << 8) + B00000000, // { (B00000000 << 8) + B00000000, // | (B00000000 << 8) + B00000000, // } (B00000000 << 8) + B00000000 // ~*/ // abcdefgh ijklmnop }; char topData[160]; char bottomData[160]; // Constructor ePaper::ePaper(int EIO, int XCK, int LATCH, int SLPB, int DI0) { _EIO = EIO; _XCK = XCK; _LATCH = LATCH; _SLPB = SLPB; _DI0 = DI0; pinMode(_EIO, OUTPUT); pinMode(_XCK, OUTPUT); pinMode(_LATCH, OUTPUT); pinMode(_SLPB, OUTPUT); pinMode(_DI0, OUTPUT); // Initial Pin Configurations ----------------------- digitalWrite(_SLPB, HIGH); // Sleep high turns the display on digitalWrite(_DI0, HIGH); // Initialize data high digitalWrite(_XCK, LOW); digitalWrite(_EIO, HIGH); digitalWrite(_LATCH, LOW); } void ePaper::flipData(char * characterData) { char a; for (int i=0; i<80; i++) { a = characterData[i]; characterData[i] = characterData[159-i]; characterData[159-i] = a; } } void ePaper::print(char * displayTop, char * displayBottom, int bw, int com) { digitalWrite(_EIO, LOW); if (bw) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); delayMicroseconds(1); clock(); // Y0 digitalWrite(_EIO, HIGH); for (int i = 0; i<160; i++) { if (bw) { if (displayBottom[i]) digitalWrite(_DI0, LOW); else digitalWrite(_DI0, HIGH); delayMicroseconds(1); clock(); } else { if (displayBottom[i]) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); delayMicroseconds(1); clock(); } } if (com) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); clock(); // Y161 //--- 2nd display --- if (bw) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); clock(); // Y0 for (int i = 0; i<160; i++) { if (bw) { if (displayTop[i]) digitalWrite(_DI0, LOW); else digitalWrite(_DI0, HIGH); delayMicroseconds(1); clock(); } else { if (displayTop[i]) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); delayMicroseconds(1); clock(); } } if (com) digitalWrite(_DI0, HIGH); else digitalWrite(_DI0, LOW); delayMicroseconds(1); clock(); // Y161 latch(); } void ePaper::clock() { digitalWrite(_XCK, HIGH); delayMicroseconds(1); digitalWrite(_XCK, LOW); delayMicroseconds(1); } void ePaper::latch() { digitalWrite(_LATCH, HIGH); delayMicroseconds(5); digitalWrite(_LATCH, LOW); delayMicroseconds(5); } void ePaper::writeNumberTop(long input) { sprintf(topData, "%10ld", input); createData(topData, topData); } void ePaper::writeNumberBottom(long input) { sprintf(bottomData, "%10ld", input); createData(bottomData, bottomData); } void ePaper::writeTop(char * characterData) { sprintf(topData, "%-10s", characterData); createData(topData, topData); } void ePaper::writeBottom(char * characterData) { sprintf(bottomData, "%-10s", characterData); createData(bottomData, bottomData); } void ePaper::writeDisplay() { flipData(topData); // If data is not flipped, it will look upside down. // in the following calls, use WHITE_BG for a white background or // BLACK_BG for a black background print(topData, bottomData, WHITE_BG, 1); delay(100); print(topData, bottomData, WHITE_BG, 1); delay(500); print(topData, bottomData, WHITE_BG, 0); delay(100); print(topData, bottomData, WHITE_BG, 0); } void ePaper::createData(char * characterData, char * toDisplay) { for (int i=0; i<10; i++) { int n = chars[toDisplay[i]-32]; for (int j=15; j>=0; j--) { characterData[(9-i)*16 + j] = n & 1; n = n >> 1; } } } <file_sep>/ePaper_Example.ino #include "ePaper.h" // This file includes defines for each displayable character int EIOpin = 8; // Input/output pin for chip selection int XCKpin = 9; // Clock input pin for taking display data int LATCHpin = 10; // Latch pulse input pin for display data int SLEEPBpin = 11; // Sleep Pin for the display int DI0pin = 12; // Input pin for display data //setup display with pin definitions ePaper epaper = ePaper(EIOpin, XCKpin, LATCHpin, SLEEPBpin, DI0pin); void setup(){ Serial.begin(9600); epaper.writeTop("Random"); epaper.writeBottom("Numbers"); epaper.writeDisplay(); delay(5000); } void loop(){ long top = random(2147483646); long bottom = random(2147483646); epaper.writeNumberTop(top); epaper.writeNumberBottom(bottom); epaper.writeDisplay(); delay(5000); }
0c0e41715c088b307fd26d266dc825acecf98a0e
[ "C++" ]
3
C++
bildr-org/e-paper
fb9b2ef33d5e64c66eceb14af281b90b8717c99c
58990798becdda3c1373957cb54febd783e7da34
refs/heads/master
<repo_name>jinadpatel/Assignment-3<file_sep>/serverfinal.js /*{ "node": true, "camelcase": true, "indent": 4, "undef": true, "quotmark": "single", "maxlen": 80, "trailing": true "curly": true, "eqeqeq": true, "forin": true, "immed": true, "latedef": true, "newcap": true, "nonew": true, "unused": true, "strict": true }*/ var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var http = require('http'); app.use(express.static('.')); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/', function(req, res) { res.sendFile(__dirname + "/" + "index.html"); }); var urlencodedParser = bodyParser.urlencoded({ extended: false }); app.post('/maxnumber', urlencodedParser, function(req, res) { // Prepare output in JSON format var maxnum = [{ "no1": "100" }, { "no1": "200" }, { "no1": "300" }, { "no1": "400" }, { "no1": "500" }]; function maxnumber(maxnum) { var max = 0; var i = 0; arrlength = maxnum.length; for (i = 0; i < arrlength; i++) { var value = Number(maxnum[i].no1); if (value > max) { max = value; } } res.send(JSON.stringify({ "max": max, })); } maxnumber(maxnum); }); app.post('/averageNumber', urlencodedParser, function(req, res) { var avgnum = [{ "num2": "1" }, { "num2": "2" }, { "num2": "3" }, { "num2": "4" }, { "num2": "5" }]; function findaveragenumber(avgnum) { var averageNumber = 0; var avgresult = 0; var avgarrlength = avgnum.length; for (var i = 0; i < avgarrlength; i++) { averageNumber = averageNumber + Number(avgnum[i]["num2"]); } avgresult = averageNumber / avgarrlength; res.send(JSON.stringify({ "avg": avgresult, })); } findaveragenumber(avgnum); }); app.post('/oneevenNumber', urlencodedParser, function(req, res) { var evennum = [{ "num3": "1" }, { "num3": "2" }, { "num3": "3" }, { "num3": "4" }, { "num3": "5" }]; function evennumber(evennum) { var evenarrlength = evennum.length; for (var i = 0; i < evenarrlength; i++) { var check = Number(evennum[i]["num3"]); if (check % 2 === 0) { res.end(JSON.stringify({ "result": "true" })); } } res.end(JSON.stringify({ "result": "false" })); } evennumber(evennum); }); app.post('/allevenNumber', urlencodedParser, function(req, res) { var allevennum = [{ "num4": "2" }, { "num4": "4" }, { "num4": "6" }, { "num4": "8" }, { "num4": "10" }]; function checkwheatheralleven(allevennum) { var allevenarrlength = allevennum.length; for (var i = 0; i < allevenarrlength; i++) { var check = Number(allevennum[i]["num4"]); if (check % 2 === 1) { res.send(JSON.stringify({ "result1": "false" })); } } res.send(JSON.stringify({ "result1": "true" })); } checkwheatheralleven(allevennum); }); app.post('/getTwiceString/:string1', function(req, res) { var somevar = req.params.string1; var stringchecktwice = [{ "num5": "red" }, { "num5": "blue" }, { "num5": "blue" }, { "num5": "green" }, { "num5": "yellow" }, { "num5": "red" }]; function findStringInArrayTwice(stringchecktwice, somevar) { var stringlength = stringchecktwice.length; for (var i = 0; i < stringlength; i++) { console.log("------++++-----" + req.params.string1); if (somevar.trim() === (String(stringchecktwice[i][ "num5" ]).trim())) { for (var j = i + 1; j < stringlength; j++) { if (somevar.trim() === (String(stringchecktwice[ j]["num5"]).trim())) { console.log("------++++-----" + req.params.string1); res.end(JSON.stringify({ "result": "true" })); } } } } res.end(JSON.stringify({ "result": "false" })); } findStringInArrayTwice(stringchecktwice, somevar); }); app.post('/checkstringonce/:string2', function(req, res) { var somevar2 = req.params.string2; var stringcheckonce = [{ "num6": "red" }, { "num6": "blue" }, { "num6": "green" }, { "num6": "yellow" }, ]; function findStringInArrayOnce(stringcheckonce, somevar2) { var stringlength = stringcheckonce.length; for (var i = 0; i < stringlength; i++) { console.log("------++++-----" + req.params.string2); if (somevar2.trim() === (String(stringcheckonce[i][ "num6" ]).trim())) { res.end(JSON.stringify({ "result1": "true" })); } } res.end(JSON.stringify({ "result1": "false" })); } findStringInArrayOnce(stringcheckonce, somevar2); }); app.listen(3000); console.log("listening to port 3000");
5e3efc7b0c8c495b836e41161f1aa4b9b6142b6f
[ "JavaScript" ]
1
JavaScript
jinadpatel/Assignment-3
f8201f6f9e46ad0b7177c239f2abd7095e29bfd5
a99b1e78061863e7fa7e74577ef93c1d32920042
refs/heads/master
<repo_name>shaybuzz/MalshinunCrashesExample<file_sep>/app/src/main/java/com/sw/malshinuncrashesexample/ExampleApp.kt package com.sw.malshinuncrashesexample import android.app.Application import com.malshinun_crashes.MalshinunCrashes class ExampleApp : Application() { override fun onCreate() { super.onCreate() MalshinunCrashes(this) } }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/AppLifeCycleHandler.kt package com.malshinun_crashes import android.app.Activity import android.app.Application import android.os.Bundle import android.os.Handler import java.lang.ref.WeakReference internal class AppLifeCycleHandler(private val appOnForeground: (Boolean) -> Unit) : Application.ActivityLifecycleCallbacks { private val delay = 500L private val handler = Handler() private var isResumed = false private var wasOnBackground = true lateinit var lastActivity: WeakReference<Activity> private set //wait each pause - wait for next activity resume - to avoid call back when pausing from activity to another activity override fun onActivityPaused(activity: Activity) { isResumed = false handler.postDelayed({ //may resume from passing to another activity if (!isResumed) { appOnForeground.invoke(false) wasOnBackground = true } }, delay) } override fun onActivityStarted(activity: Activity) { } override fun onActivityDestroyed(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityStopped(activity: Activity) { } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { lastActivity = WeakReference(activity) } override fun onActivityResumed(activity: Activity) { isResumed = true handler.postDelayed({ if (isResumed && wasOnBackground) { wasOnBackground = false appOnForeground.invoke(true) } }, delay) } }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/SenderManger.kt package com.malshinun_crashes import android.os.Handler import android.util.Log import com.google.gson.Gson import com.malshinun_crashes.model.MiscData import com.malshinun_crashes.remote.ReportApi import com.malshinun_crashes.repository.ReportRepository import java.util.concurrent.ExecutorService import java.util.concurrent.Executors internal class SenderManger( private val reportApi: ReportApi, private val reportRepository: ReportRepository, private val miscData: MiscData, private val interval: Long ) : Runnable { private val TAG = SenderManger::class.java.simpleName private val executorService: ExecutorService = Executors.newFixedThreadPool(1) private val handler = Handler() private var isCanceled = false fun reporting(enabled: Boolean) { if (enabled) { isCanceled = false handler.post(this) } else { isCanceled = true handler.removeCallbacks(this) } } override fun run() { if (!isCanceled) { executorService.execute { sendReportTask() } handler.postDelayed(this@SenderManger, interval) } } fun sendReportTask() { val report = reportRepository.getReport() report?.let { lastReport -> try { //add the miscData before sending to server //no need to save/load such data in the repository lastReport.miscData = miscData val response = reportApi.sendReport(Gson().toJson(lastReport)).execute() if (response.isSuccessful) { //after sending the report to the server we can remove it from our local repository reportRepository.delete(lastReport) } else { //dont remove the report and try to send it next time Log.e(TAG, "failed sending report") } } catch (e: Throwable) { Log.e(TAG, "Some error while sending report to server ${e.message}") } } } }<file_sep>/settings.gradle include ':malshinun-crashes' include ':app' rootProject.name = "MalshinunCrashesExample"<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/remote/ReportApi.kt package com.malshinun_crashes.remote import com.malshinun_crashes.model.Report import retrofit2.Call import retrofit2.http.Body import retrofit2.http.POST internal interface ReportApi { @POST("api/exceptions") fun sendReport(@Body report: String): Call<Void> }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/repository/ReportRepository.kt package com.malshinun_crashes.repository import com.malshinun_crashes.model.Report internal interface ReportRepository { fun saveReport(report: Report) fun getReport(): Report? fun delete(report: Report) }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/MalshinunCrashes.kt package com.malshinun_crashes import android.app.Application import android.content.Context import android.util.Log import com.malshinun_crashes.Consts.DEFAULT_OS_HANDLER_PKG_NAME import com.malshinun_crashes.Consts.ONE_MINUTE import com.malshinun_crashes.Consts.SDK_PACKAGE_NAME import com.malshinun_crashes.model.MiscData import com.malshinun_crashes.model.Report import com.malshinun_crashes.remote.Network import com.malshinun_crashes.repository.ReportRepository import com.malshinun_crashes.repository.ReportRepositoryImpl class MalshinunCrashes(private val context: Context) { private val TAG = MalshinunCrashes::class.java.simpleName private var oldHandler: Thread.UncaughtExceptionHandler? = null private val reportApi = Network.reportApi private val reportRepository: ReportRepository = ReportRepositoryImpl(context) private val miscData = MiscData(Utils.getPackage(context), Utils.getVersionName(context)) private val senderManger = SenderManger(reportApi, reportRepository, miscData, ONE_MINUTE) private val appLifeCycleHandler: AppLifeCycleHandler = AppLifeCycleHandler { isOnForeground -> senderManger.reporting(isOnForeground) } init { try { oldHandler = Thread.getDefaultUncaughtExceptionHandler() if (oldHandler != null && oldHandler!!.javaClass.name.startsWith(SDK_PACKAGE_NAME)) { //our sdk handler Log.d(TAG, "sdk handler") } else if (oldHandler != null && oldHandler!!.javaClass.name.startsWith( DEFAULT_OS_HANDLER_PKG_NAME ) ) { //android os default handler Log.d(TAG, "os handler") } registerToAppLifeCycleCallBack() handleUncaughtException() } catch (throwable: Throwable) { Log.e(TAG, "failed to report crash ${throwable.message}") } } private fun registerToAppLifeCycleCallBack() { (context.applicationContext as Application).registerActivityLifecycleCallbacks( appLifeCycleHandler ) } private fun handleUncaughtException() { Thread.setDefaultUncaughtExceptionHandler({ thread, throwable -> val report = Report.toReport(throwable) reportRepository.saveReport(report) oldHandler?.uncaughtException(thread, throwable) finishLastActivity() exit() }) } private fun finishLastActivity() { appLifeCycleHandler.lastActivity.get()?.let { lastActivity -> lastActivity.finish() appLifeCycleHandler.lastActivity.clear() } } private fun exit() { android.os.Process.killProcess(android.os.Process.myPid()); System.exit(2) } }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/Consts.kt package com.malshinun_crashes internal object Consts { const val ONE_MINUTE = 60000L const val SDK_PACKAGE_NAME = "com.malshinun_crashes" const val DEFAULT_OS_HANDLER_PKG_NAME = "com.android.internal.os" }<file_sep>/app/src/main/java/com/sw/malshinuncrashesexample/OtherActivity.kt package com.sw.malshinuncrashesexample import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.other_activity.* import java.lang.IllegalStateException import java.lang.RuntimeException class OtherActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.other_activity) btnThrowException.setOnClickListener { throw IllegalStateException("some invalid state exception") } btnThrow2.setOnClickListener { throw RuntimeException("some run time exception") } btnThrow3.setOnClickListener { throw NullPointerException("some null pointer exception") } btnCatchException.setOnClickListener { try { throw IllegalArgumentException("Argument not valid") }catch (exception:IllegalArgumentException){ Toast.makeText(this, "caught exception ${exception.message}", Toast.LENGTH_SHORT).show() Log.e("OtherActivity", "caught exception ${exception.message} $exception") } } } }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/remote/Network.kt package com.malshinun_crashes.remote import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory internal object Network { private val BASE_URL = "http://localhost:9000/" val reportApi by lazy { retrofit.create(ReportApi::class.java) } private val okHttpClient = OkHttpClient.Builder().build() private val retrofit = Retrofit.Builder().client(okHttpClient).baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build() } <file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/repository/ReportRepositoryImpl.kt package com.malshinun_crashes.repository import android.content.Context import com.malshinun_crashes.Consts.SDK_PACKAGE_NAME import com.malshinun_crashes.model.Report internal class ReportRepositoryImpl(context: Context) : ReportRepository { private val PREFERENCE_FILE_NAME = "$SDK_PACKAGE_NAME-crash-reports" //implementing repository by writing/reading local share preferences with private mode //where the time when crash accord (its a string format) is part of the report info //and acts as the key in the sharepref for that crash private val sharedPref = context.applicationContext.getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE) override fun saveReport(report: Report) { sharedPref.edit().putString(report.time, report.stackTrace).apply() } override fun getReport(): Report? { sharedPref.all.keys.firstOrNull()?.let { time -> sharedPref.getString(time, null)?.let { stackTrace -> return Report( time, stackTrace ) } } return null } override fun delete(report: Report) { sharedPref.edit().remove(report.time).apply() } }<file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/model/Report.kt package com.malshinun_crashes.model import android.os.Build import java.io.PrintWriter import java.io.StringWriter import java.util.* internal data class Report(val time: String, val stackTrace: String) { var miscData: MiscData? = null companion object { fun toReport(throwable: Throwable): Report { val time = Date().time.toString() val sw = StringWriter() throwable.printStackTrace(PrintWriter(sw)) return Report( time, sw.toString() ) } } } //General data about the device and the hosting app internal data class MiscData( val packageName: String, val appVersion: String, val manufacturer: String = Build.MANUFACTURER, val model: String = Build.MODEL, val version: Int = Build.VERSION.SDK_INT, val versionRelease: String = Build.VERSION.RELEASE ) <file_sep>/malshinun-crashes/src/main/java/com/malshinun_crashes/Utils.kt package com.malshinun_crashes import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager internal object Utils { fun getPackage(context: Context):String{ return context.applicationContext.packageName } fun getVersionName(context: Context): String { try { return getPackageInfo(context.applicationContext)?.versionName ?: "not found" } catch (e: PackageManager.NameNotFoundException) { return "not found" } } fun getPackageInfo(context: Context): PackageInfo? { return context.applicationContext.packageManager.getPackageInfo(getPackage(context), 0) } }<file_sep>/malshinun-crashes/src/test/java/com/malshinun_crashes/SenderManagerTest.kt package com.malshinun_crashes import com.google.gson.Gson import com.malshinun_crashes.model.MiscData import com.malshinun_crashes.model.Report import com.malshinun_crashes.remote.ReportApi import com.malshinun_crashes.repository.ReportRepository import com.nhaarman.mockitokotlin2.* import okhttp3.ResponseBody import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import retrofit2.Call import retrofit2.Response @RunWith(JUnit4::class) class SenderManagerTest { private val serverResponse: Call<Void> = mock() private val reportApi: ReportApi = mock() { on { sendReport(any()) } doReturn serverResponse } private val reportRepository: ReportRepository = mock() private val miscData: MiscData = MiscData("somename", "someVersion", "manufactor", "model", 1, "version") private val interval = 10000L private val report: Report = Report("some time", "some stackTrace") private val reportJsonStr: String = Gson().toJson(report) private lateinit var senderManger: SenderManger @Before fun setup() { senderManger = SenderManger(reportApi, reportRepository, miscData, interval) } @Test fun `check positive scenario`() { whenever(reportRepository.getReport()).doReturn(report) whenever(reportApi.sendReport(reportJsonStr)).thenReturn(serverResponse) whenever(serverResponse.execute()).thenReturn(Response.success<Void>(null)) senderManger.sendReportTask() verify(reportApi).sendReport(reportJsonStr) verify(reportRepository).delete(report) } @Test fun `check server returns error scenario`() { whenever(reportRepository.getReport()).doReturn(report) whenever(reportApi.sendReport(reportJsonStr)).thenReturn(serverResponse) whenever(serverResponse.execute()).thenReturn( Response.error( 400, ResponseBody.create(null, "error") ) ) senderManger.sendReportTask() verify(reportApi).sendReport(reportJsonStr) verify(reportRepository, never()).delete(report) } @Test fun `check repository return no report`() { whenever(reportRepository.getReport()).doReturn(null) senderManger.sendReportTask() verify(reportApi, never()).sendReport(reportJsonStr) verify(reportRepository, never()).delete(report) } }
08da2879eaf57392891ea07329179491ab3f47a5
[ "Kotlin", "Gradle" ]
14
Kotlin
shaybuzz/MalshinunCrashesExample
d8d189aa206a459886c9da71a702075472cb9559
a07c4b45a8db16e6f62f3a0477cc07097de0181f
refs/heads/master
<repo_name>gcollazo/cyclejs-starter-kit<file_sep>/app/index.js import './style/app.css'; import Rx from 'rx'; import { run } from '@cycle/core'; import { makeDOMDriver, h1 } from '@cycle/dom'; function main() { return { DOM: Rx.Observable.of( h1('Welcome to Cycle.js') ) }; } const drivers = { DOM: makeDOMDriver('#app') }; run(main, drivers); <file_sep>/README.md # cyclejs-starter-kit A template for starting [Cycle.js](http://cycle.js.org/) projects. I made this to help me create toy project while learning Cycle.js. Based on [survivejs/cycle-starter](https://github.com/survivejs/cycle-starter). ## Start here * `git clone https://github.com/gcollazo/cyclejs-starter-kit.git your-project-name` * `cd your-project-name` * `npm install` ## Running * `npm start` * Visit your app at [http://localhost:8080](http://localhost:8080) ## Building * `npm run build`
7ecb9cbb924ce571c25dce61c1ec47b0b6ee628f
[ "JavaScript", "Markdown" ]
2
JavaScript
gcollazo/cyclejs-starter-kit
04d94e239d8c9759b60af2a427349b03771cb78c
b02d52d1583a17aba9846189ddb2828b7eb08830
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # coding=utf-8 def slowprint(s): for c in s + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(0.1 / 100) logo = """\x1b[32m ▄▄▌ ▄▄ • ▄▄ • ▄▄▄ .▄▄▄ ██• ▪ ▐█ ▀ ▪▐█ ▀ ▪▀▄.▀·▀▄ █· ██▪ ▄█▀▄ ▄█ ▀█▄▄█ ▀█▄▐▀▀▪▄▐▀▀▄ ▐█▌▐▌▐█▌.▐▌▐█▄▪▐█▐█▄▪▐█▐█▄▄▌▐█•█▌ .▀▀▀ ▀█▄▀▪·▀▀▀▀ ·▀▀▀▀ ▀▀▀ .▀ ▀\x1b[00m """ def header(): os.system('clear') slowprint(logo) print('Logger creator tools by \x1b[33mIqbalmh18') print('\x1b[33m1. \x1b[00mCreate Logger') print('\x1b[33m2. \x1b[00mEdit logger') print('\x1b[33m3. \x1b[00mRemove logger') print('\x1b[33m4. \x1b[00mRead source code') print('\x1b[33m0. \x1b[00mExit') print('\x1b[00m') main() def main(): dog=input('\x1b[00mLogger®Creator\x1b[32m > \x1b[33m') if dog == '': print('\x1b[00mCommand not found\x1b[91m!') main() elif dog == '1': print('') print('\x1b[00mPlease login with Account Google') u=input('\x1b[00mInput your username: \x1b[33m') p=input('\x1b[00mInput your password: \x1b[33m') s=input('\x1b[00mInput your subject : \x1b[33m') t=input('\x1b[00mSend mail to : \x1b[33m') b1=("""'"""+u+"""'"""+""","""+"""'"""+p+"""'"""+""")""") b2=("subject="+"""'"""+s+"""'""") print('\x1b[33m') b3=("""'"""+t+"""'"""+""","""+"subject"+""","""+"body"+""")""") b4=("") b5=("main"+"""("""+""")""") print('Creating logger code, please wait ...') os.system('sleep 3') os.system('cat log1 > logger.py;echo "'+b1+'" >> logger.py;echo "'+b2+'" >> logger.py;cat log2 >> logger.py;echo "'+b3+'" >> logger.py;print "'+b4+'" >> logger.py;print "'+b5+'" >> logger.py;cat logger.py > /sdcard/logger.py') slowprint('\x1b[00mSuccess, file auto saved as \x1b[33m/sdcard/logger.py') os.system('xdg-open https://instagram.com/Ongky559') elif dog == '2': os.system('nano logger.py') main() elif dog == '3': os.system('rm logger.py') print('\x1b[00mLogger has been removed \x1b[91m!') os.system('sleep 3') header() elif dog == '4': os.system('cat logger.py') main() elif dog == '0': os.system('xdg-open https://instagram.com/saydog.official;exit') else: print('\x1b[00mCommand not found\x1b[91m!') main() header()
4ca165165a3091fa649b4002c2c88f9bd39bb51f
[ "Python" ]
1
Python
Y0HAN28/Logger
613de633334affde878325de4487e5432c11f8b8
edc109ea60ec9d2af68a98d9a5d66e7180d1079f
refs/heads/master
<repo_name>FBurakY/JavaPersistence-API<file_sep>/JPAWeek03/src/test/EmployeeTest9.java package test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.Employee; import repository.EmployeeRepository; import repository.EmployeeRepositoryImpl; public class EmployeeTest9 { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); EntityManager entityManager = emf.createEntityManager(); EmployeeRepository empRepository = new EmployeeRepositoryImpl(entityManager); Employee employee = new Employee(); employee.setName("<NAME>"); employee.setSurname("Yurtsever"); employee.setSalary(5000); Map<String, String> phones = new HashMap<>(); phones.put("HOME", "216100"); phones.put("WORK", "216200"); phones.put("MOBILE", "555588"); employee.setPhoneNumbers(phones); empRepository.save(employee); } } <file_sep>/JPAWeek03/src/repository/EmployeeRepositoryImpl.java package repository; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import entity.Company; import entity.Department; import entity.Employee; import entity.ParkingSpace; import entity.Phone; import entity.Project; public class EmployeeRepositoryImpl implements EmployeeRepository { private EntityManager entityManager; public EmployeeRepositoryImpl(EntityManager entityManager) { super(); this.entityManager = entityManager; } @Override public void save(Employee employee) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(employee); transaction.commit(); } @Override public void insertDepartment(Department department) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(department); transaction.commit(); } @Override public void insertParkingSpace(ParkingSpace parkingSpace) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(parkingSpace); transaction.commit(); } @Override public void insertPhone(Phone phone) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(phone); transaction.commit(); } @Override public void insertProject(Project project) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(project); transaction.commit(); } @Override public void insertCompany(Company company) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(company); transaction.commit(); } } <file_sep>/JPAWeek01/src/test/TestEmployeeDAO.java package test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import dao.EmployeeDAO; import domain.Employee; public class TestEmployeeDAO { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); EntityManager entityManager = emf.createEntityManager(); EmployeeDAO empDAO = new EmployeeDAO(entityManager); // Employee employee1 = new Employee(1, "<NAME>", "Yurtsever", 5000); Employee employee2 = new Employee(2, "Mehtap", "Çam", 10000); System.out.println("inserting....."); empDAO.saveEmployee(employee1); empDAO.saveEmployee(employee2); System.out.println("inserting... ok"); System.out.println("finding...."); Employee foundEmployee = empDAO.findEmployeeById(2); System.out.println(foundEmployee); System.out.println("Get all...."); empDAO.findAllEmployees().forEach(System.out::println); System.out.println("Deleting..."); //empDAO.removeEmployee(2); // System.out.println("updating..."); empDAO.raiseSalary(1, 3000); foundEmployee = empDAO.findEmployeeById(1); System.out.println(foundEmployee); } } <file_sep>/JPAWeek03/src/repository/EmployeeRepository.java package repository; import entity.Company; import entity.Department; import entity.Employee; import entity.ParkingSpace; import entity.Phone; import entity.Project; public interface EmployeeRepository { public void save(Employee employee); public void insertDepartment(Department department); public void insertParkingSpace(ParkingSpace parkingSpace); public void insertPhone(Phone phone); public void insertProject(Project project); public void insertCompany(Company company); } <file_sep>/JPAWeek03/src/test/EmployeeTest.java package test; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.Department; import entity.Employee; import entity.EmployeeType; import entity.ParkingSpace; import repository.EmployeeRepository; import repository.EmployeeRepositoryImpl; public class EmployeeTest { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); // EntityManagerFactory emf = // Persistence.createEntityManagerFactory("EmployeePersistenceUnitForHibernate"); EntityManager entityManager = emf.createEntityManager(); EmployeeRepository empRepository = new EmployeeRepositoryImpl(entityManager); Employee employee = new Employee(); employee.setName("<NAME>"); employee.setSurname("Yurtsever"); employee.setSalary(15000); EmployeeType empType = EmployeeType.PART_TIME; employee.setEmployeeType(empType); Date today = new Date(); employee.setStartDate(today); byte[] imageData = "content".getBytes(); employee.setImage(imageData); Department department = new Department(); department.setDeptName("IT - Dept"); empRepository.insertDepartment(department); ParkingSpace parkingSpace = new ParkingSpace(); parkingSpace.setFlat(-1); parkingSpace.setLocation("A-10"); ParkingSpace parkingSpace2 = new ParkingSpace(); parkingSpace2.setFlat(-2); parkingSpace2.setLocation("B-20"); empRepository.insertParkingSpace(parkingSpace); empRepository.insertParkingSpace(parkingSpace2); employee.setDepartment(department); employee.setParkingSpace(parkingSpace); empRepository.save(employee); Employee employee2 = new Employee(); employee2.setName("Mehtap"); employee2.setSurname("C"); employee2.setSalary(5000); employee2.setEmployeeType(EmployeeType.PART_TIME); employee2.setDepartment(department); //employee2.setParkingSpace(parkingSpace); employee2.setParkingSpace(parkingSpace2); empRepository.save(employee2); entityManager.close(); emf.close(); } } <file_sep>/JPAWeek03/src/notes/RelationShipNotes.java package notes; public class RelationShipNotes { } // bir Entity Relationship icin; // 1 - Role // 2 - Directionality // 3 - Cardinality // 4 - Ordinality / Optionality // ROLE // bir iliskide 2 tarafin varligi gerekli/soz konusudur. // her iliski icin 2 tane Entity vardir. // Employee - Department // DIRECTIONALITY // - Unidirectional // - BiDirectional // bir iliskide , 2 entityden sadece birisi digerini gosteriyorsa/point bu durumda Unidirectionaldir. // birbirlerini gosteriyorsa bidirectionaldir. // CARDINALITY // Cardinal -> onemli , asil , nicelik // bir Employee/calisan , sadece 1 departmana bagli olabilir./calisir // 1 departmanda N tane employee/calisan olabilir. // 1 Employee N tane Phone olabilir. // 1 Phone sadece 1 Employee ya aittir. // 1 Employe N tane Project/projede calisabilir. // 1 Project/projede M tane Employee/calsian olabilir. // cardinality kavramindan kastimiz ; // bir iliskideki su ifadelerdir; // OneToOne // OneToMany // ManyToOne // ManyToMany // ORDINALITY / OPTIONALITY // zorunlu/mandotary ya da secimlik/optional olup olmamasi ile ilgili bir kavramdir. // Customer - BillingInfo // her customer icin billinginfo olmak zorunda degildir. // BillingInfo bizim icin zorunlu degil. optional/secimliktir. // Single-valued RelationShip // @OneToOne // @ManyToOne // Collection-valued Relationship // @ManyToMany // @OneToMany <file_sep>/JPAWeek03/src/test/EmployeeTest2.java package test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.Employee; import entity.ParkingSpace; import repository.EmployeeRepository; import repository.EmployeeRepositoryImpl; public class EmployeeTest2 { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); EntityManager entityManager = emf.createEntityManager(); EmployeeRepository empRepository = new EmployeeRepositoryImpl(entityManager); Employee employee = new Employee(); employee.setName("<NAME>"); employee.setSurname("Yurtsever"); employee.setSalary(5000); ParkingSpace parkingSpace = new ParkingSpace(); parkingSpace.setFlat(-1); parkingSpace.setLocation("A-10"); parkingSpace.setEmployee(employee); empRepository.insertParkingSpace(parkingSpace); employee.setParkingSpace(parkingSpace); empRepository.save(employee); ParkingSpace foundPs = entityManager.find(ParkingSpace.class, 1); System.out.println(foundPs); } } <file_sep>/JPAWeek03/src/test/EmployeeTest4.java package test; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.Employee; import entity.Phone; import repository.EmployeeRepository; import repository.EmployeeRepositoryImpl; public class EmployeeTest4 { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); EntityManager entityManager = emf.createEntityManager(); EmployeeRepository empRepository = new EmployeeRepositoryImpl(entityManager); Employee employee = new Employee(); employee.setName("<NAME>"); employee.setSurname("Yurtsever"); employee.setSalary(15000); Phone phone1 = new Phone("553052", "MOBILE"); Phone phone2 = new Phone("312200", "HOME"); Phone phone3 = new Phone("312500", "WORK"); empRepository.insertPhone(phone1); empRepository.insertPhone(phone2); empRepository.insertPhone(phone3); employee.getPhones().add(phone1); employee.getPhones().add(phone2); employee.getPhones().add(phone3); empRepository.save(employee); } } <file_sep>/JPAWeek03/src/test/EmployeeTest6.java package test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.Address; import entity.Employee; import repository.EmployeeRepository; import repository.EmployeeRepositoryImpl; public class EmployeeTest6 { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePersistenceUnit"); EntityManager entityManager = emf.createEntityManager(); EmployeeRepository empRepository = new EmployeeRepositoryImpl(entityManager); Employee employee = new Employee(); employee.setName("<NAME>"); employee.setSurname("Yurtsever"); employee.setSalary(5000); Address address = new Address("stree1", "road1", "no1", "istanbul", "34000"); employee.setAddress(address); empRepository.save(employee); } }
3fd545553a3daf901a9f261af81804b9788adcde
[ "Java" ]
9
Java
FBurakY/JavaPersistence-API
7fa739f9d79f91196138c71b8a957d5af4776fd2
273cfe6e17419a909bd828b7feb84f6378cd1816
refs/heads/master
<repo_name>newForinux/SIMPLE-Flutter<file_sep>/android/app/src/main/kotlin/edu/handong/simple_flutter/MainActivity.kt package edu.handong.simple_flutter import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
ad5f92c166583b7e27abcc2364e76e2a8c6c568f
[ "Kotlin" ]
1
Kotlin
newForinux/SIMPLE-Flutter
ac58200883e4dc2a08628c79aed71af625503b52
54be090e80665b2cc711e14e4fbc6fe63dd73104
refs/heads/master
<repo_name>imclab/John-Smith<file_sep>/README.md <NAME> Extension ==================== What ---- Install it from here: [Homepage](http://pzwart3.wdka.hro.nl/wiki/Networked_Media_Sampler/Based_on_a_true_story/best_group) Chrome Extension that replaces every username with "John Smith", and every profile picture with the default avatar, on Facebook and Google+.<file_sep>/Chrome/johnSmith/googleplus.js function johnSmithIt() { jQuery(".Hf, .c-i-Cc-Dr, .eQ, .uo, .JywKwb, .proflink, .fn, .kb, .tD, .uD, .c-W-yq").each(function() { jQuery(this).text("<NAME>"); }); jQuery(".Fn, .c-Ob-jy, .c-i-Cc-Dk, .fQ, .B-J-pc-ja, .g-PyX6, .CVZgrc, .dk, .KM, .c-W-nr, .c-W-tq").not(".B-J-pc-ja-C .B-J-pc-ja").each(function() { jQuery(this).attr("src", "//ssl.gstatic.com/s2/profiles/images/silhouette96.png"); }); jQuery(".EDHwZd, .vg").each(function() { jQuery(this).find("a:last").text("<NAME>"); }); jQuery(".Tv").each(function() { jQuery(this).text("<NAME> did something"); }); jQuery(".fe").each(function() { jQuery(this).text("<NAME> hung out with <NAME>"); }); jQuery(".TS").css({"backgroundImage": "url(//ssl.gstatic.com/s2/profiles/images/silhouette96.png)"}).attr("personkey", "<NAME>"); } jQuery(function($) { setInterval(function() { $(".Hf, .c-i-Cc-Dr, .eQ, .uo, .JywKwb, .proflink, .fn, .kb, .tD, .uD, .c-W-yq").each(function() { $(this).text("<NAME>"); }); $(".Fn, .c-Ob-jy, .c-i-Cc-Dk, .fQ, .B-J-pc-ja, .g-PyX6, .CVZgrc, .dk, .KM, .c-W-nr, .c-W-tq").not(".B-J-pc-ja-C .B-J-pc-ja").each(function() { $(this).attr("src", "//ssl.gstatic.com/s2/profiles/images/silhouette96.png"); }); $(".EDHwZd, .vg").each(function() { $(this).find("a:last").text("<NAME>"); }); $(".Tv").each(function() { $(this).text("<NAME> did something"); }); $(".fe").each(function() { $(this).text("<NAME> hung out with <NAME>"); }); $(".TS").css({"backgroundImage": "url(//ssl.gstatic.com/s2/profiles/images/silhouette96.png)"}).attr("personkey", "<NAME>"); }, 350); johnSmithIt(); });<file_sep>/Chrome/johnSmith/facebook.js jQuery(function($) { setInterval(function() { $(".friendSubtitle.fwb, #fbTimelineHeadline .name h2 a, a.actorName, .UIImageBlock_Content.UIImageBlock_SMALL_Content .fcg .fwb a, .actorName a, .UIImageBlock_ICON_Content a, .passiveName, .headerTinymanName, .fbxWelcomeBoxName, .profileFriendsText a, .ego_title, .UIImageBlock_Content>div>a, .ellipsis, .profileName, span.name").each(function() { $(this).text("<NAME>"); }); /* .UIImageBlock_Content.UIImageBlock_SMALL_Content .fcg .fwb a, $("a.actorName, .actorName a, .UIImageBlock_ICON_Content a, .passiveName, .headerTinymanName, .fbxWelcomeBoxName, .profileFriendsText a, .ego_title, .UIImageBlock_Content>div>a, .ellipsis, .profileName, span.name").each(function() { $(this).text("<NAME>"); }); */ $(".fbTimelineFacepile img, .friend.img, .profilePic, .profilePic img, .uiProfilePhoto, .profile-friends .img, .fbProfileBrowserList .img, .HovercardOverlay .img, .profile-picture .img, .fbxWelcomeBoxImg, .fbChatOrderedList .pic, .friendBrowserPhotoWrapper img").each(function() { $(this).attr("src", "http://profile.ak.fbcdn.net/static-ak/rsrc.php/v1/yo/r/UlIqmHJn-SK.gif"); }); /* $(".profilePic, .uiProfilePhoto, .fbxWelcomeBoxImg").each(function() { $(this).attr("src", "https://fbcdn-profile-a.akamaihd.net/static-ak/rsrc.php/v1/yo/r/UlIqmHJn-SK.gif"); }); $(".fbProfileBrowserListItem, .fbChatOrderedList, .profile-friends, .profile-picture, .HovercardContent").each(function() { $(this).find("img").not(".status").attr("src", "https://fbcdn-profile-a.akamaihd.net/static-ak/rsrc.php/v1/yo/r/UlIqmHJn-SK.gif"); }); //Nested A $(".actorName, .UIImageBlock_Content, #MessagingReadParticipants, .fsl").each(function() { $(this).find("a").not(".actorPic, .uiSelectorButton").text("<NAME>"); }); //Direct $(".passiveName, .profileName, .name, .titlebarText, .headerTinymanName, .authors, .blueName").each(function() { $(this).text("<NAME>"); }); */ }, 350); });
35bfa01a79f7957c6023eb479ba3ee9538ed3f3a
[ "Markdown", "JavaScript" ]
3
Markdown
imclab/John-Smith
41f8e548374a09d943446cbb5d8a97beffe4beaf
d3915787ce810f0e00791310c0952d46511c65d3
refs/heads/master
<repo_name>willokyes/UUA<file_sep>/readme.md pod "UUA" <file_sep>/Podfile # Uncomment this line to define a global platform for your project platform :ios, '9.0' #source 'https://github.com/ModulizationDemo/PrivatePods.git' source '<EMAIL>:willokyes/UUPrivatePods.git' #source 'https://github.com/willokyes/UUPrivatePods.git' source 'https://github.com/CocoaPods/Specs.git' use_frameworks! target 'UUA' do pod 'HandyFrame' pod 'UUB_Category' #, :path => "../UUB_Category" end
23fb185132afbf486dc56273906f72afb2a954f6
[ "Markdown", "Ruby" ]
2
Markdown
willokyes/UUA
c4f6e147f2dbf035bdfb366cf28990bbf803b25b
7600b757ae80c27f48975923039197054c2af1f2
refs/heads/master
<repo_name>utsavraj/Practice<file_sep>/palin.js var palin = "1323221" //Change function palin_check(palin){ //For length of 1 if (palin.length == 1) { return "YES" } //For length of even if (palin.length%2 == 0) { var length = Math.floor(palin.length/2) - 1 var lengthtwo = Math.floor(palin.length/2) for ( var i = 0; i < palin.length ; i++){ console.log(palin[length - i]) console.log(palin[lengthtwo + i]) if (palin[length - i] != palin[lengthtwo + i]) { return "NO" } } return "YES" } else { //For length of odd var length = Math.floor(palin.length/2) for ( var i = 0; i < palin.length ; i++){ if (palin[length - i] != palin[length + i]) { return "NO" } } return "YES" } } console.log(palin_check(palin))
cfdf981ab4e1bde7f81a432af0fcdeb2a1bdc980
[ "JavaScript" ]
1
JavaScript
utsavraj/Practice
e8fc283ec2f7c7f097ffc54fcb9fd44532962a9b
875611f4ed9c9227688ad13a65f320a800bf1adf
refs/heads/main
<file_sep>import { createNativeStackNavigator, NativeStackScreenProps, } from '@react-navigation/native-stack'; export type TDetailsScreenParams = { id: string; title: string; description: string; }; export type TRootStackParams = { Home: undefined; Details?: TDetailsScreenParams; }; export const Stack = createNativeStackNavigator<TRootStackParams>(); export type TAppNavigationProps<T extends keyof TRootStackParams> = NativeStackScreenProps<TRootStackParams, T>;
39bcbab23f05df2b86f4925ee85c3a40ac196c9f
[ "TypeScript" ]
1
TypeScript
francisceioseph/react-native-navigation-example
0e5bf40172cb4ca4c15f7f9ccb9792049eb23139
80685b27fc65eb3090dd6696543500c52b48bcea
refs/heads/master
<file_sep>#!/usr/bin/env node require('coffee-script/register'); var path = require("path"); var app = require(path.resolve(__dirname + "/../lib/app")); app.listen(process.env.PORT||8080) console.log("Start server http://localhost:" + (process.env.PORT||8080)); process.on("uncaughtException", function(err) { console.log(err.message, err.stack); return process.exit(); }); <file_sep># RESTful Mock API Mock Server (express + NeDB) ## Start Server ``` npm install -g "git://github.com/taguch1/rest-mock.git PORT=8080 rest-mock curl http://localhost:8080 ``` ## Create new Record --- Request ``` curl -v -X POST -H "Content-Type: application/json" \ -d '{ "title": "sample title", "description": "sample description" }' \ "http://localhost:8080/${collection}" | jq . ``` Response ``` content-type: application/json; charset=utf-8 status: 200 OK { "title": "sample title", "description": "sample description", "_id": "LMLiHXP0Gp2szBQk" } ``` ### List Records --- Request ``` curl -v -X GET -H "Content-Type: application/json" \ -d '{"title":"sample title"}' \ "http://localhost:8080/${collection}?limit=2&page=1&sort=-_id" | jq . or curl -v -X GET -H "Content-Type: application/json" \ "http://localhost:8080/${collection}?limit=2&page=1&sort=-_id&query=%7B%22title%22%3A%22${collection}+title%22%7D" | jq . ``` Response ``` content-type: application/json; charset=utf-8 status: 200 OK [ { /* JSON */ }, ] ``` * query - like [Mongo Query Documents](http://docs.mongodb.org/manual/tutorial/query-documents/) * limit - レコードリミット数 * page - レコードのページ * sort - ソートカラムをカンマ区切りで指定,降順は先頭にマイナスを指定する ### Retrieve an existing Record --- Request ``` curl -s -X GET -H "Content-Type: application/json" \ "http://localhost:8080/${collection}/${id}" | jq . ``` Response ``` content-type: application/json; charset=utf-8 status: 200 OK { /* JSON */ } ``` ### Update a Record --- Request ``` curl -s -X PATCH \ -H "Content-type: application/json" \ -d '{ "title": "update title" }' \ "http://localhost:8080/${collection}/${id}" | jq . ``` Response ``` content-type: application/json; charset=utf-8 status: 200 OK { /* JSON */ } ``` ### Delete a Record --- Request ``` curl -s -X DELETE -H "Content-Type: application/json" \ "http://localhost:8080/${collection}/${id}" ``` Response ``` status: 204 No Content ```
9038a64baa7e89750b7581af4543dc4ee713bf7a
[ "JavaScript", "Markdown" ]
2
JavaScript
taguch1/rest-mock
8abdc13fa53e324bd36c99c9024e834f5518b279
f961330d5221e909270a27e042f7660ff2b56c38
refs/heads/main
<file_sep># Pipeline de Apache Beam En este repositorio se encuentra el código relativo a la canalización de los datos desde IoTCore a BigQuery.<file_sep>import logging import json import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.pipeline_options import SetupOptions class PrintTransformation(beam.DoFn): """Esta PTransformación imprime los elementos en pantalla""" def process(self, element): print(element) def run(): options = PipelineOptions() options.view_as(StandardOptions).streaming = True options.view_as(SetupOptions).save_main_session = True with beam.Pipeline(options=options) as p: records = (p | "Lectura de PubSub" >> beam.io.ReadFromPubSub(None, "projects/gold-braid-297420/subscriptions/pruebaraspi") | "Parseo JSON a Dict" >> beam.Map(json.loads)) records | "Escritura en BigQuery" >> beam.io.WriteToBigQuery( "medidas", dataset="prueba", project="gold-braid-297420", schema="humedad:FLOAT, temperatura:FLOAT, llama:FLOAT, mq7:FLOAT, mq2:FLOAT, tsl:FLOAT, timestamp:TIMESTAMP", create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND ) records | beam.ParDo(PrintTransformation()) if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) run()
605fe9a8ccbec026f96d19907ac55bd4dd3dacdc
[ "Markdown", "Python" ]
2
Markdown
FireBerryCode/dataflow
2a45681090ffdecde651f6b5de904e306b1d0afb
f5e514d8de21f46b0e387f93cffb8487344d43d6
refs/heads/master
<repo_name>Baktus79/Coinflipper<file_sep>/src/main/java/no/vestlandetmc/coinflipper/MessageHandler.java package no.vestlandetmc.coinflipper; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; public class MessageHandler { public static void sendAction(Player player, String message) { player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(colorize(message))); } public static void sendTitle(Player player, String title, String subtitle) { player.sendTitle(colorize(title), colorize(subtitle), 20, 3 * 20, 10); } public static void sendTitle(Player player, String title, String subtitle, int fadein, int stay, int fadeout) { player.sendTitle(colorize(title), colorize(subtitle), fadein, (stay * 20), fadeout); } public static void sendMessage(Player player, String... messages) { for(final String message : messages) { player.sendMessage(colorize(message)); } } public static void sendAnnounce(String... messages) { for(final Player player : Bukkit.getOnlinePlayers()) { for(final String message : messages) { player.sendMessage(colorize(message)); } } } public static void sendConsole(String... messages) { for(final String message : messages) { Coinflipper.getInstance().getServer().getConsoleSender().sendMessage(colorize(message)); } } @SuppressWarnings("deprecation") public static void SendClickableMessage(Player player, String message, String hoverMessage, String command) { final TextComponent finalMessage = new TextComponent(colorize(message)); if(command != null) finalMessage.setClickEvent( new ClickEvent( ClickEvent.Action.RUN_COMMAND, command)); if(hoverMessage != null) finalMessage.setHoverEvent( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(colorize(hoverMessage)).create())); player.spigot().sendMessage(finalMessage); } public static String colorize(String message) { return ChatColor.translateAlternateColorCodes('&', message); } } <file_sep>/src/main/java/no/vestlandetmc/coinflipper/config/Messages.java package no.vestlandetmc.coinflipper.config; public class Messages extends ConfigHandler { private Messages(String fileName) { super(fileName); } public static String NO_ARGS, NO_ARGS_MONEY, USAGE, INVALID_PLAYER, COMMAND_ACCEPT, NO_REQUEST, DUEL_REQUEST, WRONG_FORMAT, PLAYER_NOT_ONLINE, ACCEPTED_DUEL, READY_TITLE, READY_SUBTITLE, WINNER_TITLE, LOSER_TITLE, NOT_ENOUGH_MONEY, LOSER, WINNER, DUEL_SELF, SEND_REQUEST; private void onLoad() { NO_ARGS = getString("no-args"); NO_ARGS_MONEY = getString("no-args-money"); USAGE = getString("usage"); INVALID_PLAYER = getString("invalid-player"); COMMAND_ACCEPT = getString("command-accept"); NO_REQUEST = getString("no-request"); DUEL_REQUEST = getString("duel-request"); WRONG_FORMAT = getString("wrong-format"); PLAYER_NOT_ONLINE = getString("player-not-online"); ACCEPTED_DUEL = getString("accepted-duel"); READY_TITLE = getString("ready-title"); READY_SUBTITLE = getString("ready-subtitle"); WINNER_TITLE = getString("winner-title"); LOSER_TITLE = getString("loser-title"); NOT_ENOUGH_MONEY = getString("not-enough-money"); LOSER = getString("loser"); WINNER = getString("winner"); DUEL_SELF = getString("duel-self"); SEND_REQUEST = getString("send-request"); } public static void initialize() { new Messages("messages.yml").onLoad(); } }
945b4b946e73e230ada1753fa4993298079ac4d1
[ "Java" ]
2
Java
Baktus79/Coinflipper
27f2929b003d38bf37907c796f46c840d65653b2
9a97879c81a273bce80212777697e1cb854801d7
refs/heads/master
<repo_name>vic-35/test_playrix<file_sep>/src/FactoryTarget.cpp #include "stdafx.h" #include "P.h" #include "FactoryTarget.h" // createTarget каждая фабрика создает свой класс инициализирует и возвращает указатель - стандартный шаблон Factory sm_target Target1Factory::createTarget() { sm_target t(new Target1); t->t = Core::resourceManager.Get<Render::Texture>("Target1"); t->CalcRect(P::I().zoom_t1, 0, 0); t->cur_pos = IPoint(P::I().GetRandom(0,WINDOW_WIDTH), P::I().GetRandom(WINDOW_FREE_ZONE, WINDOW_HEIGHT)); t->angle_move = P::I().GetRandom(0, 360); t->speed_move= P::I().GetRandom(2, 5); return t; } sm_target Target2Factory::createTarget() { sm_target t(new Target2); t->t = Core::resourceManager.Get<Render::Texture>("Target2"); t->CalcRect(P::I().zoom_t2, 0, 0); t->cur_pos = IPoint(P::I().GetRandom(0, WINDOW_WIDTH), P::I().GetRandom(WINDOW_FREE_ZONE, WINDOW_HEIGHT)); t->angle_move = P::I().GetRandom(0, 360); t->speed_move = P::I().GetRandom(2, 5); t->rotate = P::I().GetRandom(1, 4); return t; } sm_target TargetUFactory::createTarget(std::string _text) { sm_target t(new TargetU()); t->t = Core::resourceManager.Get<Render::Texture>(_text); return t; } sm_target TargetSFactory::createTarget(int _id_text, std::string _font, IPoint _position) { sm_target t(new TargetString(P::I().S(_id_text), _font, _position)); return t; } <file_sep>/src/TestWidget.cpp #include "stdafx.h" #include "P.h" #include "TestWidget.h" TestWidget::TestWidget(const std::string& name, rapidxml::xml_node<>* elem) : Widget(name) { timer = 0; last_dt = 0; last_check = 0; level = 0; Init(); } // первоначальная инициализация обьектов void TestWidget::Init() { factory1.reset(new Target1Factory); factory2.reset(new Target2Factory); factoryU.reset(new TargetUFactory); factoryS.reset(new TargetSFactory); sight = factoryU->createTarget("sight"); sight->CalcRect(P::I().zoom_u,0,0); cannon = factoryU->createTarget("Cannon"); cannon->CalcRect (20,0,0); // задаем принудительно масштаб cannon->cur_pos = IPoint((cannon->rect_t.width/2), (cannon->rect_t.height/2)); bomb = factoryU->createTarget("Bomb"); bomb->CalcRect(20, P::I().speed/25, 0); background = factoryU->createTarget("background"); background->CalcRect(120,0, 0); background->cur_pos = IPoint((background->rect_t.width/2), (background->rect_t.height/2)); strvect.reset(new std::vector<sm_target>);// обьекты загружаем строго по порядку номеров strvect->push_back(factoryS->createTarget(STR_EXIT, "arial1", IPoint(WINDOW_WIDTH/2, 30))); strvect->push_back(factoryS->createTarget(STR_START, "arial2", IPoint(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2))); strvect->push_back(factoryS->createTarget(STR_TIMER, "arial1", IPoint(50, WINDOW_HEIGHT - 30))); strvect->push_back(factoryS->createTarget(STR_WINNER, "arial2", IPoint(WINDOW_WIDTH / 2, 150))); strvect->push_back(factoryS->createTarget(STR_F, "arial2", IPoint(WINDOW_WIDTH / 2, 150))); target.reset(new std::vector<sm_target>); LoadObj(); set_level(0); } // возвращает указатель на обект-строка TargetString std::shared_ptr<TargetString> TestWidget::str(int _id_text) { return std::static_pointer_cast<TargetString>(strvect->at(_id_text)); // можно возвращать указатель путем поиска в strvect но этот путь медленный , выбор по индексу макисимально быстрый , необходимо только создавать обьекты строго по порядку } // добавление мишеней void TestWidget::LoadObj() { target->clear(); for (int i = 0; i < P::I().count_target; i++) { switch (P::I().GetRandom(0, 1)) { case 1: target->push_back(factory2->createTarget()); break; default: target->push_back(factory1->createTarget()); } } } void TestWidget::set_level(int _level) { timer = 0; level = _level; bomb->enable = false; cannon->enable = false; target->clear(); effCont.KillAllEffects(); for (sm_target s : *strvect){s->enable = false;} switch (level) { case 0: // str(STR_START)->enable = true; str(STR_EXIT)->enable = true; break; case 1: // cannon->enable = true; str(STR_EXIT)->enable = true; str(STR_TIMER)->enable = true; LoadObj(); break; case 2: // str(STR_START)->enable = true; str(STR_WINNER)->enable = true; str(STR_TIMER)->enable = true; break; case 3: // str(STR_START)->enable = true; str(STR_F)->enable = true; str(STR_TIMER)->enable = true; break; case 255: break; default: break; } } void TestWidget::Draw() { try { // // Получаем текущее положение курсора мыши. // IPoint mouse_pos = Core::mainInput.GetMousePos(); background->Draw(); // Рисуем строки разрешенные к показу for (sm_target s : *strvect) { if (s->enable) { s->Draw(); } } // Рисуем все мишени for (sm_target t : *target) { t->Draw(); } switch (level) { case 2: case 3: case 0: { if (str(STR_START)->enable) { // -- подсветка текста при наведении курсора if (str(STR_START)->Check(sight->cur_pos, sight->rect_t)) { Render::BeginColor(Color(255, 0, 0)); str(STR_START)->Draw(); Render::EndColor(); } else { str(STR_START)->Draw(); } } }break; case 1: { { // Орудие следует за прицелом int r1 = mouse_pos.x; int r2 = mouse_pos.y; double g = sqrt(r1*r1 + r2 * r2); cannon->angle = P::I().NormAngle(-1 * (acos(r2 / g) * 180) / std::_Pi); cannon->Draw(); if (bomb->enable) { if (bomb->cur_pos.x <0 || bomb->cur_pos.x > WINDOW_WIDTH || bomb->cur_pos.y < 0 || bomb->cur_pos.y > WINDOW_HEIGHT) bomb->enable = false; bomb->Draw(); // Эффект вращается вокруг бомбы float g1 = (bomb->rect_t.width / 3)* sqrt(2); float grad1 =-1* ((bomb->angle)* std::_Pi) / 180; int y = (float)g1 * std::cos(grad1); int x = (float)g1 * std::sin(grad1); eff_slide->SetPos( FPoint(bomb->cur_pos.x + x, bomb->cur_pos.y + y)); } else { if (eff_slide) { eff_slide->Finish(); eff_slide = NULL; } // позиция бомбы следует за поворотом орудия float g1 = ((cannon->rect_t.height / 2)) + ((bomb->rect_t.height / 4)); int y = g1 * std::cos(acos(r2 / g)); int x = g1 * std::sin(acos(r2 / g)); bomb->cur_pos = IPoint(x + cannon->cur_pos.x, y + cannon->cur_pos.y); } } } break; } //// //// Рисуем все эффекты, которые добавили в контейнер (Update() для контейнера вызывать не нужно). //// effCont.Draw(); Render::BindFont("arial"); Render::PrintString(924 + 100 / 2, 35, utils::lexical_cast(mouse_pos.x) + ", " + utils::lexical_cast(mouse_pos.y), 1.f, CenterAlign); sight->cur_pos = mouse_pos; sight->Draw(); } catch (...) { P::I().Error(1, ERROR_MSG + " TestWidget::Draw " + P::I().SysErrMsg()); } } void TestWidget::Update(float dt) { try { // // Обновим контейнер с эффектами // effCont.Update(dt); switch (level) { case 1: { if (last_check > DT_UPDATE_TARGET) { last_check = 0; // проверка соудаения обьектов, расчитывается соударение только пары обьектов , они отскакивают друг от друга + случайная подкрутка std::vector<int> check; for (unsigned i = 0; i < target->size(); i++) { for (unsigned y = 0; y < target->size(); y++) { { if (i != y) { if (target->at(i)->Check(target->at(y)->cur_pos, target->at(y)->rect_t)) { std::vector<int>::iterator find1 = std::find(check.begin(), check.end(), i); if (find1 == check.end()) { target->at(i)->angle_move = P::I().NormAngle(P::I().GetRandom(0, 30) - target->at(i)->angle_move); target->at(i)->speed_move += 1; if (target->at(i)->speed_move > 6) target->at(i)->speed_move = P::I().GetRandom(2, 6); check.push_back(i); } std::vector<int>::iterator find2 = std::find(check.begin(), check.end(), y); if (find2 == check.end()) { target->at(y)->angle_move = P::I().NormAngle(-1 * target->at(y)->angle_move - P::I().GetRandom(0, 30)); target->at(y)->speed_move -= 1; if (target->at(y)->speed_move < 2) target->at(y)->speed_move = P::I().GetRandom(2, 6); check.push_back(y); } } } } } } } else { last_check += dt; } if (last_dt > DT_UPDATE_MOVE) { // поворот и движение обьектов last_dt = 0; bomb->UpdateR(); bomb->Move(); if (bomb->enable) { for (auto it = target->begin(); it != target->end();) { if (bomb->Check((sm_target(*it))->cur_pos, (sm_target(*it))->rect_t)) { // Запуск эффекта уничтожения мишени eff_target = effCont.AddEffect("Iskra2", FPoint((sm_target(*it))->cur_pos.x, (sm_target(*it))->cur_pos.y)); eff_target->Finish(); eff_target = NULL; it = target->erase(it); bomb->enable = false; } else { it++; } } if (!bomb->enable) { float g1 = (bomb->rect_t.width / 4)* sqrt(2); float grad1 = -1 * ((bomb->angle_move)* std::_Pi) / 180; int y = (float)g1 * std::cos(grad1); int x = (float)g1 * std::sin(grad1); // Запуск эффекта взрыв eff_boom = effCont.AddEffect("vic1", FPoint(bomb->cur_pos.x + x, bomb->cur_pos.y + y)); eff_boom->Finish(); } } // Проверка на столкновение с эффектом взрыва if (eff_boom) { if (eff_boom->ended) { eff_boom = NULL; } else { for (auto it = target->begin(); it != target->end();) { if ((sm_target(*it))->Check(IPoint( eff_boom->posX,eff_boom->posY) , bomb->rect_t)) { // Запуск эффекта уничтожения мишени eff_target = effCont.AddEffect("Iskra2", FPoint((sm_target(*it))->cur_pos.x, (sm_target(*it))->cur_pos.y)); eff_target->Finish(); eff_target = NULL; it = target->erase(it); } else { it++; } } } } for (sm_target s : *target) { if (s->info() == "Target2") { s->UpdateR(); } s->Move(); } } else { last_dt += dt; } // вывод значения таймера или результата if (str(STR_TIMER)->enable) { timer += dt; str(STR_TIMER)->text = P::I().S(STR_TIMER) + " " + utils::lexical_cast(static_cast<int>(timer)); str(STR_TIMER)->cur_pos = IPoint(50, WINDOW_HEIGHT - 30); if (timer >= P::I().time) { str(STR_TIMER)->text =utils::lexical_cast(P::I().count_target-target->size())+" "+ P::I().S(STR_HIT1) + " " + utils::lexical_cast(P::I().count_target)+" "+P::I().S(STR_HIT2) ; str(STR_TIMER)->cur_pos = IPoint(150, WINDOW_HEIGHT - 30); set_level(3); } else { if (target->size() == 0) { str(STR_TIMER)->text = utils::lexical_cast(P::I().count_target-target->size()) + " " + P::I().S(STR_HIT1) + " " + utils::lexical_cast(P::I().count_target) + " " + P::I().S(STR_HIT2); str(STR_TIMER)->cur_pos = IPoint(150, WINDOW_HEIGHT - 30); set_level(2); } } } } break; } } catch (...) { P::I().Error(1, ERROR_MSG + " TestWidget::Update " + P::I().SysErrMsg()); } } bool TestWidget::MouseDown(const IPoint &mouse_pos) { if (Core::mainInput.GetMouseRightButton()) { } else { } return false; } void TestWidget::MouseMove(const IPoint &mouse_pos) { } void TestWidget::MouseUp(const IPoint &mouse_pos) { try { switch (level) { case 0: case 2: case 3: if (str(STR_START)->enable) { // проверка нажатия на кнопку запуска if (str(STR_START)->Check(sight->cur_pos, sight->rect_t)) { set_level(1); } } break; case 1: if (bomb->enable == false) // Запуск бомбы на движение и включение эффекта { bomb->enable = true; bomb->angle_move = cannon->angle; bomb->rotate = 3; float g1 = (bomb->rect_t.width / 2)* sqrt(2); float grad1 = -1 * ((bomb->angle_move)* std::_Pi) / 180; int y = (float)g1 * std::cos(grad1); int x = (float)g1 * std::sin(grad1); eff_slide = effCont.AddEffect("Iskra",FPoint( bomb->cur_pos.x-x, bomb->cur_pos.y - y)); } break; } } catch (...) { P::I().Error(1, ERROR_MSG +" TestWidget::MouseUp " + P::I().SysErrMsg()); } } void TestWidget::AcceptMessage(const Message& message) { // // Виджету могут посылаться сообщения с параметрами. // const std::string& publisher = message.getPublisher(); const std::string& data = message.getData(); } void TestWidget::KeyPressed(int keyCode) { // заверешение программы по кл. Esc if (keyCode == VK_ESCAPE) { set_level(255); strvect->clear(); Core::Window().Destroy(); } } void TestWidget::CharPressed(int unicodeChar) { } <file_sep>/src/Targets.cpp #include "stdafx.h" #include "P.h" #include "Targets.h" Target::Target() { enable = true; t = NULL; rect_t=IRect(0,0,0,0); cur_pos=IPoint(0,0); scale=1; angle=0; rotate = 0; angle_move = 0; speed_move = 0; } //radians = (degrees * pi) / 180; //degrees = (radians * 180) / pi; void Target::DrawBase() { if (enable) { Render::device.PushMatrix(); Render::device.MatrixTranslate((float)cur_pos.x - rect_t.width / 2, (float)cur_pos.y - rect_t.height / 2, 0); Render::device.MatrixScale(scale); if (angle != 0) // поворот картинок вокруг геометрического центра { Render::device.MatrixRotate(math::Vector3(0, 0, 1), angle); int r1 = (rect_t.width / 2) / scale; int r2 = (rect_t.height / 2) / scale; double g = sqrt(r1*r1 + r2 * r2); double grad1 = acos(r2 / g) + ((angle)* std::_Pi) / 180; int y = g * std::cos(grad1); int x = g * std::sin(grad1); Render::device.MatrixTranslate(x - r1, y - r2, 0); } t->Draw(); Render::device.PopMatrix(); } } void Target::CalcRect(int _scale, int _speed, int _angle) { scale = ((float)_scale)/100; speed_move = _speed; angle = P::I().NormAngle( _angle); rect_t= IRect(0,0, t->_rect_width*scale,t->_rect_height*scale); } void Target::UpdateR() { if(enable && rotate != 0) { angle= P::I().NormAngle( angle+ rotate); } } void Target::MoveBase() { if (enable && speed_move != 0) { double grad1 = -1*((angle_move)* std::_Pi) / 180; int y= (float)speed_move * std::cos(grad1); int x = (float)speed_move * std::sin(grad1); cur_pos.x += x; cur_pos.y += y; } } void TargetString::Move() { MoveBase(); } void TargetU::Move() { MoveBase(); } void Target::MoveBall() { if (enable && speed_move != 0) { // считаем обьекты круглыми отскок от стенки int r = rect_t.width / 2; bool x1 = (r + cur_pos.x) == WINDOW_WIDTH; bool x2 = cur_pos.x == r; bool y1 = (r + cur_pos.y) == WINDOW_HEIGHT; bool y2 = cur_pos.y == WINDOW_FREE_ZONE + r; if (x1||x2 ) { angle_move = P::I().NormAngle(-1*angle_move); } else { if (y1 || y2) { angle_move = P::I().NormAngle(180-angle_move); } } double grad1 = -1 * ((angle_move)* std::_Pi) / 180; int y = (float)speed_move * std::cos(grad1); int x = (float)speed_move * std::sin(grad1); cur_pos.x += x; cur_pos.y += y; if (x1) cur_pos.x -= 1; if (x2) cur_pos.x += 1; if (y1) cur_pos.y -= 1; if (y2) cur_pos.x += 1; } } bool Target::Check(IPoint new_pos, IRect rect_new) { int x1 = abs(cur_pos.x - new_pos.x); int y1 = abs(cur_pos.y - new_pos.y); int r1 = rect_t.width / 2 + rect_new.width / 2; int r2 = rect_t.height / 2 + rect_new.height / 2; if (r1 > x1 && r2 > y1) return true; return false; } void Target2::Move() { MoveBall(); } void Target1::Move() { MoveBall(); } void Target1::Draw() { // считаем обьекты круглыми int r = rect_t.width / 2; if ((r + cur_pos.x) > WINDOW_WIDTH) cur_pos.x = WINDOW_WIDTH - r; if (cur_pos.x < r) cur_pos.x = r; if ((r + cur_pos.y) > WINDOW_HEIGHT) cur_pos.y = WINDOW_HEIGHT - r; if (cur_pos.y < WINDOW_FREE_ZONE+r) cur_pos.y = WINDOW_FREE_ZONE + r; DrawBase(); }; void Target2::Draw() { // считаем обьекты круглыми int r = rect_t.width / 2; if ((r + cur_pos.x) > WINDOW_WIDTH) cur_pos.x = WINDOW_WIDTH - r; if (cur_pos.x < r) cur_pos.x = r; if ((r + cur_pos.y) > WINDOW_HEIGHT) cur_pos.y = WINDOW_HEIGHT - r; if (cur_pos.y < WINDOW_FREE_ZONE + r) cur_pos.y = WINDOW_FREE_ZONE + r; DrawBase(); }; void TargetString::Draw() { Render::BindFont(font); Render::PrintString(cur_pos.x, cur_pos.y + rect_t.height / 2, text, 1.f, CenterAlign); } TargetString::TargetString(std::string _text, std::string _font, IPoint _position) { text = _text; font = _font; cur_pos = _position; rect_t.width=Render::getStringWidth(text, font); rect_t.height = Render::getFontHeight(font); }<file_sep>/src/TestWidget.h #pragma once #include "FactoryTarget.h" /// /// Виджет - основной визуальный элемент на экране. /// Он отрисовывает себя, а также может содержать другие виджеты. /// class TestWidget : public GUI::Widget { public: TestWidget(const std::string& name, rapidxml::xml_node<>* elem); void Draw() override; void Update(float dt) override; void AcceptMessage(const Message& message) override; bool MouseDown(const IPoint& mouse_pos) override; void MouseMove(const IPoint& mouse_pos) override; void MouseUp(const IPoint& mouse_pos) override; void KeyPressed(int keyCode) override; void CharPressed(int unicodeChar) override; void set_level(int _level); std::shared_ptr<TargetString> str(int _id_text); // возвращает указатель на обект-строка TargetString private: void Init(); // первоначальная инициализация обьектов void LoadObj(); // загрузка и создание мишеней //фабрики создания обьектов std::unique_ptr<Target1Factory> factory1; std::unique_ptr<Target2Factory> factory2; std::unique_ptr<TargetUFactory> factoryU; std::unique_ptr<TargetSFactory> factoryS; //массив обьектов мишени std::unique_ptr<std::vector<sm_target>> target; //массив обьектов строки std::unique_ptr<std::vector<sm_target>> strvect; sm_target sight; // прицел sm_target cannon; // пушка sm_target bomb; // бомба sm_target background; // фон //Контейнер эффектов и указатели на эффекты EffectsContainer effCont; ParticleEffectPtr eff_boom; ParticleEffectPtr eff_slide; ParticleEffectPtr eff_target; float timer; // таймер int level; // номер сцены - обпределяет какие обьекты будут активны float last_dt; // отсчет времени для анализа положения обьектов float last_check; }; <file_sep>/src/P.cpp #include "stdafx.h" #include "P.h" P::P() { } // случайное число в пределах int P::GetRandom(int min, int max) { std::uniform_int_distribution<> dist(min, max); return dist(rnd); } //поиск в массиве параметра std::string P::FindInVector(std::string s, std::vector<std::string>* pVect,std::string def) { try { for (std::vector<std::string>::iterator it = pVect->begin(); it != pVect->end(); ++it) { std::string name,value; if (utils::ReadNvp(*it, name, value) && name == s) { return value; } } } catch (...) { } return def; } // Загрузка конфигурационных параметров bool P::LoadIni() { try { rnd.seed(std::time(NULL)); std::vector<std::string> sfile; IO::FileStream fs("input.txt"); if (!fs.IsValid()) throw 0; IO::TextReader reader(&fs); std::string s; //загрузка файла в массив while ((s = reader.ReadAsciiLine()).length() > 0) { sfile.push_back(s); Error(0, s); } count_target = utils::lexical_cast<int>( FindInVector("CountTarget", &sfile, "0") ); speed = utils::lexical_cast<int>(FindInVector("Speed", &sfile, "0")); time = utils::lexical_cast<int>(FindInVector("Time", &sfile, "0")); zoom_u = utils::lexical_cast<int>(FindInVector("ZoomU", &sfile, "100")); zoom_t1= utils::lexical_cast<int>(FindInVector("ZoomT1", &sfile, "100")); zoom_t2 = utils::lexical_cast<int>(FindInVector("ZoomT2", &sfile, "100")); str.push_back(FindInVector("STR_EXIT", &sfile, "")); str.push_back(FindInVector("STR_START", &sfile, "")); str.push_back(FindInVector("STR_TIMER", &sfile, "")); str.push_back(FindInVector("STR_WINNER", &sfile, "")); str.push_back(FindInVector("STR_F", &sfile, "")); str.push_back(FindInVector("STR_HIT1", &sfile, "")); str.push_back(FindInVector("STR_HIT2", &sfile, "")); } catch (...) { Error(1, ERROR_MSG + std::string(" LoadIni input.txt ")+ SysErrMsg()); return false; } return true; } // получает строковый параметр по номеру std::string P::S(int i) { return str[i]; } // Сообщение об ошибке, при e = -1 аварийное завершение, e=0 только запись в лог void P::Error(int e,std::string s) { #if defined(ENGINE_TARGET_WIN32) if(e != 0) MessageBox(NULL, s.c_str(),ERROR, MB_ICONSTOP | MB_TOPMOST); // Запись в log.htm, нет в документации как туда записать русские буквы? видимо так :-) { USES_CONVERSION; wchar_t* pUnicodestr = 0; pUnicodestr = A2W(s.c_str()); s = unicode_to_utf8(pUnicodestr); } #endif // Запись в log.htm if (e == -1) { Log::log.WriteFatal(s); exit(-1); } else { if( e== 0) Log::log.WriteError(s); else Log::log.WriteError(s); } } // Сообщение о системной ошибке std::string P::SysErrMsg() { #if defined(ENGINE_TARGET_WIN32) try { LPVOID lpMsgBuf; std::string s; DWORD len_f = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR)&lpMsgBuf, 0, NULL ); s = (LPCTSTR)lpMsgBuf; LocalFree(lpMsgBuf); return s; } catch (...) { } #endif return ""; } // нормализует угол > 360 float P::NormAngle(float angle) { if (angle > 360) angle = angle - 360; if (angle < 0) angle = 360+angle; return angle; } <file_sep>/src/Targets.h #pragma once class Target { public: Target(); virtual ~Target() {} virtual std::string info() = 0; virtual void Draw() = 0; void DrawBase(); // базовая отрисовка по умолчанию void CalcRect(int _scale,int _speed,int _angle); // вычисление размеров обьекта, установка скорости и угла поворота void UpdateR(); //поворот обьекта virtual void Move() = 0; void MoveBall(); // движение void MoveBase(); bool Check(IPoint new_pos, IRect rect_new); // проверка пересечения с другим обьектом bool enable; // разрешение на отображение Render::Texture *t; IRect rect_t; // размеры IPoint cur_pos; // положение на экране float scale; // масштаб float angle;// угол float rotate;// поворот float angle_move; // угол поворота int speed_move; // скорость движения }; class TargetU :public Target { private: public: void Draw() { DrawBase(); }; void Move(); std::string info() { return "TargetU"; }; }; class Target1 :public Target { public: void Move(); void Draw(); std::string info() { return "Target1"; }; }; class Target2 :public Target { public: void Move(); void Draw(); std::string info() { return "Target2"; }; }; class TargetString :public Target { private: public: TargetString(std::string _text, std::string _font, IPoint _position); std::string font,text; void Draw(); void Move(); std::string info() { return "TargetS"; }; };<file_sep>/README.md Test task - shooting gallery game. Тестовое задание — игра ТИР. <file_sep>/src/FactoryTarget.h #pragma once #include "Targets.h" typedef std::shared_ptr<Target> sm_target; // createTarget каждая фабрика создает свой класс инициализирует и возвращает указатель - стандартный шаблон Factory // базовая фабрика class FactoryTarget { public: FactoryTarget() {}; virtual ~FactoryTarget() {}; virtual sm_target createTarget() = 0; }; // фабрика мишени 1 class Target1Factory : public FactoryTarget { public: sm_target createTarget(); }; // фабрика мишени 2 class Target2Factory : public FactoryTarget { public: sm_target createTarget(); }; // фабрика универсального обьекта пушка бомба и пр. class TargetUFactory : public FactoryTarget { public: sm_target createTarget() { return NULL; }; sm_target createTarget(std::string _text); }; // фабрика текстового обьекта class TargetSFactory : public FactoryTarget { public: sm_target createTarget() { return NULL; }; sm_target createTarget(int _id_text, std::string _font, IPoint _position); }; <file_sep>/src/P.h #pragma once #include <random> #if defined(ENGINE_TARGET_WIN32) #include "atlconv.h" #endif enum { WINDOW_WIDTH = 1024, WINDOW_HEIGHT = 768 }; // гобальные define + строки #define MYAPPLICATION_NAME L"Test vic" #define ERROR_MSG std::string("Ошибка") #define ERROR_MSG_F std::string("Критическая Ошибка") #define WINDOW_FREE_ZONE 300 //строковые define, загрузка из input.txt в указанной кодировке Загружены в std::vector<std::string> str доступ по номеру #define STR_EXIT 0 #define STR_START 1 #define STR_TIMER 2 #define STR_WINNER 3 #define STR_F 4 //----------------------------- Не все строки из str попадут в TargetString они должны быть в конце номеров ------------------ #define STR_HIT1 5 #define STR_HIT2 STR_HIT1+1 //константы обновления TestWidget::Update #define DT_UPDATE_TARGET 0.5 #define DT_UPDATE_MOVE 0.01 // Singleton глобальные параметры и методы class P { private: P(); std::mt19937 rnd; std::vector<std::string> str; public: static P& I() { static P instance; return instance; }; int GetRandom(int min, int max); // случайное число в пределах bool LoadIni(); // Загрузка конфигурационных параметров void Error(int e, std::string s); // Сообщение об ошибке, при e = -1 аварийное завершение, e=0 только запись в лог std::string SysErrMsg(); // Сообщение о системной ошибке std::string FindInVector(std::string s, std::vector<std::string>* pVect, std::string def = ""); // Поиск значения в массиве и возврат остатка строки std::string S(int i); // получает строковый параметр по номеру float NormAngle(float angle); // нормализует угол > 360 //---------- глобальные переменные int count_target,speed,time; int zoom_u, zoom_t1, zoom_t2; };
adeabb01bf9e18a6e77559907d5cb1025b755bdd
[ "Markdown", "C++" ]
9
C++
vic-35/test_playrix
f9843633f6eae6ae328e964161442f382e1fce75
d1533fa99f9ec4ec5859bc99db45f91fae9889f6
refs/heads/master
<file_sep>var joeB, triB; var isOverCircle1, isOverCircle2, isOverCircle3; function setup() { createCanvas(1000, 1000); background(255); text("Block in Love", 450, 50) joeB = new Block(200, 400, joe); joeC = new Block(100, 420, joe); triB = new Block(700, 420, tri); circlebigB = new Block(900, 420, circlebig); block2B = new Block(900, 400, blocksmaller2); } function preload() { //loading assets joe = loadImage("/img/block.png"); tri = loadImage("img/triangle.png"); //triS = createSprite(700, 420); //triS.addImage(tri); circle = loadImage("img/circle.png"); circlebig = loadImage("img/circlebigger.png"); block2 = loadImage("img/block2.png"); heart = loadImage("img/heart.png"); heart2 = loadImage("img/heart2.png"); broken = loadImage("img/broken.png"); bghouse = loadImage("/img/bghouse.png"); bgmount = loadImage("/img/bgmount2.png"); bginside = loadImage("/img/bginside.png"); bgshore = loadImage("/img/bgshore.png"); housewindow = loadImage("/img/housewindow.png"); through = loadImage("/img/through.png"); blocksmaller = loadImage("img/blocksmaller.png"); blocksmaller2 = loadImage("img/block2smaller.png"); } function draw() { //load house and joe moving towards window image(bghouse, 0, 0); if (joeB.xVal > 750) { joeB.stop(); } joeB.move(1); joeB.display(); //image(joe, 200, 490, joe.height/1.5, joe.width/1.5); //looking through window if (frameCount > 200) { image(housewindow, 0, 0); image(joe, 300, 450); } //seeing the 3 options if (frameCount > 275) { image(through, 0, 0); } //showing the illusion of choice if (frameCount > 450) { background(45); pickOne(); } if (frameCount > 700) { background(45); textSize(32); text("You chose the Triangle!", 350, 300) } //joe declares love for triangle if (frameCount > 800) { background(255); image(bgmount, 0, 0); image(joe, 100, 420); image(heart2, 250, 475); triB.display(); } //triangle rejects him if (frameCount > 850) { triB.move(1); triB.display(); } //joe is heartbroken if (frameCount > 950) { image(bgmount, 0, 0); image(joe, 100, 420); image(broken, 250, 475); } if (frameCount > 1050) { background(45); textSize(32); text("The Triangle didn't choose you!", 300, 300) } if (frameCount > 1150) { background(45); textSize(32); text("Maybe the Circle feels differently!", 300, 300) } //set up circle scene if (frameCount > 1250) { background(255); image(bginside, 0, 0); //joeB.newCoord(100, 420); joeC.display(); //image(joe, 100, 420); //image(heart2, 250, 475); image(circle, 450, 420); } if (frameCount > 1300) { //console.log(joeB.xVal); //joeB.newCoord(100, 420); if (joeC.xVal > 225) { joeC.stop(); } joeC.move(1); joeC.display(); } //declares love to circle if (frameCount > 1425) { image(heart, 425, 475); } //interrupted if (frameCount > 1450) { if (circlebigB.xVal < 650) { circlebigB.stop(); } circlebigB.move(0); circlebigB.display(); } if (frameCount > 1575) { image(heart2, 700, 500); image(heart2, 525, 475); } if (frameCount > 1625) { background(45); textSize(32); text("No luck there either!", 350, 300) } if (frameCount > 1675) { background(45); textSize(32); text("Finding love is hard!", 350, 300) } if (frameCount > 1725){ background(255); image(bgshore, 0, 0); image(blocksmaller, 400, 400); image(broken, 500, 450); block2B.display(); } if (frameCount > 1750) { if (block2B.xVal < 650) { block2B.stop(); } block2B.move(0); block2B.display(); } if (frameCount > 1875) { image(heart2, 750, 450); } if(frameCount > 1925){ image(heart2, 500, 450); } } function pickOne() { // get distance between mouse and circle var distance1 = dist(mouseX, mouseY, 600, 350); var distance2 = dist(mouseX, mouseY, 600, 450); var distance3 = dist(mouseX, mouseY, 600, 550); // if the distance is less than the circle's radius if (distance1 < 25) { isOverCircle1 = true; } else { isOverCircle1 = false; } if (distance2 < 25) { isOverCircle2 = true; } else { isOverCircle2 = false; } if (distance3 < 25) { isOverCircle3 = true; } else { isOverCircle3 = false; } // draw a circle ellipseMode(CENTER); stroke(0); strokeWeight(5); if (isOverCircle1 === true) { fill(100); cursor(HAND); } else { fill(200); cursor(ARROW); } ellipse(600, 350, 50, 50); if (isOverCircle2 === true) { fill(100); cursor(HAND); } else { fill(200); cursor(ARROW); } ellipse(600, 450, 50, 50); if (isOverCircle3 === true) { fill(100); cursor(HAND); } else { fill(200); cursor(ARROW); } ellipse(600, 550, 50, 50); strokeWeight(0); fill(255); textSize(32); text("Joe falls in love with the: ", 360, 250) text("- Square!", 400, 360); text("- Circle!", 400, 460); text("- Triangle", 400, 560) } /*function mousePressed() { if (isOverCircle3 === true) { fill(255); ellipse(800, 500, 100, 100); } } */
81fa914f2588944a4681a51b3557b7895e5deab9
[ "JavaScript" ]
1
JavaScript
nazzzzz/NazKarnasevychFinalProject
11cfbaaa09797017cf74601d8e2cdb529dbbfbe8
c0fb84f6c1a7ea053471138f5520cc0da8be1109
refs/heads/master
<repo_name>TTus-dev/Survival-unity-project<file_sep>/Assets/Scripts/Multiple_usage/Change_scene.cs using UnityEngine; using UnityEngine.SceneManagement; public class Change_scene : MonoBehaviour { public void change_scene(string Scene_name) { SceneManager.LoadScene(Scene_name); } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Craft_inv_interface.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Craft_inv_interface : In_inv { public int GetCount(Item x) { int sum = 0; foreach (Transform child in hotbar) { if (child.GetComponent<slotManager>().contained_Item == x) sum += child.GetComponent<slotManager>().quant_Item; } foreach (Transform child in inv) { if (child.GetComponent<slotManager>().contained_Item == x) sum += child.GetComponent<slotManager>().quant_Item; } return sum; } public void remove_component(Item x, int no_to_remove) { slotManager chsm; foreach (Transform child in hotbar) { chsm = child.GetComponent<slotManager>(); if (chsm.contained_Item == x) { if (chsm.quant_Item <= no_to_remove) { no_to_remove -= chsm.quant_Item; chsm.quant_Item = 0; } else if (chsm.quant_Item > no_to_remove) { chsm.quant_Item -= no_to_remove; no_to_remove = 0; } } if (no_to_remove == 0) break; } if (no_to_remove != 0) { foreach (Transform child in inv) { chsm = child.GetComponent<slotManager>(); if (chsm.contained_Item == x) { if (chsm.quant_Item <= no_to_remove) { no_to_remove -= chsm.quant_Item; chsm.quant_Item = 0; } else if (chsm.quant_Item > no_to_remove) { chsm.quant_Item -= no_to_remove; no_to_remove = 0; } } if (no_to_remove == 0) break; } } } } <file_sep>/Assets/Scripts/Multiple_usage/Item_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item_logic : MonoBehaviour { public Item scrptbl_obj; public int contained_items = 5; public bool remove_count(int n) { contained_items -= n; if (contained_items == 0) { Destroy(gameObject); return true; } return false; } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/ToolSwing.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ToolSwing : MonoBehaviour { public bool check_col = false; Hotbar_logic hbar; public string affected_tag; private void Start() { hbar = GameObject.Find("Player/Hud/Hotbar").GetComponent<Hotbar_logic>(); } private void OnTriggerStay(Collider other) { if (check_col && other.CompareTag(affected_tag)) { GetHitByTool ghbt = other.GetComponent<GetHitByTool>(); ghbt.GetHit(); hbar.hotbar_slot.remove_Use(); check_col = false; } } } <file_sep>/Assets/Scripts/Multiple_usage/Grill_Logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Grill_Logic : MonoBehaviour { Transform Fuel; public int fuel_state; int[] cooking_slots_s = { -1, -1, -1, -1 }; int[] cooking_slots_l = { -1, -1 }; Transform top; void Start() { top = transform.GetChild(4); Fuel = transform.Find("Fuel"); fuel_state = -1; } public void IncreaseFuel() { if (fuel_state < 3) { fuel_state += 1; Fuel.GetChild(fuel_state).gameObject.SetActive(true); } if (fuel_state == 0) StartCoroutine(Fuel_routine()); } public void DecreaseFuel() { if (fuel_state > -1) { Fuel.GetChild(fuel_state).gameObject.SetActive(false); fuel_state -= 1; } } public bool Add_cookable(Cookable c) { if (c.large == false) { for (int i = 0; i < 4; i++) { if (cooking_slots_s[i] == -1) { cooking_slots_s[i] = 10; Vector3 cookplace_offset = top.GetChild(i).position + new Vector3(0, c.prefab.transform.lossyScale.y / 2); GameObject added_c = Instantiate(c.prefab, cookplace_offset, new Quaternion(0, 0, 0, 0)); added_c.transform.SetParent(top.GetChild(i)); added_c.GetComponent<Collider>().enabled = false; added_c.GetComponent<Rigidbody>().useGravity = false; top.GetChild(i).GetComponent<Cook_slot_logic>().Start_cooking(c.seconds_to_cook); return true; } } } else { for (int i = 0; i < 2; i++) { if (cooking_slots_l[i] == -1) { if (cooking_slots_s[i] == -1 & cooking_slots_s[i + 1] == -1) { cooking_slots_l[i] = 1; Vector3 cookplace_offset = top.GetChild(i).position + new Vector3(0, c.prefab.transform.lossyScale.y / 2); GameObject added_c = Instantiate(c.prefab, cookplace_offset, new Quaternion(0, 0, 0, 0)); added_c.transform.SetParent(top.GetChild(i + 4)); added_c.GetComponent<Collider>().enabled = false; added_c.GetComponent<Rigidbody>().useGravity = false; return true; } } } } return false; } IEnumerator Fuel_routine() { while (fuel_state > -1) { yield return new WaitForSeconds(120); DecreaseFuel(); } } } <file_sep>/Assets/Scriptable_Objects/Placeable.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New_PlaceableItem", menuName = "Items/Craftable/Placeable")] public class Placeable : Craftable { Transform cam_spawn; public GameObject placed_prefab; public new void OnEnable() { base.OnEnable(); cam_spawn = player_reference.transform.Find("Player_cam"); } public override bool Use() { GameObject a = new GameObject(); if (Physics.Raycast(cam_spawn.position, cam_spawn.forward, out RaycastHit t_hit, 5) && t_hit.collider.gameObject.layer == 8) { if (t_hit.point != null) { a = Instantiate(placed_prefab, t_hit.point, new Quaternion()); return true; } } return false; } } <file_sep>/Assets/Scripts/Single_usage/GetHitByTool.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GetHitByTool : MonoBehaviour { public int hits_left; protected void remove_hit() { hits_left -= 1; if (hits_left == 0) Destroy(gameObject); } public virtual void GetHit() { remove_hit(); } } <file_sep>/Assets/Scripts/Multiple_usage/EnemyStates/EnemyAttackState.cs using UnityEngine; public class EnemyAttackState : EnemyAbstractState { public override void EnterState(EnemyAI enemy) { throw new System.NotImplementedException(); } public override void UpdateState(EnemyAI enemy) { throw new System.NotImplementedException(); } } <file_sep>/Assets/Scriptable_Objects/Cookable.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New_EdibleItem", menuName = "Items/Edible/Cookable")] public class Cookable : Edible { public bool large; public float seconds_to_cook; public Edible equivalent; } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Player_grill_usage.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_grill_usage : In_inv { Crosshair_dialog_handler cdial; Player_attributes_handler pattr; Hotbar_logic hbl; public Item fuel; Transform slot = null; Transform aimed_object; Camera cam; private new void Start() { base.Start(); cam = transform.Find("Player_cam").GetComponent<Camera>(); cdial = GetComponent<Crosshair_dialog_handler>(); pattr = GetComponent<Player_attributes_handler>(); hbl = hotbar.GetComponent<Hotbar_logic>(); } private void Update() { Ray cam_ray = cam.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(cam_ray, out RaycastHit hit) && hit.distance < pattr.aiming_distance) { Grill_Logic tsl; aimed_object = hit.transform; if (aimed_object.CompareTag("Fuel")) { tsl = aimed_object.GetComponentInParent<Grill_Logic>(); if (tsl != null) { cdial.Set_cdialog("Brak drewna w ekwipunku"); cdial.Set_dialog_color(new Color(181, 0, 0, 255)); int i; for (i = 0; i < 10; i++) { slot = hotbar.GetChild(i); if (slot.GetComponent<slotManager>().contained_Item == fuel) { cdial.Set_cdialog("Dodaj drewna"); cdial.Set_dialog_color(Color.black); break; } slot = null; } if (slot == null) { for (i = 0; i < 14; i++) { slot = inv.GetChild(i); if (slot.GetComponent<slotManager>().contained_Item == fuel) { cdial.Set_cdialog("Dodaj drewna"); cdial.Set_dialog_color(Color.black); break; } } slot = null; } if (tsl.fuel_state < 3) { cdial.Enablestate(true); if (Input.GetKeyDown(KeyCode.E) && slot != null) { slot.GetComponent<slotManager>().change_quant(-1); tsl.IncreaseFuel(); } else if (Input.GetKeyDown(KeyCode.R)) tsl.DecreaseFuel(); } else if (tsl.fuel_state == 3) cdial.Enablestate(false); } } else if (aimed_object.CompareTag("Grill_top")) { if (hbl.Get_held_item() is Cookable) { tsl = aimed_object.GetComponentInParent<Grill_Logic>(); cdial.Set_cdialog("Połóż jedzenie"); cdial.Set_dialog_color(Color.black); cdial.Enablestate(true); if (Input.GetKeyDown(KeyCode.E)) { bool add_check = tsl.Add_cookable(hbl.Get_held_item() as Cookable); if (add_check) hbl.Get_current_slot().change_quant(-1); } } else cdial.Enablestate(false); } } else { cdial.Enablestate(false); } } } <file_sep>/Assets/Scriptable_Objects/Edible.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New_EdibleItem", menuName = "Items/Edible/Not Cookable")] public class Edible : Item { public float nutrive_value; public float thrist_value; public override bool Use() { Player_attributes_handler pah = player_reference.GetComponent<Player_attributes_handler>(); pah.change_Hunger(nutrive_value); pah.change_Thirst(thrist_value); return true; } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Player_Move.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_Move : MonoBehaviour { public float player_speed; public LayerMask ground; public Transform groundDetector; public float jump_height = 3; public float gravity = -9.81f; private Rigidbody rig; private CharacterController ccontrol; private Vector3 velocity; // Start is called before the first frame update void Start() { rig = GetComponent<Rigidbody>(); ccontrol = GetComponent<CharacterController>(); } // Update is called once per frame void Update() { bool ground_under = Physics.CheckSphere(groundDetector.position, 0.5f, ground); if (ground_under) { if (velocity.y < 0) { velocity.y = -2f; } } if (Input.GetButton("Jump") && ground_under) { velocity.y = Mathf.Sqrt(jump_height * -2f * gravity); } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; ccontrol.Move(move * player_speed * Time.deltaTime); velocity.y += gravity * Time.deltaTime; ccontrol.Move(velocity * Time.deltaTime); } } <file_sep>/Assets/Scripts/Multiple_usage/Tree_GetHit.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tree_GetHit : GetHitByTool { Picking_up_items Pui; public List<Item> drop_items; public Item[] possible_drops; private void Start() { Pui = GameObject.Find("Player").GetComponent<Picking_up_items>(); Generate_drops(); hits_left = drop_items.Count; } private void Generate_drops() { for (int i = 1; i < 6; i++) drop_items.Add(possible_drops[Random.Range(0,2)]); } public override void GetHit() { int rand_drop = Random.Range(0, drop_items.Count); Pui.insert_Item(drop_items[rand_drop], 1); drop_items.RemoveAt(rand_drop); base.GetHit(); } } <file_sep>/Assets/Scripts/Multiple_usage/EnemyStates/EnemyWardState.cs using UnityEngine; public class EnemyWardState : EnemyAbstractState { bool reset_once; public override void EnterState(EnemyAI enemy) { enemy.transform.rotation = new Quaternion(0, 0, 0, 0); } public override void UpdateState(EnemyAI enemy) { if (Vector3.Distance(enemy.player.transform.position, enemy.target.transform.position) <= 25) { enemy.SwitchState(enemy.AlertedState); } } } <file_sep>/Assets/Scripts/Multiple_usage/EnemyStates/EnemyAlertedState.cs using UnityEngine; public class EnemyAlertedState : EnemyAbstractState { public override void EnterState(EnemyAI enemy) { } public override void UpdateState(EnemyAI enemy) { enemy.transform.LookAt(enemy.player.transform); if (Vector3.Distance(enemy.player.transform.position, enemy.target.transform.position) > 25) { enemy.SwitchState(enemy.WardState); } } } <file_sep>/Assets/Scripts/Single_usage/CraftButton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CraftButton : MonoBehaviour { Picking_up_items Pui; Craft_inv_interface Cii; slotManager CraftSelection_Slot; private void Start() { GameObject player = GameObject.Find("Player"); Pui = player.GetComponent<Picking_up_items>(); CraftSelection_Slot = player.transform.Find("Hud/Crafting/CraftingSelected/CraftingSlot").GetComponent<slotManager>(); Cii = player.GetComponent<Craft_inv_interface>(); } public void Craft() { Pui.insert_Item(CraftSelection_Slot.contained_Item, CraftSelection_Slot.quant_Item); gameObject.GetComponent<Button>().interactable = false; gameObject.GetComponent<Button>().interactable = true; Craftable CI = CraftSelection_Slot.contained_Item as Craftable; for (int i = 0; i < CI.Comps.Length; i++) { Cii.remove_component(CI.Comps[i], CI.comp_quants[i]); if (!transform.parent.Find("ViewPort2").GetChild(0).GetChild(i).GetComponent<ComponentPanel>().Refresh()) gameObject.GetComponent<Button>().interactable = false; } } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/In_inv.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class In_inv : MonoBehaviour { protected Transform inv; protected Transform hotbar; protected Transform hud; protected void Start() { hud = transform.Find("Hud"); inv = hud.Find("Inventory/Background"); hotbar = hud.Find("Hotbar"); } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Hotbar_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Hotbar_logic : MonoBehaviour { Player_attributes_handler attr_instance; public slotManagerInv hotbar_slot; Item last_held; bool SpamPreventBool; int Slot_selected = 0; public Transform pov_hldr; private void Start() { attr_instance = transform.parent.parent.GetComponent<Player_attributes_handler>(); hotbar_slot = transform.GetChild(Slot_selected).GetComponent<slotManagerInv>(); Display_update(true); } private void Update() { if (!attr_instance.inMenu) { if (Input.GetKeyDown(KeyCode.Mouse0)) { if (hotbar_slot.contained_Item != null) { if (hotbar_slot.contained_Item is Tool && !SpamPreventBool) { SpamPreventBool = true; StartCoroutine(StopSpam()); StartCoroutine(HitTimeWindow()); hotbar_slot.contained_Item.Use(); pov_hldr.GetChild(0).GetComponent<ToolSwing>().check_col = true; } else if (!(hotbar_slot.contained_Item is Tool)) { if (hotbar_slot.contained_Item.Use()) hotbar_slot.remove_Use(); } } } } pov_holder_update(); } void pov_holder_update() { slotManagerInv hbar_slot = transform.GetChild(Slot_selected).GetComponent<slotManagerInv>(); if (pov_hldr.childCount != 0 && (last_held != hbar_slot.contained_Item || hbar_slot.contained_Item == null)) { GameObject.Destroy(pov_hldr.GetChild(0).gameObject, 0); } if (pov_hldr.childCount == 0) { if (hbar_slot.contained_Item != null) { GameObject item_held = Instantiate(hbar_slot.contained_Item.prefab, new Vector3(0, 0, 0), Quaternion.identity); item_held.transform.SetParent(pov_hldr); item_held.transform.localPosition = new Vector3(0, -item_held.transform.lossyScale.y / 2, 0); item_held.transform.localRotation = Quaternion.Euler(0, 0, 0); if (item_held.GetComponent<Rigidbody>() != null) { item_held.GetComponent<Rigidbody>().useGravity = false; item_held.GetComponent<Rigidbody>().isKinematic = true; if (item_held.GetComponent<Item_logic>().scrptbl_obj is Tool) { foreach (Transform child in item_held.transform) { child.GetComponent<Collider>().isTrigger = true; } } } last_held = hbar_slot.contained_Item; } } } void Display_update(bool display_state) { transform.GetChild(Slot_selected).GetChild(0).gameObject.SetActive(display_state); } public void Set_selection(int x) { if (!attr_instance.inMenu) { Display_update(false); Slot_selected = x; Display_update(true); hotbar_slot = transform.GetChild(Slot_selected).GetComponent<slotManagerInv>(); } } public void Selection_numberUp() { if (!attr_instance.inMenu) { Display_update(false); if (Slot_selected != 9) Slot_selected++; else Slot_selected = 0; Display_update(true); hotbar_slot = transform.GetChild(Slot_selected).GetComponent<slotManagerInv>(); } } public void Selection_numberDown() { if (!attr_instance.inMenu) { Display_update(false); if (Slot_selected != 0) Slot_selected--; else Slot_selected = 9; Display_update(true); hotbar_slot = transform.GetChild(Slot_selected).GetComponent<slotManagerInv>(); } } public Item Get_held_item() { return hotbar_slot.contained_Item; } public slotManagerInv Get_current_slot() { return hotbar_slot.GetComponent<slotManagerInv>(); } IEnumerator HitTimeWindow() { yield return new WaitForSeconds(0.08f); pov_hldr.GetChild(0).GetComponent<ToolSwing>().check_col = false; StopCoroutine(HitTimeWindow()); } IEnumerator StopSpam() { yield return new WaitForSeconds(0.5f); SpamPreventBool = false; StopCoroutine(StopSpam()); } } <file_sep>/Assets/Scripts/Multiple_usage/EnemyAI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyAI : MonoBehaviour { public GameObject player, target; public Quaternion originalrot; public EnemyAbstractState current_state; public EnemyWardState WardState = new EnemyWardState(); public EnemyAlertedState AlertedState = new EnemyAlertedState(); public EnemyChaseState ChaseState = new EnemyChaseState(); public EnemyAttackState AttackState = new EnemyAttackState(); public EnemyGetBackState GetBackState = new EnemyGetBackState(); private void Start() { originalrot = transform.rotation; current_state = WardState; current_state.EnterState(this); } void Update() { current_state.UpdateState(this); } public void SwitchState(EnemyAbstractState newState) { current_state = newState; current_state.EnterState(this); } } <file_sep>/Assets/Scriptable_Objects/Item.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New_Item", menuName = "Items/Item")] public class Item : ScriptableObject { public string item_name; public GameObject prefab; public Sprite inventory_icon; public int max_uses = 1; public int max_stack; public GameObject player_reference; public void OnEnable() { player_reference = GameObject.Find("Player"); } public virtual bool Use() { return false; } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Player_attributes_handler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_attributes_handler : MonoBehaviour { private Transform health_bar; private Transform thirst_bar; private Transform hunger_bar; private float pcurr_hunger, pmax_hunger, pcurr_thirst, pmax_thirst, pcurr_health, pmax_health; public float aiming_distance; public bool inMenu = false; private void Start() { health_bar = GameObject.Find("Hud/Health/Bar").transform; thirst_bar = GameObject.Find("Hud/Thirst/Bar").transform; hunger_bar = GameObject.Find("Hud/Hunger/Bar").transform; pcurr_health = pmax_health = 100; pcurr_thirst = pmax_thirst = 100; pcurr_hunger = pmax_hunger = 100; pcurr_thirst = 20; pcurr_hunger = 20; aiming_distance = 3f; } public void change_Health(float x) { if (pcurr_health + x > pmax_health) pcurr_health = pmax_health; else if (pcurr_health + x < 0) pcurr_health = 0; else pcurr_health += x; update_Bar(pcurr_health, pmax_health, health_bar); } public void change_Thirst(float x) { if (pcurr_thirst + x > pmax_thirst) pcurr_thirst = pmax_thirst; else if (pcurr_thirst + x < 0) pcurr_thirst = 0; else pcurr_thirst += x; update_Bar(pcurr_thirst, pmax_thirst, thirst_bar); } public void change_Hunger(float x) { if (pcurr_hunger + x > pmax_hunger) pcurr_hunger = pmax_hunger; else if (pcurr_hunger + x < 0) pcurr_hunger = 0; else pcurr_hunger += x; update_Bar(pcurr_hunger, pmax_hunger, hunger_bar); } private void update_Bar(float curr, float max, Transform bar) { float ratio = curr / max; bar.localScale = new Vector3(ratio, 1, 1); } } <file_sep>/Assets/Scripts/Single_usage/CraftSelReset.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CraftSelReset : MonoBehaviour { public void Reset() { Transform Cslot = transform.Find("CraftingSlot"); Cslot.GetComponent<slotManager>().change_Item(null); Cslot.GetComponent<slotManager>().set_quant(0); Cslot.Find("Item_image").gameObject.SetActive(false); } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Debuging.cs using UnityEngine; public class Debuging : MonoBehaviour { Player_attributes_handler attr_instance; Picking_up_items Picking_up; Hotbar_logic hbar_instance; Selection_slot_logic sel_slot; public Item item; private void Start() { attr_instance = GetComponent<Player_attributes_handler>(); Picking_up = GetComponent<Picking_up_items>(); hbar_instance = transform.Find("Hud/Hotbar").GetComponent<Hotbar_logic>(); sel_slot = transform.Find("Hud/Inventory/Selection").GetComponent<Selection_slot_logic>(); } // Update is called once per frame private void Update() { if (Input.GetKeyDown(KeyCode.L)) Picking_up.insert_Item(item, 1); if (Input.GetKeyDown(KeyCode.Q)) Application.Quit(); if (Input.GetKeyDown(KeyCode.C)) { Transform craft = transform.Find("Hud/Crafting"); if (craft != null) { if (attr_instance.inMenu && craft.gameObject.activeSelf) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; attr_instance.inMenu = false; craft.gameObject.SetActive(false); transform.Find("Hud/Panel").gameObject.SetActive(false); } else if (!attr_instance.inMenu && !craft.gameObject.activeSelf) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; attr_instance.inMenu = true; craft.gameObject.SetActive(true); craft.Find("CraftingSelected").GetComponent<CraftSelReset>().Reset(); craft.Find("ViewPort2").GetComponent<CraftArrayLogic>().Clear(); transform.Find("Hud/Panel").gameObject.SetActive(true); } } } if (Input.GetKeyDown(KeyCode.Tab)) { Transform inv = transform.Find("Hud/Inventory"); if (inv != null) { if (attr_instance.inMenu && inv.gameObject.activeSelf) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; attr_instance.inMenu = false; sel_slot.Reset_Selection(); transform.Find("Hud/Inventory").gameObject.SetActive(false); transform.Find("Hud/Panel").gameObject.SetActive(false); } else if (!attr_instance.inMenu && !inv.gameObject.activeSelf) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; attr_instance.inMenu = true; transform.Find("Hud/Inventory").gameObject.SetActive(true); transform.Find("Hud/Panel").gameObject.SetActive(true); } } } if (!attr_instance.inMenu) { if (Input.GetKeyDown(KeyCode.Alpha1)) { hbar_instance.Set_selection(0); } else if (Input.GetKeyDown(KeyCode.Alpha2)) { hbar_instance.Set_selection(1); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { hbar_instance.Set_selection(2); } else if (Input.GetKeyDown(KeyCode.Alpha4)) { hbar_instance.Set_selection(3); } else if (Input.GetKeyDown(KeyCode.Alpha5)) { hbar_instance.Set_selection(4); } else if (Input.GetKeyDown(KeyCode.Alpha6)) { hbar_instance.Set_selection(5); } else if (Input.GetKeyDown(KeyCode.Alpha7)) { hbar_instance.Set_selection(6); } else if (Input.GetKeyDown(KeyCode.Alpha8)) { hbar_instance.Set_selection(7); } else if (Input.GetKeyDown(KeyCode.Alpha9)) { hbar_instance.Set_selection(8); } else if (Input.GetKeyDown(KeyCode.Alpha0)) { hbar_instance.Set_selection(9); } if (Input.mouseScrollDelta.y > 0) { hbar_instance.Selection_numberUp(); } else if (Input.mouseScrollDelta.y < 0) { hbar_instance.Selection_numberDown(); } } } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Mouse_Look.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mouse_Look : MonoBehaviour { public Transform cam; public Transform pov_holder; public float mouse_sens_x; public float mouse_sens_y; private float xRotation = 0f; Player_attributes_handler pattr; // Start is called before the first frame update void Start() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; pattr = GetComponent<Player_attributes_handler>(); } // Update is called once per frame void Update() { if (!pattr.inMenu) { float mouseX = Input.GetAxis("Mouse X") * mouse_sens_x * 100 * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * mouse_sens_y * 100 * Time.deltaTime; xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 65f); cam.localRotation = Quaternion.Euler(xRotation, 0f, 0f); transform.Rotate(Vector3.up * mouseX); } } }<file_sep>/Assets/Scripts/Single_usage/slotManager.cs using UnityEngine; using UnityEngine.UI; public class slotManager : MonoBehaviour { public Item contained_Item; public int quant_Item; public int current_uses; public bool TurnOffUpdate; protected Transform qnt; protected Transform its; protected void Start() { qnt = transform.Find("Quantity"); its = transform.Find("Item_image"); if (TurnOffUpdate) { its.GetComponent<Image>().sprite = contained_Item.inventory_icon; its.gameObject.SetActive(true); } } private void Update() { if (!TurnOffUpdate) Display_Update(); } public void exchange(slotManager s) { int temp_quant = s.quant_Item; int temp_uses = s.current_uses; Item temp_contained = s.contained_Item; s.quant_Item = quant_Item; s.change_Item(contained_Item); s.current_uses = current_uses; quant_Item = temp_quant; change_Item(temp_contained); current_uses = temp_uses; } public void change_Item(Item x, int i = 0) { contained_Item = x; if (i == 1) Start(); if (contained_Item != null) its.GetComponent<Image>().sprite = contained_Item.inventory_icon; else its.GetComponent<Image>().sprite = null; } public void set_quant(int n) { quant_Item = n; } public void change_quant(int n) { quant_Item += n; } public void Display_Update() { if (quant_Item == 0) contained_Item = null; if (qnt != null && its != null) { if (quant_Item > 1) { qnt.GetComponent<Text>().text = quant_Item.ToString(); if (qnt.gameObject.activeSelf != true) qnt.gameObject.SetActive(true); if (its.gameObject.activeSelf != true) its.gameObject.SetActive(true); } else if (quant_Item <= 1) { if (qnt.gameObject.activeSelf != false) qnt.gameObject.SetActive(false); if (quant_Item == 1) { qnt.GetComponent<Text>().text = quant_Item.ToString(); if (its.gameObject.activeSelf != true) its.gameObject.SetActive(true); } else if (quant_Item == 0) { if (its.gameObject.activeSelf != false) its.gameObject.SetActive(false); } } } } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Crosshair_dialog_handler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Crosshair_dialog_handler : MonoBehaviour { Transform cdialog; Text text_cmp; string[] Ignored_tags = new string[] {"Untagged"}; Camera cam; private void Start() { cdialog = transform.Find("Hud").Find("Pick_up_dialog"); text_cmp = cdialog.GetComponent<Text>(); cam = transform.Find("Player_cam").GetComponent<Camera>(); } private void Update() { Ray cam_ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(cam_ray, out hit) && hit.distance < 3f) { Transform aimed_object = hit.transform; for (int i = 0; i < Ignored_tags.Length; i++) { if (aimed_object.CompareTag(Ignored_tags[i])) { Set_cdialog(""); Enablestate(false); break; } } } } public void Set_cdialog(string a) { text_cmp.text = a; } public void Add_text(string a) { text_cmp.text += a; } public void Set_dialog_color(Color c) { text_cmp.color = c; } public void Enablestate(bool b) { cdialog.gameObject.SetActive(b); } } <file_sep>/Assets/Scripts/Multiple_usage/slotManagerInv.cs using UnityEngine; using UnityEngine.EventSystems; public class slotManagerInv : slotManager, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler { slotManager Selection_slotsm; Selection_slot_logic Selection_slotl; Picking_up_items pui_script; Transform Hotbar; slotManagerInv hotbar_slot = null; GameObject inv; bool cursor_Over = false; private new void Start() { base.Start(); Selection_slotsm = GameObject.Find("Player/Hud/Inventory/Selection").GetComponent<slotManager>(); Selection_slotl = GameObject.Find("Player/Hud/Inventory/Selection").GetComponent<Selection_slot_logic>(); pui_script = GameObject.Find("Player").GetComponent<Picking_up_items>(); Hotbar = GameObject.Find("Player/Hud/Hotbar").transform; inv = GameObject.Find("Player/Hud/Inventory"); } private void Update() { if (contained_Item != null && current_uses == 0) { quant_Item -= 1; current_uses = contained_Item.max_uses; } if (cursor_Over) { if (Input.GetKeyDown(KeyCode.Alpha1)) { hotbar_slot = Hotbar.GetChild(0).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha2)) { hotbar_slot = Hotbar.GetChild(1).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { hotbar_slot = Hotbar.GetChild(2).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha4)) { hotbar_slot = Hotbar.GetChild(3).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha5)) { hotbar_slot = Hotbar.GetChild(4).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha6)) { hotbar_slot = Hotbar.GetChild(5).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha7)) { hotbar_slot = Hotbar.GetChild(6).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha8)) { hotbar_slot = Hotbar.GetChild(7).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha9)) { hotbar_slot = Hotbar.GetChild(8).GetComponent<slotManagerInv>(); } else if (Input.GetKeyDown(KeyCode.Alpha0)) { hotbar_slot = Hotbar.GetChild(9).GetComponent<slotManagerInv>(); } if (hotbar_slot != null) exchange(hotbar_slot); hotbar_slot = null; } Display_Update(); } public void change_Item(Item x) { base.change_Item(x); current_uses = x.max_uses; } public void remove_Use() { current_uses -= 1; } public void OnPointerClick(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Left && inv.activeSelf) { if (Selection_slotsm.contained_Item == null && contained_Item != null) { Selection_slotsm.change_Item(contained_Item); Selection_slotsm.set_quant(quant_Item); set_quant(0); Selection_slotl.Prev_slot = transform.GetComponent<slotManagerInv>(); } else if (Selection_slotsm.contained_Item != null) { if (contained_Item == Selection_slotsm.contained_Item) { if (Selection_slotsm.quant_Item == 20 || quant_Item == 20 && Selection_slotsm.quant_Item != quant_Item) { int temp = Selection_slotsm.quant_Item; Selection_slotsm.set_quant(quant_Item); set_quant(temp); } else if(quant_Item < 20) { int quant_toAdd = pui_script._place_checker_helper(transform, Selection_slotsm.contained_Item, Selection_slotsm.quant_Item); Selection_slotsm.change_quant(-quant_toAdd); change_quant(quant_toAdd); } } else if (contained_Item == null) { change_Item(Selection_slotsm.contained_Item); set_quant(Selection_slotsm.quant_Item); Selection_slotsm.set_quant(0); Selection_slotsm.change_Item(null); } else if (contained_Item != Selection_slotsm.contained_Item) { exchange(Selection_slotsm); } } } else if (eventData.button == PointerEventData.InputButton.Right) { if (Selection_slotsm.contained_Item == null && contained_Item != null) { Selection_slotsm.change_Item(contained_Item); int half = (int)Mathf.Ceil((float)quant_Item / 2); Selection_slotsm.set_quant(half); change_quant(-half); Selection_slotl.Prev_slot = transform.GetComponent<slotManagerInv>(); } else if (Selection_slotsm.contained_Item != null) { if (Selection_slotsm.contained_Item == contained_Item || contained_Item == null) { if (contained_Item == null) change_Item(Selection_slotsm.contained_Item); int quant_toAdd = pui_script._place_checker_helper(transform, Selection_slotsm.contained_Item, 1); Selection_slotsm.change_quant(-quant_toAdd); change_quant(quant_toAdd); } else if (contained_Item != Selection_slotsm.contained_Item) { exchange(Selection_slotsm); } } } } public void OnPointerEnter(PointerEventData eventData) { if (!cursor_Over) cursor_Over = true; } public void OnPointerExit(PointerEventData eventData) { if (cursor_Over) cursor_Over = false; } } <file_sep>/Assets/Scriptable_Objects/Craftable.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Craftable : Item { public Item[] Comps; public int[] comp_quants; } <file_sep>/Assets/Scripts/Multiple_usage/CraftingPanel_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class CraftingPanel_logic : MonoBehaviour, IPointerClickHandler { CraftArrayLogic CAL; Craftable CraftItem; Button CreateBtn; Transform CraftSel; void Start() { transform.GetChild(1).GetComponent<Text>().text = transform.GetChild(0).GetComponent<slotManager>().contained_Item.item_name; Transform Craftmenu = transform.parent.parent.parent; CAL = Craftmenu.Find("ViewPort2").GetComponent<CraftArrayLogic>(); CraftItem = transform.Find("CraftingSlot").GetComponent<slotManager>().contained_Item as Craftable; CraftSel = Craftmenu.Find("CraftingSelected"); CreateBtn = Craftmenu.Find("MakeBtn").GetComponent<Button>(); } public void OnPointerClick(PointerEventData eventData) { CreateBtn.interactable = true; CAL.Clear(); CraftSel.Find("CraftingSlot").GetComponent<slotManager>().change_Item(CraftItem); CraftSel.Find("Text").GetComponent<Text>().text = CraftItem.item_name; CraftSel.Find("CraftingSlot").GetComponent<slotManager>().set_quant(1); for (int i = 0; i < CraftItem.Comps.Length; i++) { if (!CAL.Add(CraftItem.Comps[i], CraftItem.comp_quants[i])) { CreateBtn.interactable = false; } } } } <file_sep>/Assets/Scriptable_Objects/Tool.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New_PlaceableItem", menuName = "Items/Craftable/Tool")] public class Tool : Craftable { public string anim_name; public override bool Use() { Transform pholder = player_reference.transform.Find("Player_cam").Find("Pov_holder"); if (pholder != null && pholder.childCount != 0) { pholder.GetChild(0).GetComponent<Animator>().Play(anim_name, -1, 0f); return false; } return false; } } <file_sep>/Assets/Scripts/Multiple_usage/ComponentPanel.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ComponentPanel : MonoBehaviour { public int requiredQuant; slotManager panel_sm; Text text; Craft_inv_interface icount; public void Start() { panel_sm = transform.GetChild(0).GetComponent<slotManager>(); text = transform.GetChild(1).GetComponent<Text>(); icount = GameObject.Find("Player").GetComponent<Craft_inv_interface>(); } public void setItem(Item x) { panel_sm.change_Item(x, 1); } public void setRequiredQuant(int a) { requiredQuant = a; } public bool Refresh() { Item i = panel_sm.contained_Item; int item_ininv = icount.GetCount(i); text.text = $"{i.item_name} {item_ininv} / {requiredQuant}"; if (item_ininv < requiredQuant) { text.color = new Color(181, 0, 0, 255); return false; } return true; } } <file_sep>/Assets/Scripts/Single_usage/CraftArrayLogic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CraftArrayLogic : MonoBehaviour { public GameObject ComponentPanel; Transform ContentPanel, TextField; void Start() { ContentPanel = transform.Find("Content"); } public bool Add(Item i, int q) { GameObject cp = Instantiate(ComponentPanel, ContentPanel); ComponentPanel cps = cp.GetComponent<ComponentPanel>(); cps.Start(); cps.setItem(i); cps.setRequiredQuant(q); bool can_craft = cps.Refresh(); return can_craft; } public void Clear() { foreach (Transform child in transform.GetChild(0)) { Destroy(child.gameObject); } } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Dropping_items_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class Dropping_items_logic : MonoBehaviour { public bool outside_inv; public Camera player_view; slotManager selection_slot; private void Start() { selection_slot = transform.GetChild(7).GetChild(2).GetComponent<slotManager>(); } private void Update() { if (Input.GetKeyDown(KeyCode.Mouse0) || Input.GetKeyDown(KeyCode.Mouse1)) { if (selection_slot.contained_Item != null && outside_inv) { if (selection_slot.contained_Item is Placeable) drop_item(selection_slot.contained_Item.prefab, selection_slot.quant_Item, selection_slot.contained_Item); else drop_item(selection_slot.contained_Item.prefab, selection_slot.quant_Item); selection_slot.set_quant(0); } } } public void drop_item(GameObject item_prefab, int quant, Item Scrptbl = null) { Vector3 inst_pos = player_view.transform.position + player_view.transform.forward * 2; GameObject dropped = Instantiate(item_prefab, inst_pos, Quaternion.identity); dropped.GetComponent<Item_logic>().contained_items = quant; if (dropped.GetComponent<Item_logic>().scrptbl_obj is Tool) dropped.GetComponent<Animator>().enabled = false; if (Scrptbl != null) dropped.GetComponent<Item_logic>().scrptbl_obj = Scrptbl; } } <file_sep>/Assets/Scripts/Multiple_usage/Cook_slot_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cook_slot_logic : MonoBehaviour { Grill_Logic gl; Cookable ca_obj; // Start is called before the first frame update void Start() { gl = transform.parent.parent.GetComponent<Grill_Logic>(); } // Update is called once per frame void Update() { } public void Start_cooking(float x) { StartCoroutine(Cook_routine(x)); } IEnumerator Cook_routine(float x) { float ttc = x; while (ttc > 0f) { yield return new WaitForSeconds(.1f); if (gl.fuel_state > -1) ttc -= .1f; } Transform ca = transform.GetChild(0); Cookable ca_obj = ca.GetComponent<Item_logic>().scrptbl_obj as Cookable; GameObject cooked = Instantiate(ca_obj.equivalent.prefab, ca.position, ca.rotation, transform); cooked.transform.localScale = ca.localScale; cooked.GetComponent<Rigidbody>().useGravity=false; Destroy(ca.gameObject); } } <file_sep>/Assets/Scripts/Single_usage/Player_Scripts/Picking_up_items.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Picking_up_items : In_inv { Player_attributes_handler pattr; Dropping_items_logic drp; Crosshair_dialog_handler cdial; Camera cam; struct partial_pickup_info { public Transform slot; public int pickeditem_no; } private new void Start() { base.Start(); cam = transform.Find("Player_cam").GetComponent<Camera>(); pattr = GetComponent<Player_attributes_handler>(); drp = hud.GetComponent<Dropping_items_logic>(); cdial = GetComponent<Crosshair_dialog_handler>(); } void Update() { Ray cam_ray = cam.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(cam_ray, out RaycastHit hit) && hit.distance < pattr.aiming_distance && !pattr.inMenu) { Transform aimed_object = hit.transform; if (aimed_object.CompareTag("Pickable")) { Item_logic dropped_item = aimed_object.GetComponent<Item_logic>(); partial_pickup_info info = place_checker(dropped_item.scrptbl_obj, dropped_item.contained_items); Transform slot = info.slot; cdial.Set_cdialog($"Podnieś {dropped_item.scrptbl_obj.item_name}"); if (dropped_item.contained_items > 1) cdial.Add_text($" ({dropped_item.contained_items})"); if (slot == null) { cdial.Add_text(" (brak miejsca)"); cdial.Set_dialog_color(new Color(181, 0, 0, 255)); } else { cdial.Set_dialog_color(Color.black); } cdial.Enablestate(true); if (Input.GetKeyDown(KeyCode.E) && slot != null) { insert_Item(dropped_item); } } cdial.Enablestate(true); } else { cdial.Enablestate(false); } } public int _place_checker_helper(Transform slot, Item item, int item_ammount) { slotManager SM = slot.GetComponent<slotManager>(); if (SM.contained_Item == item || SM.contained_Item == null) { if (SM.quant_Item + item_ammount <= item.max_stack) { return item_ammount; } else if (SM.quant_Item + item_ammount > item.max_stack && SM.quant_Item < item.max_stack) { return item.max_stack - SM.quant_Item; } } return 0; } public void insert_Item(Item_logic dropped_item) { partial_pickup_info info; Transform slot; bool stop_pickingup = false; while (!stop_pickingup) { info = place_checker(dropped_item.scrptbl_obj, dropped_item.contained_items); slot = info.slot; if (slot != null) { slotManagerInv SM = slot.GetComponent<slotManagerInv>(); SM.change_Item(dropped_item.scrptbl_obj); SM.change_quant(info.pickeditem_no); stop_pickingup = dropped_item.remove_count(info.pickeditem_no); } if (slot == inv.GetChild(inv.childCount - 1) || slot == null) stop_pickingup = true; } } public void insert_Item(Item script_obj, int quant) { partial_pickup_info info; Transform slot; bool stop_pickingup = false; while (!stop_pickingup) { info = place_checker(script_obj, quant); slot = info.slot; if (slot != null) { slotManagerInv SM = slot.GetComponent<slotManagerInv>(); SM.change_Item(script_obj); SM.change_quant(info.pickeditem_no); quant -= info.pickeditem_no; if (quant == 0) stop_pickingup = true; } if (slot == inv.GetChild(inv.childCount - 1) || slot == null) stop_pickingup = true; } if (quant > 0) { drp.drop_item(script_obj.prefab, quant); } } partial_pickup_info place_checker(Item item, int item_ammount) { partial_pickup_info pChecker_result; int isPlace_result; foreach (Transform child in hotbar) { isPlace_result = _place_checker_helper(child, item, item_ammount); if (isPlace_result > 0) { pChecker_result.slot = child; pChecker_result.pickeditem_no = isPlace_result; return pChecker_result; } } foreach (Transform child in inv) { isPlace_result = _place_checker_helper(child, item, item_ammount); if (isPlace_result > 0) { pChecker_result.slot = child; pChecker_result.pickeditem_no = isPlace_result; return pChecker_result; } } pChecker_result.slot = null; pChecker_result.pickeditem_no = 0; return pChecker_result; } } <file_sep>/Assets/Scripts/Single_usage/Selection_slot_logic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Selection_slot_logic : MonoBehaviour { public slotManagerInv Prev_slot; slotManager self_sm; private void Start() { self_sm = transform.GetComponent<slotManager>(); } // Update is called once per frame void Update() { transform.position = Input.mousePosition; } public void Reset_Selection() { if (self_sm.contained_Item != null) { Prev_slot.change_Item(self_sm.contained_Item); Prev_slot.set_quant(self_sm.quant_Item); self_sm.change_Item(null); self_sm.set_quant(0); self_sm.Display_Update(); } } }<file_sep>/Assets/Scripts/Multiple_usage/Enemy_GetHit.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy_GetHit : GetHitByTool { // Update is called once per frame void Update() { } public override void GetHit() { base.GetHit(); } } <file_sep>/Assets/Scripts/Multiple_usage/EnemyStates/EnemyAbstractState.cs using UnityEngine; public abstract class EnemyAbstractState { public abstract void EnterState(EnemyAI enemy); public abstract void UpdateState(EnemyAI enemy); }
07332f5821a00022fe2369865a5a888d95b96b7e
[ "C#" ]
38
C#
TTus-dev/Survival-unity-project
f5769bd68666cdd28c8da27ce02eaa8d547565a4
7f6ed74042c164545876907f90feb5720e3834e3
refs/heads/master
<file_sep>package com.lanwei.es.jetty; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; /** * * @author alexmu */ public class ServerStartup { private static final String HOST = "172.16.1.12"; private static final Integer PORT = 28080; private static final Integer POOL_SIZE = 8; static Server server = null; public static void startup() throws Exception { server.start(); server.join(); } public static void init() throws Exception { Connector connector = new SelectChannelConnector(); connector.setHost(HOST); connector.setPort(PORT); server = new Server(); server.setConnectors(new Connector[]{connector}); server.setThreadPool(new QueuedThreadPool(POOL_SIZE)); ContextHandler dataLoadContext = new ContextHandler("/spider"); ServerHandler dataDispatchHandler = ServerHandler.getDataDispatchHandler(); if (dataDispatchHandler == null) { throw new Exception("initializing dataDispatchHandler is failed"); } dataLoadContext.setHandler(dataDispatchHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[]{dataLoadContext}); server.setHandler(contexts); } public static void stop() { try { server.stop(); } catch (Exception ex) { } ServerHandler dataDispatchHandler = ServerHandler.getDataDispatchHandler(); dataDispatchHandler.shutdown(); } } <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.lanwei</groupId> <artifactId>es</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <!-- 编码 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <!-- jdk 1.8 --> <profiles> <profile> <id>jdk18</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile> </profiles> <dependencies> <!-- es检索 --> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>2.3.4</version> </dependency> <!-- 爬虫 --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.9.2</version> </dependency> <!-- json相关 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.11</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <!-- jdbc 相关--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!-- redis操作 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- 定时任务 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <!-- ftp相关 --> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.3</version> </dependency> <!-- jetty相关 --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>8.1.14.v20131031</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlets</artifactId> <version>8.1.14.v20131031</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.19.Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.6</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>servlet-api</artifactId> <version>3.0.20100224</version> </dependency> <!-- httpClient4.5 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.5</version> </dependency> </dependencies> <build> <finalName>es</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF8</encoding> <compilerVersion>1.8</compilerVersion> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <appendAssemblyId>false</appendAssemblyId> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.lanwei.es.quartz.QuartzMain</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>assembly</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>package com.lanwei.es.util; import com.alibaba.fastjson.JSONObject; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import java.io.IOException; import java.net.InetAddress; import java.util.Date; import java.util.Set; import java.util.concurrent.ExecutionException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * @作者: liuxinyun * @日期: 2017/6/28 10:49 * @描述: */ public class EsUtil { private static TransportClient client; private static final String[] nodes = new String[]{"172.16.1.11:9300", "172.16.1.12:9300"}; private static final String clusterName = "haq-es"; static Settings settings = Settings.settingsBuilder() .put("cluster.name", clusterName) .put("client.transport.sniff", true) .build(); static { try { client = TransportClient.builder().settings(settings).build(); for (String node : nodes) { String ip = node.split(":")[0]; Integer port = Integer.valueOf(node.split(":")[1]); client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip), port)); } }catch (Exception e){ e.printStackTrace(); } } /** * 单例模式 * @return */ public static synchronized TransportClient getClient(){ return client; } /** * 关闭 */ public static void close() { client.close(); } /** * 创建索引 * @param indexName 索引名称 * @param shardNum 分片数量 * @param replicaNum 副本数量 * @return * @throws IOException */ public static boolean createIndex(String indexName, int shardNum, int replicaNum) throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("settings") .field("number_of_shards", shardNum)//设置分片数量 .field("number_of_replicas", replicaNum)//设置副本数量 .endObject() .endObject(); System.out.println(mapping.string()); CreateIndexRequestBuilder cirb = client .admin() .indices() .prepareCreate(indexName)//index名称 .setSource(mapping); CreateIndexResponse response = cirb.execute().actionGet(); if (response.isAcknowledged()) { return true; } else { return false; } } /** * 插入对象 * @param indexName * @param type * @param o * @throws IOException */ public static void insertObject(String indexName, String type, Object o) throws IOException { IndexResponse response = client //prepareIndex(索引库名,索引type,指定id) .prepareIndex(indexName, type) .setSource(JSONObject.toJSONString(o)).get(); if (response.isCreated()) { System.out.println("index:" + response.getIndex() + " insert doc id:" + response.getId() + " result:" + response.isCreated()); } else { System.out.println("created failed."); } } /** * 插入Json字符串 * @param indexName * @param type * @param str * @throws IOException */ public static void insertString(String indexName, String type, String str) throws IOException { IndexResponse response = getClient() //prepareIndex(索引库名,索引type,指定id) .prepareIndex(indexName, type) .setSource(str).get(); if (response.isCreated()) { System.out.println("index:" + response.getIndex() + " insert doc id:" + response.getId() + " result:" + response.isCreated()); } else { System.out.println("created failed."); } } /** * 查询文档 */ public void getDocument() { GetResponse response = client.prepareGet("javaapi-index1", "log", "1").get(); String source = response.getSource().toString(); long version = response.getVersion(); String indexName = response.getIndex(); String type = response.getType(); String id = response.getId(); System.out.println("source:" + source + ", version:" + version + ", index name:" + indexName + ", type:" + type + ", id:" + id); } //强制修改 public void updateDocForcely(String indexName, String type, String id) throws IOException, InterruptedException, ExecutionException { UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index(indexName); updateRequest.type(type); updateRequest.id(id); updateRequest.doc(jsonBuilder() .startObject() .field("type", "file") .endObject()); client.update(updateRequest).get(); } //不存在泽创建,存在则修改 public void updateOrCreateDoc(String indexName, String type, String id) throws IOException, InterruptedException, ExecutionException { IndexRequest indexRequest = new IndexRequest(indexName, type, id) .source(jsonBuilder() .startObject() .field("type", type) .field("eventCount", 2) .field("eventDate", new Date()) .field("message", "secilog insert doc test") .endObject()); UpdateRequest updateRequest = new UpdateRequest(indexName, type, id) .doc(jsonBuilder() .startObject() .field("type", "file") .endObject()) .upsert(indexRequest); client.update(updateRequest).get(); } /** * 根据id删除文档 * @param indexName * @param type * @param id * @return */ public static boolean deleteDocumentByID(String indexName, String type, String id) { DeleteResponse dresponse = client.prepareDelete(indexName, type, id).execute().actionGet(); return dresponse.isFound(); //文档存在返回true,不存在返回false; } /** * 删除指定索引名 * @param indexName * @return */ public static boolean deleteIndex(String indexName) { DeleteIndexRequest delReq = new DeleteIndexRequest(indexName); DeleteIndexResponse response = null; try { response = client.admin().indices().delete(delReq).actionGet(); } catch (Exception ex) { System.out.println("IndexNotFoundException[no such index:" + indexName + "]"); return false; } return true; } /** * 删除除了某些索引之外的所有索引 * @param without */ public static void deleteIndicesWithout(Set<String> without) { ClusterStateResponse response = client.admin().cluster() .prepareState() .execute().actionGet(); //获取所有索引 String[] indexs = response.getState().getMetaData().getConcreteAllIndices(); for (String index : indexs) { if (without.contains(index)) { continue; } System.out.println(index + " delete");// //清空所有索引。 DeleteIndexResponse deleteIndexResponse = client.admin().indices() .prepareDelete(index) .execute().actionGet(); System.out.println(deleteIndexResponse.getHeaders()); } } /** * 清空指定索引的缓存 * @param indexName * @return */ public static boolean clearIndicesCache(String indexName) { ClearIndicesCacheResponse response = null; try { response = client.admin().indices() .clearCache(new ClearIndicesCacheRequest(indexName) .fieldDataCache(true). queryCache(true). requestCache(true) ).actionGet(); BytesStreamOutput bso = new BytesStreamOutput(); response.writeTo(bso); System.out.println("clear res:" + bso.bytes().toUtf8()); if (response.getFailedShards() > 0) { return false; } return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 删除所有索引 */ public static void deleteAllIndices() { ClusterStateResponse response = client.admin().cluster() .prepareState() .execute().actionGet(); //获取所有索引 String[] indexs = response.getState().getMetaData().getConcreteAllIndices(); for (String index : indexs) { System.out.println(index + " delete");// //清空所有索引。 DeleteIndexResponse deleteIndexResponse = client.admin().indices() .prepareDelete(index) .execute().actionGet(); System.out.println(deleteIndexResponse.getHeaders()); } } } <file_sep>package com.lanwei.es.quartz; import com.lanwei.es.jetty.ServerStartup; import com.lanwei.es.util.SpiderUtil; /** * @作者:刘新运 * @日期:2017/6/28 0:28 * @描述:类 */ public class QuartzMain { public static void main(String[] args) { //jetty Thread t = new Thread(new Runnable() { @Override public void run() { try { ServerStartup.init(); ServerStartup.startup(); } catch (Exception e) { e.printStackTrace(); } } }); t.start(); //定时任务 SpiderUtil.nowSpider(); QuartzSpider qs = new QuartzSpider(); String jobName = "spider"; try { //每30分钟执行一次 QuartzManager.addJob(qs, jobName, "0 0/30 * * * ?"); QuartzManager.start(); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.lanwei.es.quartz; import com.lanwei.es.spider.Spider; import com.lanwei.es.spider.WebEntity; import com.lanwei.es.util.MysqlUtil; import com.lanwei.es.util.RedisUtil; import com.lanwei.es.util.SpiderUtil; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import redis.clients.jedis.Jedis; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @作者:刘新运 * @日期:2017/6/28 0:19 * @描述:类 */ public class QuartzSpider implements Job { public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{ SpiderUtil.nowSpider(); } }
537e088443d2e8e75c51d19c6fefc1b6581c657a
[ "Java", "Maven POM" ]
5
Java
newSue/es-1
a5b5345c8b54a0e0525229951039dfaaefcce501
5120eaaa83a782768809635f6ad9815051989775
refs/heads/master
<file_sep>package com.epam.scripps.channels.cookingchannel.tests; import com.epam.scripps.utils.ConfigReader; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import java.util.concurrent.TimeUnit; /** * Created by Iurii_Galias on 6/11/2015. */ public class PreparingConfiguration { protected static WebDriver driver; protected static String home = ConfigReader.getStringFromFile("dev.env.home"); protected static String liveTv = ConfigReader.getStringFromFile("dev.env.live"); protected static String optName = ConfigReader.getStringFromFile("opt.name"); protected static String optPass = ConfigReader.getStringFromFile("opt.pass"); protected static WebDriver getDriver() { if (driver == null){ driver = chooseDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS).pageLoadTimeout(15,TimeUnit.SECONDS); driver.manage().window().maximize(); } return driver; } private static WebDriver chooseDriver() { String browser = java.lang.System.getProperties().getProperty("webbrowser"); if (browser == null) { browser = "firefox"; } if (browser.equalsIgnoreCase("firefox")) { driver = new FirefoxDriver(); } return driver; } @BeforeClass public void preparation() { driver = getDriver(); } @AfterSuite public void tearDown() { driver.quit(); } } <file_sep>package com.epam.scripps.channels.cookingchannel.pages; import com.epam.scripps.channels.cookingchannel.pages.authentication.ProvidersPopUp; import com.epam.scripps.utils.Utils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; /** * Created by Iurii_Galias on 6/11/2015. */ public class MainPage { protected static WebDriver driver; @FindBy(id = "logo") protected WebElement logo; @FindBy(xpath = "//*[contains(text(),'Full Episodes')]") protected WebElement fullEpisodesButton; @FindBy(xpath = "//*[contains(text(),'Shows')]") protected WebElement showButton; @FindBy(xpath = ".//*[@id='showsWrapper']/ul[1]/li[1]/a") protected WebElement firstShows; @FindBy(xpath = "//*[contains(text(),'LIVE TV')]") protected WebElement liveTvButton; @FindBy(id = "logIn") protected WebElement signInButton; @FindBy(className = "icon-auth-required") protected WebElement iconKey; @FindBy(id = "leadCarousel") protected WebElement leadCarousel; @FindBy(className = "rsArrowIcn ss-navigateright") protected WebElement mainCarouselNavigationRight; @FindBy(className = "rsArrowIcn ss-navigateleft") protected WebElement mainCarouselNavigationLeft; @FindBy(xpath = "//*[contains(text(),'More Videos')]") protected WebElement moreVideosButton; @FindBy(xpath = ".//*[@id='mvpd-logo-href']/img") protected WebElement optimumLogo; @FindBy(id = "logOut") protected WebElement signOutButton; //==================================================================== public MainPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } //==================================================================== static methods public static String checkUrl() { return driver.getCurrentUrl(); } //==================================================================== other methods public boolean mainPageChecking() { return Utils.isElementPresent(leadCarousel); } public boolean signInChecking() { Utils.waitForElementPresent(driver,signInButton, 15, 5); return Utils.isElementPresent(signInButton) && Utils.isElementPresent(iconKey); } public boolean isAuthorized() { Utils.waitForElementPresent(driver, optimumLogo, 15, 5); return Utils.isElementPresent(optimumLogo); } public void getUrl(String url) { driver.get(url); } public ParentPage moveToParentPage() { logo.click(); return PageFactory.initElements(driver, ParentPage.class); } public MainPage moveToMainPage() { fullEpisodesButton.click(); return PageFactory.initElements(driver,MainPage.class); } public PlayerPage moveToPlayerPage() { Actions action = new Actions(driver); action.moveToElement(showButton).build().perform(); firstShows.click(); return PageFactory.initElements(driver,PlayerPage.class); } public LiveTvPage moveToLiveTvPage() { liveTvButton.click(); return PageFactory.initElements(driver, LiveTvPage.class); } public ProvidersPopUp openPopUp() { signInButton.click(); return PageFactory.initElements(driver, ProvidersPopUp.class); } public void signOut() { signOutButton.click(); } }
2e94c6618c057e67f0f2b80cd8d048fb5d863e45
[ "Java" ]
2
Java
Yuri100500/ScrippsTest
bad3f2cb08dadcafa261d55972e1a4dbf5d7330b
908f5434e146abb385d9541df2b7ac3e6b7b8718
refs/heads/master
<repo_name>samuelistico/labML<file_sep>/knn_src/knn.py import csv import pdb import random import math acc = 0#initializes the accuarcy global num = 10 dSet = 0#determine the dataset to be used dataBases = ["post-operative.data","cmc.data","covtype.data"] nn = [1,3,5,7,9,30,45,60]#K used kTimes = [0,0,0,0,0,0,0,0]#it will hold the number of times used the k global k #this method loads the dataset and normalizes the data for datastets 1 and 2 def loadDataset(filename, split, trainingSet=[] , testSet=[]): with open(filename, 'rt', encoding="utf8") as csvfile: lines = csv.reader(csvfile)#reads the cvs dataset = list(lines)#assign values to dataset l = len(dataset)#number of rows if(dSet > 0):#if dataset is not first numAtr = len(dataset[0])-1#number of attributes print(numAtr) matrixMax = []#sets the max of the dataset columns for x in range(len(dataset)):#this for determines the max and puts it in the matrixMax array for y in range(numAtr): if(len(matrixMax) <= y): matrixMax.append(int(dataset[x][y])) else: if(matrixMax[y] < int(dataset[x][y])): matrixMax[y] = int(dataset[x][y]) for x in range(len(dataset)):#this for normalizes the entire dataset for y in range(numAtr): dataset[x][y] = repr(float(int(dataset[x][y])/matrixMax[y])) #print(repr(dataset[x][y])) max = int(l*split)#we determine the number of trainingset random.shuffle(dataset)#we shuffle the dataset for x in range(len(dataset)):#we create the training and test set if x < max: trainingSet.append(dataset[x]) else: testSet.append(dataset[x]) #method to calculate the distance def euclideanDistance(instance1, instance2, length): distance = 0 for x in range(length): if(dSet == 0):#if dataset is 0 we use the rules function to obtain the distance distance += pow((rules(instance1[x],x) - rules(instance2[x],x)), 2) if(dSet > 0): distance += pow(float(instance1[x]) - float(instance2[x]), 2) return math.sqrt(distance) #method to determine the values of the dataset 1 def rules(x,op): if(op == 0 | op== 1 | op == 3): return { 'high': 1, 'mid': 0.5, 'low': 0 }.get(x, 0) if(op == 2): return { 'excellent': 1, 'good': 0.66, 'fair': 0.33, 'poor': 0 }.get(x, 0) if(op >= 4 & op < 7): return { 'stable': 1, 'mod-stable': 0.5, 'unstable': 0 }.get(x, 0) import operator #method to get the nearest neighbors def getNeighbors(trainingSet, testInstance, k): distances = [] length = len(testInstance)-1 for x in range(len(trainingSet)):#foreach trainingset we calculate the euclidean distance of the instance dist = euclideanDistance(testInstance, trainingSet[x], length) distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors #method to determine the final result def getResponse(neighbors): classVotes = {} for x in range(len(neighbors)):#foreach class of the neighbors we determine the times it was repeated response = neighbors[x][-1] if response in classVotes: classVotes[response] += 1 else: classVotes[response] = 1 sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True) return sortedVotes[0][0] #determines the accuarcy according to the prediction def getAccuracy(testSet, predictions): correct = 0 for x in range(len(testSet)): if testSet[x][-1] is predictions[x]: correct += 1 return (correct/float(len(testSet))) * 100.0 def main(k): # prepare data trainingSet=[] testSet=[] split = 0.7#percentage of training set loadDataset(dataBases[dSet], split, trainingSet, testSet) print ('Train set: ' + repr(len(trainingSet))) print ('Test set: ' + repr(len(testSet))) print ("k = "+repr(k)) # generate predictions predictions=[] for x in range(len(testSet)): neighbors = getNeighbors(trainingSet, testSet[x], k) result = getResponse(neighbors) predictions.append(result) print(repr(x)+'. Predicted ' + repr(result) + ', Result ' + repr(testSet[x][-1])) accuracy = getAccuracy(testSet, predictions) print('Accuracy: ' + repr(accuracy) + '%') print ('Training set: ' + repr(len(trainingSet))) print ('Test set: ' + repr(len(testSet))) print ("K = "+repr(k)) return accuracy pdb.set_trace() AvgAcc = 0.0 for num in range(100):#we repeat this process n number of times acc = 0 bestAcc = 0 bestk = 0 for x in range(len(nn)):#we use this for to obtain the best K value of an instance # k = int(math.sqrt(len(trainingSet))/2) k = nn[x] accTemp=main(k) acc+= accTemp if(accTemp > bestAcc): bestAcc = accTemp bestk = k AvgAcc+=acc/len(nn) for ki in range(len(nn)): if(nn[ki] == bestk): kTimes[ki]+= 1 print('Accuracy Avg: ' + repr(acc/len(nn)) + '%') print('Best Accuarcy with k='+repr(bestk)+': ' + repr(bestAcc) + '%') print("AVG Accuarcy after 100:" +repr(AvgAcc/100)) allBestK = 0 allBestKi = 0 for ki in range(len(nn)):# we use this for to print the overall K value if(kTimes[ki] > allBestK): allBestK = kTimes[ki] allBestKi = nn[ki] print("Best K:" +repr(allBestKi)+" with "+repr(allBestK)) <file_sep>/knn_src/README.md -To run knn you need python 3.7 or greater -This example uses the datasets: post-operative, cmc and covtype -to change the dataset change the global variable dSet to 0, 1 or 2 accordingly -We also use the K values of 1,3,5,7,9,30,45 and 60. You can modify these values in nn array -The percentage of the training set is determined by a variable called split A basic result will be like this: Train set: 406708 Test set: 174304 k = 45 0. Predicted '2', Result '1' 1. Predicted '1', Result '1' 2. Predicted '2', Result '2' 3. Predicted '3', Result '3' 4. Predicted '2', Result '2' 5. Predicted '2', Result '2' 6. Predicted '1', Result '2' 7. Predicted '1', Result '1' 8. Predicted '1', Result '2' Accuracy: 47.28506787330316% Followed by the Avgerage of the number of times repeated. This number is determined in a for loop below the code <file_sep>/decision_tree_src/dTree.py import math from collections import Counter import dTreeUtils as utils #function to get entropy def getEntropy(d, classes): l = len(d) #get all the values for the class and count them s = utils.column(d, len(d[0]) - 1) counts = Counter(s) entropy = 0.0 #for each key in classes #calculate the -prob*log(prob) for key in counts.keys(): pos = counts[key] / l log = -0.0 if pos == 0 else math.log(pos,2) entropy -= pos*log #return entropy return entropy #method to get all the info gains def getInformationGain(data, classes): #get general entropy tE = getEntropy(data, classes) iGain = [] #for each attribute get the attr entropy for i in range(len(data[0][:-1])): attribute_list = utils.column(data,i) l = len(attribute_list) attribute_set = set(attribute_list) attibute_entropy = 0 #get the sum of attribute entropy for el in attribute_set: #get probability of attribute p_ai = attribute_list.count(el) / l #get data where its present d = [[r[i],r[-1]] for r in data if r[i] == el] #caluculate its entropy h_ai = getEntropy(d, classes) #add to sum attibute_entropy += (p_ai * h_ai) #get info gain for each attribute info_gain = tE - attibute_entropy iGain.append(info_gain) #return whole list return iGain #bottoms up way of making a tree using a dictionary in python def makeTree(data, headers, classes): #get info gains gains = getInformationGain(data, classes) #return if there are no gains if gains == []: return data[0][0] #get the index of the best attribute best = gains.index(max(gains)) #if the best is 0 return a leaf if gains[best] == 0: return data[0][-1] #get a set of all values in the best attribute s = set(utils.column(data,best)) #get the head for curr tree #this is the attribute that will serve as a node head = headers.pop(best) #make a tree and append the head node tree = {} tree[head] = {} #for each attribute in current best column #make a subtree for el in s: #copy headers h = headers.copy() #remove the current best value from the data and only send #specific data for node d = [[r for i, r in enumerate(row) if i != best] for row in data if row[best] == el] #append a new tree to our dict tree[head][el] = makeTree(d, h, classes) #return finished tree return(tree) <file_sep>/decision_tree_src/dTreeUtils.py from collections import Counter #helped function to get a column from a matrix def column(m, i): return [r[i] for r in m] #helper function to get most probable element def most_probable(d): data = Counter(d) return data.most_common(1)[0][0]<file_sep>/decision_tree_src/main.py import dTree import csv import random import statistics from collections import Counter import data_manager as dm import timeit #number of runs of our program #keep it small 1-2 for data_index2 runs = 5 #0-small 1-medium 2-large data_index = 1 #training testing ratio split = 0.66 #Methos to predict a class for a particular entry def predict(tree, entry): #get classes and headers and make copy of tree classes = dm.getClasses() headers = dm.getHeaders() res = tree.copy() #run until we find a solutiomn while True: #get each keys in current level for x in res.keys(): #get header i = headers.index(x) #get values val = entry[i] #if the value is a key then get the response #this can be a leaf or another tree if val in res[x].keys(): res = res[x][val] else: #there is not a specific path #return guess return dm.getGuess #if the result is a class then return answer if res in classes: return res return res #method to test our tree def test(tree, test_data): count = 0 l = len(test_data) #for each example get a prediction #and verify its the right one for ex in test_data: ans = predict(tree, ex) expected = ex[-1] if ans == expected: count += 1 #return avg return count/l def main(): start = timeit.default_timer() #result list results = [] #for the specified number of runs #prep the data and make a tree #test the tree for i in range(runs): dm.prepData(data_index, split) header_values = dm.getHeaders() classes = dm.getClasses() train_data = dm.getTrainData() tree = dTree.makeTree(train_data, header_values, classes) test_data = dm.getTestData() results.append(test(tree, test_data)) #print final results ds = ['SMALL', 'MEDIUM', 'LARGE', 'test'] print("\n") print("FOR " + ds[data_index] + " DATASET") print("RUNS: " + str(runs)) print("AVG ACCURACY: " + str(statistics.mean(results))) if(len(results) >= 2): print("STDEV: " + str(statistics.stdev(results))) end = timeit.default_timer() print("TIME: " + str(end-start)) print("\n") if __name__ == "__main__": main() <file_sep>/decision_tree_src/README.md # LABML ## DECISION TREE Current working version is in decision_tree_src, to run it you just need python > 3 and run python main.py this will train a new tree using the data in data.csv and then validate and print the accuracy using training_data.py it works by getting the attribute with the best info gain using the entropy formula and then recursively calculating sub trees for each case of that best attribute. The tree is therefore built bottom up as a python dictionary (key,value data structure) For the predictions we travers these dictionary using the proposed best path until we hit a leaf node the data sets have to be used as they are saved in the folder * main.py contains driver and validation code * dTree.py contains the creation of the tree * data_manager.py contains code to manage, clean and provide data * dTreeUtils.py contains extra functions used Example of generated tree in python ```javascript { 'BP-STBL': { 'mod-stable': { 'L-BP': { 'mid': { 'L-SURF': { 'mid': 'S', 'high': 'A' } }, 'high': 'A', 'low': 'A' } }, 'unstable': { 'L-O2': { 'good': { 'SURF-STBL': { 'unstable': { 'L-CORE': { 'mid': 'S', 'low': 'A' } }, 'stable': 'I' } }, 'excellent': 'A' } }, 'stable': { 'COMFORT': { '10': { 'L-SURF': { 'mid': { 'L-CORE': { 'mid': { 'SURF-STBL': { 'unstable': 'A', 'stable': 'A' } }, 'low': 'S' } }, 'high': 'A', 'low': 'A' } }, '15': 'S', '07': 'S' } } } } ``` <file_sep>/decision_tree_src/data_manager.py import csv import random import dTreeUtils as utils data_sets = ['data_low.csv','data_mid.csv','data_high.csv','data_test.csv'] clean_data_set = "clean_data.csv" headers = [] all_data = [] #where to split data lim = 0 guess = '' classes = [] def getGuess(): return guess def getClasses(): return classes def getHeaders(): return headers.copy() #return training data def getTrainData(): global guess global classes data = all_data[:lim] pos_class = utils.column(data, len(data[0]) - 1) #get classes classes = list(set(pos_class)) #and most probable class guess = utils.most_probable(pos_class) return data #get test data def getTestData(): data = all_data[lim:] return data def calcData(split): global headers global all_data global lim #read data thats been shuffled with open(clean_data_set, 'r') as f: reader = csv.reader(f) all_data = list(reader) #pop the header headers = all_data.pop(0) #get the lim for the split of data lim = int(len(all_data) * split) #pre work of data def prepData(data_index, split): data_set = data_sets[data_index] lines = open(data_set).readlines() headers = lines.pop(0) #change data for large data set into categorical values if data_index == 2: for i, line in enumerate(lines): temp = line.split(',') temp[0] = 'below mean' if int(temp[0]) <= 2959.36 - 279.98 else 'above mean' if int(temp[0]) >= 2959.36 + 279.98 else 'mean' temp[1] = 'below mean' if int(temp[1]) <= 155.65 - 111.9 else 'above mean' if int(temp[1]) >= 155.65 + 111.9 else 'mean' temp[2] = 'below mean' if int(temp[2]) <= 14.10 - 7.49 else 'above mean' if int(temp[2]) >= 14.10 + 7.49 else 'mean' temp[3] = 'below mean' if int(temp[3]) <= 269.43 - 212.55 else 'above mean' if int(temp[3]) >= 269.43 + 212.55 else 'mean' temp[4] = 'below mean' if int(temp[4]) <= 46.42 - 58.30 else 'above mean' if int(temp[4]) >= 46.42 + 58.30 else 'mean' temp[5] = 'below mean' if int(temp[5]) <= 2350.15 - 1559.25 else 'above mean' if int(temp[5]) >= 2350.15 + 1559.25 else 'mean' temp[6] = 'below mean' if int(temp[6]) <= 212.15 - 26.77 else 'above mean' if int(temp[6]) >= 212.15 + 26.77 else 'mean' temp[7] = 'below mean' if int(temp[7]) <= 223.32 - 19.77 else 'above mean' if int(temp[7]) >= 223.32 + 19.77 else 'mean' temp[8] = 'below mean' if int(temp[8]) <= 142.53 - 38.27 else 'above mean' if int(temp[8]) >= 142.53 + 38.27 else 'mean' temp[9] = 'below mean' if int(temp[9]) <= 1980.29 - 1324.19 else 'above mean' if int(temp[9]) >= 1980.29 + 1324.19 else 'mean' lines[i] = ','.join(temp) #change data for medium data set into categorical values if data_index == 1: for i, line in enumerate(lines): temp = line.split(',') temp[0] = 'below mean' if int(temp[0]) <= 32.53 - 8.22 else 'above mean' if int(temp[0]) >= 32.53 + 8.22 else 'mean' temp[3] = 'below mean' if int(temp[3]) <= 3.26 - 2.35 else 'above mean' if int(temp[3]) >= 3.26 + 2.35 else 'mean' lines[i] = ','.join(temp) #shuffle the lines random.shuffle(lines) lines.insert(0,headers) #write them onto new file open(clean_data_set, 'w').writelines(lines) calcData(split)
152acb81c6483512f283428951fb6d7593247e9b
[ "Markdown", "Python" ]
7
Python
samuelistico/labML
a33d4a45bed1f278c9d3ce518266aaa36ee27303
171b82ca108afbcc0b22a4262ae176abf0d2e15b
refs/heads/master
<repo_name>tieleman/salad<file_sep>/lib/tasks/salad.rake # # LICENSE # # The MIT License # # Copyright (c) 2009 Nederlandse Publieke Omroep # Written by: # <NAME> (@bartzon) # <NAME> (@tieleman) # # 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. # # require 'cucumber/cli/main' namespace :salad do desc "Run cucumber on multiple instances" task :features => :environment do def setup_database(conn, count) conn.merge! :database => "#{conn[:database]}_#{count}" connect_or_create_database(conn) Rake::Task["db:migrate"].invoke end # Copied from databases.rake def connect_or_create_database(conn) begin # Connect using the given connection ActiveRecord::Base.establish_connection(conn) ActiveRecord::Base.connection # This is needed to trigger an error if DB does not exist rescue # or create the database specified in the connection charset = ENV['CHARSET'] || conn[:charset] || 'utf8' collation = ENV['COLLATION'] || conn[:collation] || 'utf8_general_ci' ActiveRecord::Base.establish_connection(conn.merge(:database => nil)) ActiveRecord::Base.connection.create_database(conn[:database], :charset => charset, :collation => collation) ActiveRecord::Base.establish_connection(conn) end end begin raise "RAILS_ENV is not set to test" unless Rails.env == 'test' features_dir = "features" # Set this to your features dir features = Dir[features_dir + '/**/*.feature'].sort_by { rand } feature_sets = [] num_of_processes = ENV["SALAD_INSTANCES"] ? ENV["SALAD_INSTANCES"].to_i : 4 num_of_processes.times { feature_sets << [] } features.each_with_index { |line, index| feature_sets[index % num_of_processes] << line } conn = ActiveRecord::Base.remove_connection pids = [] num_of_processes.times do |count| pids << Process.fork do setup_database(conn, count) Cucumber::Cli::Main.execute(["-f", "progress", "-r", features_dir] + feature_sets[count]) end end # Handle interrupt by user Signal.trap 'INT' do STDERR.puts("User interrupted, exiting...") pids.each { |pid| Process.kill "KILL", pid } exit 1 end pids.each { Process.wait } rescue Exception => e STDERR.puts("#{e.message} (#{e.class})") STDERR.puts(e.backtrace.join("\n")) Kernel.exit 1 end end end<file_sep>/README.markdown Run your Cucumber on multiple CPUs. IMPORTANT! ========== Salad is no longer actively maintained, but the source is still here for reference. Setup ===== Simply copy the rake task to `lib/tasks` in your Rails project. Usage ----- RAILS_ENV=test rake salad:features At the moment you explicitly need to set `RAILS_ENV` to `test`. The first time you run it, it will create and migrate the necessary database tables, so make sure your user for the `test` environment has privileges to create additional databases. Additional databases for the extra Cucumber processes are created by appending `_#{i}` to the test database as defined in your `config.yml`. This means it will _not_ interfere with your regular test database. You can run this task and your specs at the same time. `Ctrl-c` aborts all running processes. Configuration ------------- You can configure the arguments passed to Cucumber by editing the rake task. The number of Cucumber processes is determined by the `SALAD_INSTANCES` environment variable which, if not explicitly set, defaults to 4. It is assumed your features live under `RAILS_ROOT/features`, if this is not the case you can change the `features_dir` variable in the script. When in doubt, read the script. ;-) Known problems -------------- * Sometimes tests will fail, for no apparent reason at all. :( * The first time you run it, it will create a bunch of databases, migrate them and then fail all features spectacularly... Simply quit it after migration is complete and try again. Authors ------- Written by <NAME> ([@tieleman](http://twitter.com/tieleman)) and <NAME> ([@bartzon](http://twitter.com/bartzon)), to scratch their own itch. Patches much appreciated. See also -------- Something you might also like (but wasn't around when we wrote this): [Parallel specs](http://github.com/grosser/parallel_specs). Takes a slightly different approach.
82adbb19f8fa6b4980723b23da99edbbee9b7399
[ "Markdown", "Ruby" ]
2
Ruby
tieleman/salad
7617ca87f152f206f43794a922b205f830d7db67
31d7161539259b424766fccce2507480edbb490d
refs/heads/master
<file_sep>//---------------------------------------------------- // CMySQLUserManager // 自分のUserテーブルの管理クラス // // @date 2013/11/14 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MYSQL_USER_MANAGER_H_ #define _C_MYSQL_USER_MANAGER_H_ #include "../MySQLSource/CMySQLManager.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" #include <string> #pragma warning(disable : 4996) // 使うテーブルの名前 #define USER_TABLE "User" class CMySQLUserManager { private: std::string m_userID; // UserID std::string m_id; // Userが設定したID std::string m_pass; // Userが設定したパスワード std::string m_userName; // Userの名前 public: // UserIDの取得 std::string* GetIDUser ( void ) { return &m_userID; } // UserNameの取得 std::string* GetNameUser ( void ) { return &m_userName; } public: CMySQLUserManager(); virtual ~CMySQLUserManager(); public: //---------------------------------------------------- // @name LoginChk // @content ログイン // @param loginID ログインID // @param loginPass <PASSWORD> // @return bool ログイン成功か失敗 // @date 2013/11/15 //---------------------------------------------------- bool Login ( CONST std::string* loginID, CONST std::string* loginPass ); //---------------------------------------------------- // @name SignUp // @content ユーザの新規登録 // @param userID 登録したいユーザID // @param userPass 登録したいユーザパスワード // @return bool 登録の成功か失敗 // @date 2013/11/15 //---------------------------------------------------- bool SignUp ( CONST std::string* userID, CONST std::string* userPass ); }; #endif _C_MYSQL_USER_MANAGER_H_<file_sep> //---------------------------------------------------- // CSceneGame Header // ゲームシーン // // @auter T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_GAME_H_ #define _C_SCENE_GAME_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/CObjectBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Light.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" // Manager #include "../../ManagerSource/GameScene/CGameStageManager.h" #include "../../ManagerSource/GameScene/CStageBlockManager.h" #include "../../ManagerSource/PauseScene/CPauseManager.h" #include "../../ManagerSource/GameScene/CTimeManager.h" #include "../../ManagerSource/GameScene/CScoreManager.h" #include "../../ManagerSource/GameScene/CDiceInfoManager.h" #include "../../ManagerSource/GameScene/CDiceObjManager.h" #include "../../PlayerSource/CPlayerManager.h" #include "../../UserSource/CUserManager.h" #include "../DebugScene/CDebugMode.h" #include "../../GameMathSource/CDiceRandSystem.h" #include "../../ObjectSource/GameScene/Particle/CSnowObj.h" #include "../../ObjectSource/GameScene/Particle/CSpaceParticle.h" typedef enum GAMEPLAY_STATUS { GAME_START, GAME_PLAY, GAME_PAUSE, PAUSE_FADE, TIME_UP, TIME_UP_FADE, DEBUG_MODE }eGamePlayStatus; class CSceneGame : public CSceneBase { private: CDirectCamera* m_pDirectCamera; CDirectLight* m_pDirectLight; C2DSpriteAlphaBlend* m_pBack; // 背景ポリゴン C2DSpriteRHW* m_pTimeUP; LPSTR m_pResTimeUpFilePath; C2DSpriteRHW* m_pPushEnter; LPSTR m_pResPushEnterFilePath; private: CGameStageManager* m_pGameStageManager; CPauseManager* m_pPauseManager; CTimeManager* m_pTimeManager; CScoreManager* m_pScoreManager; CDiceInfoManager* m_pDiceInfoManager; private: CSnowObj* m_pSnowObj; CSpaceParticle* m_pSpaceParticle; // ゲームプレイ中のステータス eGamePlayStatus m_eGamePlayStatus; public: CSceneGame ( CSceneChange* change ); CSceneGame ( void ); ~CSceneGame ( void ); public: void Initialize ( void ) override; // 初期化処理 void Finalize ( void ) override; // 終了処理 void Run ( void ) override; // 更新処理 void Draw ( void ) override; // 描画処理 bool Load ( void ) override; // ロード処理 public: void Pause ( void ); // ポーズ中処理 void ChangePause ( void ); // ポーズ切り替え void PauseFade ( void ); // ポーズからのフェード void TimeUp ( void ); // タイムアップ void TimeUpFade ( void ); // タイムアップのフェード }; #endif _C_SCENE_GAME_H_<file_sep>//---------------------------------------------------- // CSceneManager Header // Sceneを管理する // // @date 2013/6/15 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_MANAGER_H_ #define _C_SCENE_MANAGER_H_ #include "CSceneChange.hpp" #include "CSceneBase.hpp" #include "../../../SceneSource/GameScene/CSceneGame.h" #include "../../../SceneSource/ResultScene/CSceneResult.h" #include "../../../SceneSource/GameTitleScene/CSceneTitle.h" #include "../../../SceneSource/ModeSelectScene/CSceneModeSelect.h" #include "../../../SceneSource/ScoreScene/CSceneScore.h" #include "../../../SceneSource/ModelViewScene/CSceneModelView.h" #include "../../../SceneSource/DebugScene/CSceneDebug.h" #include "../SystemHeader/CPthread.hpp" class CSceneManager : public CSceneChange { private: CSceneBase* m_pScene; // シーン管理変数 eSceneState m_nowScene; // 現在のシーン管理変数 eSceneState m_nextScene; // 次のシーン管理変数 bool m_isLoad; // ロードフラグ // CPthread* m_pPthread; // ロード用スレッド private: //---------------------------------------------------- // Sceneをインスタンス化する //---------------------------------------------------- void Update (void); public: CSceneManager ( eSceneState state ); CSceneManager ( void ); ~CSceneManager ( void ); public: void Initialize ( void ); // 初期化 void Finalize ( void ); // 終了処理 void Run ( void ); // 更新 void Draw ( void ); // 描画 static void* ThreadLoad ( void* func ); // スレッドのためのロード関数 bool Load ( void ); // ロード void DrawLoading ( void ); // nowloading描画 public: //---------------------------------------------------- // シーン変更関数 // @nextScene //---------------------------------------------------- void ChangeScene( eSceneState NextScene ) override; }; #endif _C_SCENE_MANAGER_H_<file_sep>//---------------------------------------------------- // CSceneDebug // Debug画面シーン // // @date 2013/12/6 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_DEBUG_H_ #define _C_SCENE_DEBUG_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #define FONT_NUM (6) #define SELECT_SCENE_COLOR D3DXCOLOR( 200,0,255,255 ) #define DEFAULT_SCENE_COLOR D3DXCOLOR( 255,255,255,255 ) class CSceneDebug : public CSceneBase { private: D3DXCOLOR m_fontColor[ FONT_NUM ]; D3DXVECTOR2 m_fontPos[ FONT_NUM ]; int m_fontIndex; public: CSceneDebug ( void ){} CSceneDebug ( CSceneChange* change ); virtual ~CSceneDebug ( void ); public: void Initialize ( void ) override; void Finalize ( void ) override; void Run ( void ) override; void Draw ( void ) override; bool Load ( void ) override; }; #endif _C_SCENE_DEBUG_H_<file_sep> #include "CTitleBackManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CTitleBackManager::CTitleBackManager( void ) { // αブレンド m_pAlphaBlend = new C2DSpriteAlphaBlend; // タイトル背景 m_pTitleBack = new C2DSpriteAlphaBlend; m_pResTitleBackFilePath = TITLE_BACK_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTitleBackFilePath ); // タイトルロゴ m_pTitleLogo = new C2DSpriteAlphaBlend; m_pResTitleLogoFilePath = TITLELOG_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTitleLogoFilePath ); // Re:make m_pTitleRemake = new C2DSpriteAlphaBlend; m_pResTitleRemakeFilePath = TITLE_REMAKE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTitleRemakeFilePath ); // PUSH START PLAY m_pPushStartPlay = new C2DSpriteAlphaBlend( eFadeState::FADE_OUT ); m_pResPushStartPlayFilePath = PUSHSTART_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPushStartPlayFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CTitleBackManager::~CTitleBackManager( void ) { SAFE_DELETE( m_pAlphaBlend ); // αブレンド SAFE_DELETE( m_pTitleBack ); // タイトル背景 SAFE_DELETE( m_pPushStartPlay ); // PUSH START PLAY SAFE_DELETE( m_pTitleLogo ); // タイトルロゴ SAFE_DELETE( m_pTitleRemake ); // Remake } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CTitleBackManager::Init( void ) { m_isFade = false; m_pTitleBack->SetVertexPos( 400.0f, 320.0f, 800.0f, 640.0f ); m_pAlphaBlend->SetVertexPos( 400.0f,320.0f,800.0f,640.0f ); m_pAlphaBlend->SetDiffuse( 255,255,255,0 ); m_pPushStartPlay->SetVertexPos( 400.0f, 480.0f, 320.0f, 50.0f ); m_pPushStartPlay->SetDiffuse( 255,255,255,255 ); m_pTitleLogo->SetVertexPos( 400.0f,140.0f,400.0f,200.0f ); m_pTitleRemake->SetVertexPos( 400.0f, 250.0f, 220.0f, 60.0f ); } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CTitleBackManager::Run( void ) { // PUSH START のフェードインとフェードアウト m_pPushStartPlay->Fade( 255,80, 5 ); } //---------------------------------------------------- // フェードアウトエフェクト //---------------------------------------------------- bool CTitleBackManager::Fade( void ) { if ( m_pAlphaBlend->FadeOut( 5 ) ) { return true; } return false; } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CTitleBackManager::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTitleBackFilePath )->Get(), m_pTitleBack->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTitleLogoFilePath )->Get(),m_pTitleLogo->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTitleRemakeFilePath )->Get(), m_pTitleRemake->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResPushStartPlayFilePath )->Get(), m_pPushStartPlay->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( m_pAlphaBlend->GetVertex() ); // エフェクト描画 }<file_sep>//---------------------------------------------------- // CXAudio2 // XAudio2のクラス // // @date 2013/6/1 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_XAUDIO2_H_ #define _C_XAUDIO2_H_ #include <xaudio2.h> #include <mmsystem.h> #pragma comment(lib,"winmm.lib") class CXAudio2 { enum{ MAX_WAV = 32, // WAVサウンド最大数 }; private: IXAudio2 *m_pXAudio2; IXAudio2MasteringVoice *m_pMasteringVoice; IXAudio2SourceVoice *m_pSourceVoice[ MAX_WAV ]; BYTE *m_pWavBuffer[ MAX_WAV ]; // 波形データ(フォーマット等を含まない、純粋に波形データのみ) DWORD m_dwWavSize[ MAX_WAV ]; // 波形データのサイズ int m_iSoundIndex[ MAX_WAV ]; // 今回読み込む音の番号 float m_volBGM; float m_volSE; int m_stepBGM; int m_stepSE; int m_FadeFlag[ MAX_WAV ]; int m_reserveNumber; public: CXAudio2 ( void ); virtual ~CXAudio2 ( void ); //---------------------------------------------------- // @name Init // @content XAudio2の初期化 // @param none // @return HRESULT 成功か失敗 //---------------------------------------------------- HRESULT Init ( void ); //---------------------------------------------------- // @name LoadWav // @content Wavデータの読み込み // @param index 読み込む場所 // @pram fileName ファイルパス // @return boolean 成功か失敗 //---------------------------------------------------- boolean LoadWav ( CONST UINT index, const LPSTR fileName ); //---------------------------------------------------- // @name Release // @content Wavデータの解放 // @param index 解放場所 // @return boolean 成功か失敗 //---------------------------------------------------- boolean Release ( CONST UINT index ); //---------------------------------------------------- // @name Run // @content サウンドの再生 // @param index 再生するサウンド番号 // @param vol 再生する音量 // @param isLoop ループ再生するかのフラグ // @return boolean 成功か失敗 //---------------------------------------------------- boolean Run ( CONST UINT index, CONST FLOAT vol, CONST bool isLoop ); //---------------------------------------------------- // @name Stop // @content サウンドの停止 // @param index 停止するサウンド番号 // @return boolean 成功か失敗 //---------------------------------------------------- boolean Stop ( CONST UINT index ); //---------------------------------------------------- // @name Pause // @content サウンドの一時停止 // @param index 一時停止するサウンド番号 // @return boolean 成功か失敗 //---------------------------------------------------- boolean Pause ( CONST UINT index ); //---------------------------------------------------- // @name ChangeVolume // @content サウンドの音量変更 // @param index 音量変更するサウンド番号 // @return volume セットする音量の値 // @date boolean 成功か失敗 //---------------------------------------------------- boolean ChengeVolume ( CONST UINT index, CONST FLOAT vol ); //---------------------------------------------------- // @name StopwithFade // @content Fadeをかけて停止するサウンドの番号を指示する // @param index フェードをかけkて停止させるサウンド番号 // @param num フラグの数字 // @return boolean 成功か失敗 //---------------------------------------------------- boolean StopwithFade ( CONST UINT index, CONST int num ); //---------------------------------------------------- // @name FadeStopManager // @content サウンドにフェードをかけて停止する。毎ループ呼び出す。 // @param volume 音量 // @return boolean 成功か失敗 //---------------------------------------------------- boolean FadeStopManeger ( CONST FLOAT volume ); public: float GetVolumeBGM ( void ); // BGMの取得 float GetVolumeSE ( void ); // SEの取得 float SetVolumeBGM ( float vol ); // BGMの音量セット float SetVolumeSE ( float vol ); // SEの音量セット int GetStepBGM ( void ); // BGMのstep(倍率)をGetする int GetStepSE ( void ); // SEのstep(倍率)をGetする int SetStepBGM ( int step ); // BGMのstep(倍率)をSetする int SetStepSE ( int step ); // SEのstep(倍率)をSetする }; #endif _C_XAUDIO2_H_<file_sep>//---------------------------------------------------- // CDirectX9Camera // DirectXのカメラを制御する // // @date 2013/6/2 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DIRECTX9_CAMERA_H_ #define _C_DIRECTX9_CAMERA_H_ #include <d3dx9.h> #include "../../KaiFrameWorkHeader/DirectX9Header/CDirectX9FrameWork.h" class CDirectCamera { private: D3DXMATRIX m_view; // ビュー行列 D3DXMATRIX m_projection; // 射影行列 D3DXMATRIX m_ortho; // 正射影行列 D3DXMATRIX m_worldMtx; // カメラのワールド行列 D3DXVECTOR3 m_vEye; // カメラの位置 D3DXVECTOR3 m_vAt; // カメラの注視点 D3DXVECTOR3 m_vUp; // カメラの向き public: D3DXMATRIX* GetView ( void ) { return &m_view; } D3DXVECTOR3* GetEye ( void ) { return &m_vEye; } D3DXVECTOR3* GetAt ( void ) { return &m_vAt; } public: CDirectCamera ( void ); ~CDirectCamera ( void ); public: //---------------------------------------------------- // @name Init // @content カメラの初期化 // @param windowSizeX 画面のXサイズ // @param windowSizeY 画面のYサイズ // @return bool 成功か失敗 // @date 2013/6/3 // @update 2013/11/18 //---------------------------------------------------- bool Init ( CONST int windowSizeX, CONST int windowSizeY ); //---------------------------------------------------- // @name Init // @content カメラの初期化(位置・注視点・方向) // @param none // @return bool 成功か失敗 // @date 2013/6/4 // @update 2013/11/18 //---------------------------------------------------- bool Init ( void ); //---------------------------------------------------- // @name Set // @content カメラをセット // @param none // @return bool 成功か失敗 // @date 2013/6/3 // @update 2013/11/18 //---------------------------------------------------- bool Set ( void ); //---------------------------------------------------- // @name SetPosition // @content カメラの位置セット // @param xPos セットしたいX座標 // @param yPos セットしたいY座標 // @param zPos セットしたいZ座標 // @return bool 成功か失敗 // @date 2013/6/4 // @update 2013/11/18 //---------------------------------------------------- bool SetPosition ( CONST float xPos, CONST float yPos, CONST float zPos ); //---------------------------------------------------- // @name SetAt // @content カメラの注視点のセット // @param xPos セットしたいX座標 // @param yPos セットしたいY座標 // @param zPos セットしたいZ座標 // @return bool 成功か失敗 // @date 2013/6/5 // @update 2013/11/18 //---------------------------------------------------- bool SetAt ( CONST float xPos, CONST float yPos, CONST float zPos ); //---------------------------------------------------- // @name SetView // @content カメラのワールド行列のセット // @param none // @return BOOL 成功か失敗 // @date 2013/6/6 // @update 2013/11/18 //---------------------------------------------------- bool SetView ( void ); //---------------------------------------------------- // @name SetPerspective // @content 描画を透視投影変換に設定 // @param none // @return none // @date 2013/6/7 //---------------------------------------------------- void SetPerspective ( void ) { LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetTransform(D3DTS_PROJECTION,&m_projection); } //---------------------------------------------------- // @name SetOrtho // @content 正射影変換にセ設定 // @param none // @return none // @date 2013/6/7 //---------------------------------------------------- void SetOrtho ( void ) { LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetTransform(D3DTS_PROJECTION, &m_ortho); } //---------------------------------------------------- // @name Tracking // @content 追従カメラ(ベクトルを考慮しない) // @param pMtx 主観したいモデルのワールド座標 // @param at モデルからの距離 // @return none // @date 2013/6/10 // @update 2013/11/18 //---------------------------------------------------- void Tracking ( CONST D3DXMATRIX* pMtx, CONST float at ); //---------------------------------------------------- // @name Tracking // @content 追従させたいモデルのベクトルを利用しての追従カメラ // @param pMtx 主観したいモデルのワールド座標 // @param pVec 主観したいモデルのベクトル // @param distance モデルからのカメラの距離 // @return none // @date 2013/6/12 // @update 2013/11/18 //---------------------------------------------------- void Tracking ( CONST D3DXMATRIX* pMtx, CONST D3DXVECTOR3* pVec, CONST float distance ); public: //---------------------------------------------------- // @name SetBillBoardMat // @content 行列をビルボード用行列に変換 // @return D3DXMATRIX* 変更した行列 // @param pBillBoardPos ビルボードの位置 // @param pBillBoardMat 変換したい行列 // @date 2013/6/20 // @update 2013/11/18 変換した行列を返す //---------------------------------------------------- D3DXMATRIX* SetBillBoardMtx ( D3DXMATRIX* pBillBoardMtx, CONST D3DXVECTOR3* pBillBoardPos ); //---------------------------------------------------- // @name SetBillBoardMat // @content 行列をビルボード用行列に変換 // @param pBillBoardMat 変換したい行列 // @param distance カメラからの距離 // @return D3DXMATRIX* 変換した行列 // @date 2013/6/21 // @update 2013/11/18 変換した行列を返す //---------------------------------------------------- D3DXMATRIX* SetBillBoardMtx ( D3DXMATRIX* pBillBoardMtx, CONST float distance ); private: //---------------------------------------------------- // @name CalcQuaternion // @content クォータニオンの計算 // @param pAxis 回転方向ベクトル // @param degree 回転角度 // @return bool 成功か失敗 // @date 2013/11/18 //---------------------------------------------------- bool CalcLocalQuaternion ( CONST D3DXVECTOR3* pAxis, CONST float degree ); public: void LocalRotationQuaterX( CONST float degree ); // ローカルクォータニオンX回転 void LocalRotationQuaterY( CONST float degree ); // ローカルクォータニオンY回転 void LocalRotationQuaterZ( CONST float degree ); // ローカルクォータニオンZ回転 //---------------------------------------------------- // @name LocalRotationQuater // @content ローカル任意軸クォータニオン回転 // @param pVec 任意の軸 // @param degree 回転角度 // @return none // @date 2013/7/30 // @update 2013/11/18 //---------------------------------------------------- void LocalRotationQuater( CONST D3DXVECTOR3* pVec, CONST float degree ); }; #endif _C_DIRECTX9_CAMERA_H_<file_sep>//---------------------------------------------------- // C2DBillBoard // ビルボードのクラス // // @date 2013/12/18 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_2D_BILLBOARD_H_ #define _C_2D_BILLBOARD_H_ #include <Windows.h> #include <d3dx9.h> #include "C2DSprite.h" // 自作色情報構造体 typedef struct TAGtCOLOR { int red; int green; int blue; int alpha; }tagTCOLOR; class C2DBillBoard : public C2DSprite { private: tagTCOLOR m_color; // 色情報 public: // コンストラクタ C2DBillBoard ( void ); // デストラクタ ~C2DBillBoard ( void ); public: //---------------------------------------------------- // @name SetVertexColor // @content 色を頂点にセット // @param none // @return none // @date 2013/12/18 //---------------------------------------------------- void SetVertexColor ( void ); //---------------------------------------------------- // @name SetColor // @content 色をまとめてセット // @param r 赤値( 0 ~ 255 ) // @param g 緑値( 0 ~ 255 ) // @param b 青値( 0 ~ 255 ) // @param a α値 ( 0 ~ 255 ) // @return none // @date 2013/12/18 //---------------------------------------------------- void SetColor ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // @name SetColor // @content 色の個別セット( 各色ごとにわかれている ) // @param color 色( 各色ごと 0 ~ 255 ) // @return none // @date 2013/12/18 //---------------------------------------------------- void SetColorRed ( CONST UINT red ) { m_color.red = red; this->SetVertexColor(); } void SetColorGreen ( CONST UINT green ) { m_color.green = green; this->SetVertexColor(); } void SetColorBlue ( CONST UINT blue ) { m_color.blue = blue; this->SetVertexColor(); } void SetColorAlfa ( CONST UINT alpfa ) { m_color.alpha; this->SetVertexColor(); } //---------------------------------------------------- // @name CalcWorldMtx // @content ワールド行列をビルボード用の行列にセットする // @param cameraView カメラのビュー行列 // @return none // @date 2013/12/18 //---------------------------------------------------- void CalcWorldMtx ( CONST D3DXMATRIX* cameraView ); }; #endif _C_2D_BILLBOARD_H_<file_sep>#ifndef _WINMAIN_H_ #define _WINMAIN_H_ #if defined(DEBUG) || defined(_DEBUG) #include<crtdbg.h> #define DEBUG_INSTANCE #endif // _DEBUG // 内部ヘッダ読み込み #include <Windows.h> // 外部ヘッダ読み込み #include "../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CWindowSystem.h" #include "../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9FrameWork.h" #include "../KaiFrameWork/KaiFrameWorkHeader/SystemHeader/CFpsControl.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/DebugHeader/CDebugConsole.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneManager.h" #include "../SceneSource/DebugScene/CDebugMode.h" #include "../MySQLSource/CMySQLManager.hpp" //---------------------------------------------------- // @name GameMain // @content ゲームのメイン関数 // @param none // @return none // @date 2013/5/10 //---------------------------------------------------- void GameMain (void); //---------------------------------------------------- // @name UninitGame // @content ゲームの終了関数 // @param none // @return none // @date 2013/5/10 //---------------------------------------------------- void UninitGame (void); #endif _WINMAIN_H_<file_sep> #include "CDiceObjManager.h" const float DICE_ROLL_SPEED = 5.0f; // サイコロの回転速度(90度変化させるため90になるように) const int START_DICE_NUM = 10; // 初期のサイコロの数 const int MIN_DICE_NUM = 10; // ステージ中の最低ダイス数(これ以上少なくなったら強制的に出現させる) const int DICE_APPER_TIME = 90; // この時間でダイスの出るタイミングを管理 const int DICE_APPER = 70; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDiceObjManager::CDiceObjManager( void ) { m_pDice = new CDiceObj[MAX_DICE_NUM]; // サイコロの最大数分先に生成 m_pResDiceFilePath = DICE_XFILEPATH; CResourceManager::GetInstance()->LoadXFile( m_pResDiceFilePath ); m_pMainDice = new TMAINDICE; // メインのサイコロの構造体をインスタンス化 m_pSplitParticle = new CSplitParticle; // パーティクル m_pDiceInfoManager = nullptr; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDiceObjManager::~CDiceObjManager( void ) { SAFE_DELETE( m_pMainDice ); SAFE_DELETE_ALLAY( m_pDice ); SAFE_DELETE( m_pSplitParticle ); } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CDiceObjManager::Draw( CONST D3DXMATRIX* view ) { // カリングモード CDirectDrawSystem::GetInstance()->SetCallMode( true ); for( int i = 0; i < MAX_DICE_NUM; ++ i ) { if( m_pDice[i].GetIsDice() == true ) { CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( m_pResDiceFilePath ),m_pDice[i].GetWorldMtx(), m_pDice[i].GetColor() ); } } // パーティクル // m_pSplitParticle->Draw( view ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CDiceObjManager::Init( void ) { // ダイスのメッシュデータ取得 TMESHDATA meshData; ::ZeroMemory( &meshData, sizeof( TMESHDATA ) ); CCollision::GetInstance()->GetMeshData( &meshData, CResourceManager::GetInstance()->GetXFile( DICE_XFILEPATH )->GetMesh() ); // 先に全てのサイコロを初期化 for( int i = 0; i < MAX_DICE_NUM; ++ i ) { m_pDice[i].Init(); m_pDice[i].SetSize( &meshData.size ); } // 当たり判定用AABBを作成 CDebugMode::m_pDiceBox[0].diceBox.CreateBox( m_pDice[0].GetSize() ); CDebugMode::m_pDiceBox[0].diceBox.InitWorldMtx(); CDebugMode::m_pDiceBox[0].diceBox.SetDiffuse( 0, 0, 0, 200 ); CDebugMode::m_pDiceBox[0].diceBox.SetAmbient( 255, 0, 0, 255 ); CDebugMode::m_pDiceBox[0].isDice = true; // メインのサイコロの設定 m_pMainDice->diceObj = &m_pDice[0]; m_pDice[0].SetIsDice( true ); // 当たり判定用AABBを作成 m_pDice[0].SetAABB(); // ブロックの場所番号取得 UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pDice[0].GetXPos(), m_pDice[0].GetZPos() ); m_pMainDice->diceObj->SetIndexNo( index ); CStageBlockManager::GetInstance()->SetIsOnDice( index, true ); m_pMainDice->rollState = eDiceRollState::DICE_ROLLSTATE_NONE; m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->SetNo( 0 ); m_pMainDice->diceObj->SetStatus( DICE_STATUS::e_statusNormal ); m_pMainDice->halfSize = D3DXVECTOR3( m_pDice[0].GetSize()->x / 2, m_pDice[0].GetSize()->y / 2, m_pDice[0].GetSize()->z / 2); // ステージにメインダイスの情報をセット CStageBlockManager::GetInstance()->SetBlockToDiceInfo( m_pMainDice->diceObj, m_pMainDice->diceObj->GetIndexNo() ); // インフォ情報にメインダイスの情報をセット m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); m_diceNum = 1; m_appearTime = 0; // ステージに初期のダイスをセット for( int i = 0; i < START_DICE_NUM; ++ i ) { this->Appear(); } } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CDiceObjManager::Uninit( void ) { } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CDiceObjManager::Run() { // デバッグ this->Debug(); // 出現管理 this->AppearManager(); // 移動回転 this->MoveToRoll(); // ダイスのアニメーション制御 this->Animation(); // パーティクル処理 m_pSplitParticle->Move(); } //---------------------------------------------------- // デバッグ //---------------------------------------------------- void CDiceObjManager::Debug( void ) { #ifdef _DEBUG // 移動 if( ( CInputKeyboard::GetInstance()->GetPressKeyState( VK_D ) || CInputKeyboard::GetInstance()->GetPressKeyState( VK_A ) || CInputKeyboard::GetInstance()->GetPressKeyState( VK_W ) || CInputKeyboard::GetInstance()->GetPressKeyState( VK_S ) ) && m_pMainDice->rollState == eDiceRollState::DICE_ROLLSTATE_NONE ) { m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->InitRoll(); this->Move(); } #endif // サイコロ出現 if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_SPACE ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_X ) ) && m_pMainDice->rollState == eDiceRollState::DICE_ROLLSTATE_NONE ) { this->Appear(); } #ifdef _DEBUG // 今自分が動かしているサイコロを変更する if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_TAB ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_Y ) ) && m_pMainDice->rollState == eDiceRollState::DICE_ROLLSTATE_NONE ) { for( int i = 0; i < MAX_DICE_NUM; ++ i ) { if( m_pDice[i].GetIsDice() == true && m_pDice[i].GetStatus() == DICE_STATUS::e_statusNormal && &m_pDice[i] != m_pMainDice->diceObj ) { m_pMainDice->diceObj = (&m_pDice[i]); // メインのダイスを変える m_pMainDice->diceObj->SetIndexNo(m_pDice[i].GetIndexNo()); m_pMainDice->halfSize = D3DXVECTOR3( m_pDice[i].GetSize()->x / 2, m_pDice[i].GetSize()->y / 2, m_pDice[i].GetSize()->z / 2 ); break; } } } #endif } //---------------------------------------------------- // 移動の遷移 //---------------------------------------------------- void CDiceObjManager::Move( void ) { // 右移動 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_D ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_RIGHT )) { this->MoveRight(); } // 左移動 else if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_A ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_LEFT )) { this->MoveLeft(); } // 前進 else if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_W ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_UP )) { this->MoveFront(); } // 後進 else if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_S ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_DOWN )) { this->MoveBack(); } } //---------------------------------------------------- // 右移動 //---------------------------------------------------- void CDiceObjManager::MoveRight( void ) { // ステージの右に達していないか if( m_pMainDice->diceObj->GetWorldMtx()->_41 < CStageBlockManager::GetInstance()->GetXSize() ) { // 右にブロックがないか判定 if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 右にブロックがある場合はメインのダイスを替える m_pMainDice->diceObj = CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice(); m_pMainDice->diceObj->SetIndexNo( m_pMainDice->diceObj->GetIndexNo() ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); return; } // 右のダイスが消え中,出現し始め中だったら前のダイスを消して移動させる else if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() + 1 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetStatus() ==DICE_STATUS::e_statusDelete || CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetStatus() ==DICE_STATUS::e_statusStartAppear ) ) { CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->SetStatus( DICE_STATUS::e_statusNone ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->SetBeforStatus( DICE_STATUS::e_statusDelete ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->SetIsDice( false ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->SetIsChain( false ); CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetChainNo() )->chainDiceNum --; if( CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetChainNo() )->chainDiceNum == 0 ) { CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + 1 )->GetDice()->GetChainNo() )->isChain = false; } } m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->InitRoll(); UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pMainDice->diceObj->GetWorldMtx()->_41, m_pMainDice->diceObj->GetWorldMtx()->_43 ); CStageBlockManager::GetInstance()->SetIsOnDice( index, false ); m_pMainDice->rollState = DICE_ROLLSTATE_RIGHT; m_pMainDice->diceObj->RollChangePip( m_pMainDice->rollState ); } } //---------------------------------------------------- // 左移動 //---------------------------------------------------- void CDiceObjManager::MoveLeft( void ) { // ステージの左に達していないかを判定 if( m_pMainDice->diceObj->GetWorldMtx()->_41 > -CStageBlockManager::GetInstance()->GetXSize() ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() - 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal) { // 左にブロックがある場合はメインのダイスを替える m_pMainDice->diceObj = CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice(); m_pMainDice->diceObj->SetIndexNo(m_pMainDice->diceObj->GetIndexNo()); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); return; } // 前のダイスが消え中,出現し始め中だったら前のダイスを消して移動させる else if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() - 1 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetStatus() ==DICE_STATUS::e_statusDelete || CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetStatus() ==DICE_STATUS::e_statusStartAppear ) ) { CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->SetStatus( DICE_STATUS::e_statusNone ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->SetBeforStatus( DICE_STATUS::e_statusDelete ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->SetIsDice( false ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->SetIsChain( false ); CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetChainNo() )->chainDiceNum --; if( CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetChainNo() )->chainDiceNum == 0 ) { CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - 1 )->GetDice()->GetChainNo() )->isChain = false; } } m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->InitRoll(); UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pMainDice->diceObj->GetWorldMtx()->_41, m_pMainDice->diceObj->GetWorldMtx()->_43 ); CStageBlockManager::GetInstance()->SetIsOnDice( index, false ); m_pMainDice->rollState = DICE_ROLLSTATE_LEFT; m_pMainDice->diceObj->RollChangePip( m_pMainDice->rollState ); } } //---------------------------------------------------- // 前移動 //---------------------------------------------------- void CDiceObjManager::MoveFront( void ) { // ステージの前に達していないか if( m_pMainDice->diceObj->GetWorldMtx()->_43 < CStageBlockManager::GetInstance()->GetXSize() ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() ) == true && CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 前にブロックがある場合はメインのダイスを替える m_pMainDice->diceObj = CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice(); m_pMainDice->diceObj->SetIndexNo(m_pMainDice->diceObj->GetIndexNo()); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); return; } // 前のダイスが消え中,出現し始め中だったら前のダイスを消して移動させる else if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() ==DICE_STATUS::e_statusDelete || CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() ==DICE_STATUS::e_statusStartAppear ) ) { CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetStatus( DICE_STATUS::e_statusNone ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetBeforStatus( DICE_STATUS::e_statusDelete ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetIsDice( false ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetIsChain( false ); if( CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetChainNo() )->chainDiceNum == 0 ) { CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() - CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetChainNo() )->isChain = false; } } // 回転移動 m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->InitRoll(); UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pMainDice->diceObj->GetWorldMtx()->_41, m_pMainDice->diceObj->GetWorldMtx()->_43 ); CStageBlockManager::GetInstance()->SetIsOnDice( index, false ); m_pMainDice->rollState = DICE_ROLLSTATE_FRONT; m_pMainDice->diceObj->RollChangePip( m_pMainDice->rollState ); } } //---------------------------------------------------- // 後移動 //---------------------------------------------------- void CDiceObjManager::MoveBack( void ) { // ステージの後ろに達していないかを判定 if( m_pMainDice->diceObj->GetWorldMtx()->_43 > -CStageBlockManager::GetInstance()->GetZSize() ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() ) == true && CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 後ろにブロックがある場合はメインのダイスを替える m_pMainDice->diceObj = CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice(); m_pMainDice->diceObj->SetIndexNo(m_pMainDice->diceObj->GetIndexNo()); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); return; } // 後ろのダイスが消え中,出現し始め中だったら前のダイスを消して移動させる else if( CStageBlockManager::GetInstance()->GetIsOnDice( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() ==DICE_STATUS::e_statusDelete || CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetStatus() ==DICE_STATUS::e_statusStartAppear ) ) { CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetStatus( DICE_STATUS::e_statusNone ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetBeforStatus( DICE_STATUS::e_statusDelete ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetIsDice( false ); CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->SetIsChain( false ); CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetChainNo() )->chainDiceNum --; if( CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetChainNo() )->chainDiceNum == 0 ) { CChainManager::GetInstance()->GetChain( CStageBlockManager::GetInstance()->GetStageBlock( m_pMainDice->diceObj->GetIndexNo() + CStageBlockManager::GetInstance()->GetZNum() )->GetDice()->GetChainNo() )->isChain = false; } } m_pMainDice->degree = 0.0f; m_pMainDice->diceObj->InitRoll(); UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pMainDice->diceObj->GetWorldMtx()->_41, m_pMainDice->diceObj->GetWorldMtx()->_43 ); CStageBlockManager::GetInstance()->SetIsOnDice( index, false ); m_pMainDice->rollState = DICE_ROLLSTATE_BACK; m_pMainDice->diceObj->RollChangePip( m_pMainDice->rollState ); } } //---------------------------------------------------- // 移動+回転 //---------------------------------------------------- void CDiceObjManager::MoveToRoll( void ) { switch( m_pMainDice->rollState ) { case DICE_ROLLSTATE_RIGHT: m_pMainDice->degree += DICE_ROLL_SPEED; m_pMainDice->diceObj->MoveX( -m_pMainDice->halfSize.x, m_pMainDice->halfSize.y, 0.0f, -1.0f,m_pMainDice->degree ); m_pMainDice->diceObj->SetAABB(); // 当たり判定用AABBの位置を更新 CDebugMode::m_pDiceBox[m_pMainDice->diceObj->GetNo()].diceBox.SetWorldPos( m_pMainDice->diceObj->GetWorldMtx () ); break; case DICE_ROLLSTATE_LEFT: m_pMainDice->degree += DICE_ROLL_SPEED; m_pMainDice->diceObj->MoveX( m_pMainDice->halfSize.x, m_pMainDice->halfSize.y, 0.0f, 1.0f, m_pMainDice->degree ); m_pMainDice->diceObj->SetAABB(); // 当たり判定用AABBの位置を更新 CDebugMode::m_pDiceBox[m_pMainDice->diceObj->GetNo()].diceBox.SetWorldPos( m_pMainDice->diceObj->GetWorldMtx () ); break; case DICE_ROLLSTATE_FRONT: m_pMainDice->degree += DICE_ROLL_SPEED; m_pMainDice->diceObj->MoveZ( 0.0f, m_pMainDice->halfSize.x, -m_pMainDice->halfSize.y , 1.0f, m_pMainDice->degree ); m_pMainDice->diceObj->SetAABB(); // 当たり判定用AABBの位置を更新 CDebugMode::m_pDiceBox[m_pMainDice->diceObj->GetNo()].diceBox.SetWorldPos( m_pMainDice->diceObj->GetWorldMtx () ); break; case DICE_ROLLSTATE_BACK: m_pMainDice->degree += DICE_ROLL_SPEED; m_pMainDice->diceObj->MoveZ( 0.0f, m_pMainDice->halfSize.x, m_pMainDice->halfSize.y , -1.0f, m_pMainDice->degree ); m_pMainDice->diceObj->SetAABB(); // 当たり判定用AABBの位置を更新 CDebugMode::m_pDiceBox[m_pMainDice->diceObj->GetNo()].diceBox.SetWorldPos( m_pMainDice->diceObj->GetWorldMtx () ); break; case DICE_ROLLSTATE_NONE: break; } // 角度が90度( 1マス分移動したら ) if( m_pMainDice->degree == 90 && m_pMainDice->rollState != DICE_ROLLSTATE_NONE ) { m_pMainDice->rollState = DICE_ROLLSTATE_NONE; UINT index = CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pMainDice->diceObj->GetWorldMtx()->_41, m_pMainDice->diceObj->GetWorldMtx()->_43 ); m_pMainDice->diceObj->SetIndexNo( index ); CStageBlockManager::GetInstance()->SetBlockToDiceInfo( m_pMainDice->diceObj, m_pMainDice->diceObj->GetIndexNo() ); // ダイスのINFO情報を変更 m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); // エミッター m_pSplitParticle->Emitter( m_pMainDice->diceObj->GetXPos(), m_pMainDice->diceObj->GetYPos() - 2.0f, m_pMainDice->diceObj->GetZPos() ); // 判定 CChainManager::GetInstance()->Chain( m_pMainDice->diceObj->GetIndexNo() ); } } //---------------------------------------------------- // ダイス出現管理 //---------------------------------------------------- void CDiceObjManager::AppearManager( void ) { // 管理用変数に時間を足す m_appearTime ++; // ステージからどれだけ消してもとりあず最低数分は出現させる if( m_diceNum <= MIN_DICE_NUM ) { this->Appear(); } if( m_appearTime >= DICE_APPER_TIME ) { _int64 ran = CXorShift::GetInstance()->GetRandom( 0 , 100 ); if( ran >= DICE_APPER ) { this->Appear(); m_appearTime = 0; } } } //---------------------------------------------------- // ダイスの出現 //---------------------------------------------------- bool CDiceObjManager::Appear( void ) { // 出現していないダイスを判定 UINT notAppearNo = 0; for( int i = 0; i < MAX_DICE_NUM; ++ i ) { if ( m_pDice[i].GetIsDice() == false ) { notAppearNo = i; break; } // 全部埋まっている場合は生成できない(普通はゲームオーバだが,とりあえずエラーを防ぐために実装) if( i == MAX_DICE_NUM ) { return false; } } // ランダムにブロックの添え字を取得 UINT blockIndex = CStageBlockManager::GetInstance()->GetBlockIndexRnd(); // ブロックがまだ生成されていないかどうか if( CStageBlockManager::GetInstance()->GetIsOnDice( blockIndex ) == false ) { m_diceNum ++; // ダイスの数追加 // 現在のオブジェクトが持っている行列を初期化 m_pDice[notAppearNo].InitWorldMtx(); // 面判定配列を保存 m_pDice[notAppearNo].InitPip(); // ランダムで上面の目と横面の回転数を決める int upperFace = CDiceRandSystem::GetInstance()->GetUpperFace(); int aroundNum = CDiceRandSystem::GetInstance()->GetAroundFace(); // 上面を元にサイコロの初期をセット m_pDice[ notAppearNo ].SetPip( upperFace, aroundNum ); // サイコロの位置セット D3DXVECTOR3 workVec; D3DXMATRIX workMtx; D3DXMatrixIdentity( &workMtx ); workVec = *CStageBlockManager::GetInstance()->GetPos( blockIndex ); workMtx._41 = workVec.x; workMtx._42 = -4.0f; workMtx._43 = workVec.z; // 識別番号のセット m_pDice[ notAppearNo ].SetNo( notAppearNo ); // 回転行列と平行移動行列を乗算 m_pDice[ notAppearNo ].CalcWorldMtx( m_pDice[ notAppearNo ].GetWorldMtx(),&workMtx ); // インデックス番号を保存 m_pDice[ notAppearNo ].SetIndexNo( blockIndex ); // α値の設定 m_pDice[ notAppearNo ].SetColor( 255,255,255,127 ); // 出現中に設定 m_pDice[ notAppearNo ].SetStatus( DICE_STATUS::e_statusStartAppear ); m_pDice[ notAppearNo ].SetAABB(); // 生成されたらステージとダイスに生成されたという情報をセット m_pDice[ notAppearNo ].SetIsDice( true ); CStageBlockManager::GetInstance()->SetBlockToDiceInfo( &m_pDice[ notAppearNo ], blockIndex ); CDebugMode::m_pDiceBox[notAppearNo].diceBox.CreateBox( m_pDice[notAppearNo].GetSize() ); CDebugMode::m_pDiceBox[notAppearNo].diceBox.InitWorldMtx(); CDebugMode::m_pDiceBox[notAppearNo].diceBox.SetWorldMtx( m_pDice[notAppearNo].GetWorldMtx() ); CDebugMode::m_pDiceBox[notAppearNo].diceBox.SetDiffuse( 0, 0, 0, 200 ); CDebugMode::m_pDiceBox[notAppearNo].diceBox.SetAmbient( 255, 0, 0, 255 ); CDebugMode::m_pDiceBox[notAppearNo].isDice = true; return true; } return false; } //---------------------------------------------------- // ダイスのアニメーション //---------------------------------------------------- void CDiceObjManager::Animation( void ) { for( int i = 0; i < MAX_DICE_NUM; ++ i ) { if( m_pDice[i].GetIsDice() == true ) { // プレイヤーの現在地からブロックの添え字番号を取得する UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, CPlayerManager::GetInstance()->GetPlayerPos()->z ); switch( m_pDice[i].GetStatus() ) { // 出現して静止している状態 case DICE_STATUS::e_statusNormal: if( m_pDice[i].GetIndexNo() == playerIndex && ( CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDeleteStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppear ) ) { m_pMainDice->diceObj = &m_pDice[i]; // メインのダイス変更 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDice ); // プレイヤーをダイスの上に乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } break; // 出現し始めアニメーション case DICE_STATUS::e_statusStartAppear: // 現在の添え字がメインダイスの添え字と同じだったらプレイヤーの状態を遷移 if( m_pDice[i].GetIndexNo() == playerIndex && ( CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnStage || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDelete || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDeleteStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppear || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppearStart ) ) { m_pMainDice->diceObj = &m_pDice[i]; // メインのダイス変更 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceAppearStart ); // プレイヤーをダイスの上に乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetIsExist( true ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } // 出現し始めアニメーションが終わったら if( m_pDice[i].UpAnimation( DICE_UP_SPEED ) ) { m_pDice[i].SetStatus( DICE_STATUS::e_statusAppear ); m_pDice[i].SetBeforStatus( DICE_STATUS::e_statusStartAppear ); // ダイスのアニメーションが変わった時も、ダイスの上にいる場合はプレイヤーのステータスを変える if( m_pDice[i].GetIndexNo() == playerIndex ) { CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceAppear ); } } CDebugMode::m_pDiceBox[m_pDice[i].GetNo()].diceBox.SetWorldMtx( m_pDice[m_pDice[i].GetNo()].GetWorldMtx() ); m_pDice[i].SetAABB(); break; // 出現中アニメーション case DICE_STATUS::e_statusAppear: // 出現中アニメーションの上にダイスの上にいるプレイヤーが移動してきたらダイスの上にセット if( m_pDice[i].GetIndexNo() == playerIndex && ( CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDice || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppear || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppearStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDeleteStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDelete ) ) { m_pMainDice->diceObj = &m_pDice[i]; // メインのダイス変更 // プレイヤーの状態を遷移 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceAppear ); // プレイヤーをダイスの上に乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetIsExist( true ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } // 出現アニメーションが終わったら if( m_pDice[i].UpAnimation( DICE_UP_SPEED ) ) { m_pDice[i].SetStatus( DICE_STATUS::e_statusNormal ); m_pDice[i].SetBeforStatus( DICE_STATUS::e_statusAppear ); if( m_pDice[i].GetIndexNo() == playerIndex ) { CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDice ); } // ステージのブロックの状態を変更 CStageBlockManager::GetInstance()->SetIsOnDice( CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pDice[i].GetXPos(), m_pDice[i].GetZPos() ), true ); } CDebugMode::m_pDiceBox[m_pDice[i].GetNo()].diceBox.SetWorldMtx( m_pDice[m_pDice[i].GetNo()].GetWorldMtx() ); m_pDice[i].SetAABB(); break; // 消え始めアニメーション case DICE_STATUS::e_statusStartDelete: // プレイヤーとダイスの添え字番号が同じなら if( m_pDice[i].GetIndexNo() == playerIndex && ( CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDice || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppearStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppear || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDeleteStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDelete ) ) { m_pMainDice->diceObj = &m_pDice[i]; // メインのダイス変更 // プレイヤーの状態を遷移 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceDeleteStart ); // プレイヤーをダイスの上に乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetIsExist( true ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } // 消え始めのアニメーションが終わったら if( m_pDice[i].DownAnimation( -DICE_DOWN_SPEED ) ) { m_pDice[i].SetStatus( DICE_STATUS::e_statusDelete ); m_pDice[i].SetBeforStatus( DICE_STATUS::e_statusStartDelete ); // プレイヤーの位置からブロックの添え字番号を取得する UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, CPlayerManager::GetInstance()->GetPlayerPos()->z ); // プレイヤーとダイスの添え字番号が同じなら if( m_pDice[i].GetIndexNo() == playerIndex ) { CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceDelete ); // プレイヤーをダイスに乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } CDebugMode::m_pDiceBox[m_pDice[i].GetNo()].diceBox.SetWorldMtx( m_pDice[m_pDice[i].GetNo()].GetWorldMtx() ); m_pDice[i].SetAABB(); } break; // 消え中アニメーション case DICE_STATUS::e_statusDelete: // プレイヤーとダイスの添え字番号が同じなら if( m_pDice[i].GetIndexNo() == playerIndex && ( CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppearStart || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceAppear || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnStage || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDelete || CPlayerManager::GetInstance()->GetPlayerStatus() == ePlayerStatus::eOnDiceDeleteStart ) ) { m_pMainDice->diceObj = &m_pDice[i]; // メインのダイス変更 // プレイヤーの状態を遷移 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceDelete ); // プレイヤーをダイスの上に乗せる CPlayerManager::GetInstance()->SetPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, m_pDice[i].GetYPos() + 4.0f, CPlayerManager::GetInstance()->GetPlayerPos()->z ); m_pDiceInfoManager->SetIsExist( true ); m_pDiceInfoManager->SetInfoDice( m_pMainDice->diceObj->GetWorldMtx() ); } // 消えアニメーションが終わったら if( m_pDice[i].DownAnimation( -DICE_DOWN_SPEED ) ) { m_pDice[i].SetStatus( DICE_STATUS::e_statusNone ); m_pDice[i].SetBeforStatus( DICE_STATUS::e_statusDelete ); m_pDice[i].SetIsDice( false ); // ダイスなしの状態に設定する m_pDice[i].SetIsChain( false ); // チェインしていない状態に設定する // チェインのダイスの個数を減らしてもしなくなったらチェイン終了 CChainManager::GetInstance()->GetChain( m_pDice[i].GetChainNo() )->chainDiceNum --; if( CChainManager::GetInstance()->GetChain( m_pDice[i].GetChainNo() )->chainDiceNum == 0 ) { CChainManager::GetInstance()->GetChain( m_pDice[i].GetChainNo() )->isChain = false; } // プレイヤーの現在地からブロックの添え字番号を取得 UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( CPlayerManager::GetInstance()->GetPlayerPos()->x, CPlayerManager::GetInstance()->GetPlayerPos()->z ); // プレイヤーの添え字番号とダイスが同じだったらプレイヤーのステータス変更 if( m_pDice[i].GetIndexNo() == playerIndex ) { CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnStage ); m_pDiceInfoManager->SetIsExist( false ); } // ステージ上からダイスを削除 CStageBlockManager::GetInstance()->SetIsOnDice( CStageBlockManager::GetInstance()->GetIndexToDicePos( m_pDice[i].GetXPos(), m_pDice[i].GetZPos() ), false ); m_diceNum --; } CDebugMode::m_pDiceBox[m_pDice[i].GetNo()].diceBox.SetWorldMtx( m_pDice[m_pDice[i].GetNo()].GetWorldMtx() ); m_pDice[i].SetAABB(); break; } } } }<file_sep> #include "../../KaiFrameWorkHeader/DirectX9Header/CDirectX9Light.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDirectLight::CDirectLight( void ) { ZeroMemory( &light,sizeof( D3DLIGHT9 ) ); light.Type = D3DLIGHT_DIRECTIONAL; light.Diffuse.r = 1.0f; light.Diffuse.g = 1.0f; light.Diffuse.b = 1.0f; light.Diffuse.a = 1.0f; light.Specular.r = 1.0f; light.Specular.g = 1.0f; light.Specular.b = 1.0f; light.Direction = D3DXVECTOR3( 0.0f,-1.0f,0.0f); light.Range = 1000.0f; this->Set(); this->Switch( true ); this->SetStageAmbient( 0x88888888 ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDirectLight::~CDirectLight( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CDirectLight::Init( void ) { } //---------------------------------------------------- // ライトのセット //---------------------------------------------------- void CDirectLight::Set( void ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetLight( 0,&light ); } //---------------------------------------------------- // ライトのON OFF //---------------------------------------------------- void CDirectLight::Switch( bool isLight ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); if( isLight == true ) { pd3dDevice->LightEnable( 0, true ); } else { pd3dDevice->LightEnable( 0, false ); } } //---------------------------------------------------- // ライトの位置セット //---------------------------------------------------- void CDirectLight::SetPosition( float xPos,float yPos,float zPos ) { light.Direction.x = xPos; light.Direction.y = yPos; light.Direction.z = zPos; } //---------------------------------------------------- // ステージ全体のアンビエント光のセット //---------------------------------------------------- void CDirectLight::SetStageAmbient( DWORD ambient ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetRenderState( D3DRS_AMBIENT, ambient ); } <file_sep> #include "../../KaiFrameWorkHeader/DebugHeader/CDebugStage.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDebugStage::CDebugStage( void ) { m_lineNum = 0; m_pLineStage = new tagTDEBUGVERTEX; } //---------------------------------------------------- // コンストラクタ( ライン数を設定 ) //---------------------------------------------------- CDebugStage::CDebugStage( CONST UINT lineNum ) { m_lineNum = lineNum; m_pLineStage = new tagTDEBUGVERTEX[ lineNum ]; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDebugStage::~CDebugStage( void ) { SAFE_DELETE_ALLAY( m_pLineStage ); } //---------------------------------------------------- // 初期化 原点を中心とした正方形 //---------------------------------------------------- void CDebugStage::Init( CONST FLOAT lineLen ) { float width = lineLen / ( (m_lineNum - 1 ) / 2 / 2 ); float lineWidth = lineLen / 2; int j = 0; for( UINT i = 0; i < m_lineNum / 2; i += 2 ){ m_pLineStage[i].pos.x = lineWidth; m_pLineStage[i+1].pos.x = -lineWidth; m_pLineStage[i].pos.y = -10.0f; m_pLineStage[i+1].pos.y = -10.0f; m_pLineStage[i].pos.z = lineWidth - j * width; m_pLineStage[i+1].pos.z = lineWidth - j * width; m_pLineStage[i].color = D3DCOLOR_RGBA( 255,255,255,255 ); m_pLineStage[i+i].color = D3DCOLOR_RGBA( 255,255,255,255 ); j ++; } j = 0; for( UINT i = m_lineNum / 2; i < m_lineNum; i += 2 ){ m_pLineStage[i].pos.x = lineWidth - j * width; m_pLineStage[i+1].pos.x = lineWidth - j * width; m_pLineStage[i].pos.y = -10.0f; m_pLineStage[i+1].pos.y = -10.0f; m_pLineStage[i].pos.z = lineWidth; m_pLineStage[i+1].pos.z = -lineWidth; m_pLineStage[i].color = D3DCOLOR_RGBA( 255,255,255,255 ); m_pLineStage[i+1].color = D3DCOLOR_RGBA( 255,255,255,255 ); j ++; } } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CDebugStage::Uninit( void ) { } <file_sep>//---------------------------------------------------- // CSplitParticle // ダイスが動いた時に弾けるパーティクル // // @date 2014/1/27 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SPLIT_PARTICLE_ #define _C_SPLIT_PARTICLE_ #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DParticle.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourcePath.hpp" #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CXorShift.hpp" #include "../../../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" class CSplitParticle { private: LPSTR m_pResParticle; C2DParticle* m_pSplitPartcle; public: // コンストラクタ CSplitParticle ( void ); // デストラクタ ~CSplitParticle ( void ); public: void Emitter ( CONST float xPos, CONST float yPos, CONST float zPos ); void Move ( void ); void Draw ( CONST D3DXMATRIX* view ); }; #endif _C_SPLIT_PARTICLE_<file_sep> #include "../../KaiFrameWorkHeader/ResourceHeader/CResourceXFont.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CResourceXFont::CResourceXFont( void ) { m_pFont = nullptr; m_color = D3DXCOLOR( 255,255,255,255 ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CResourceXFont::~CResourceXFont( void ) { SAFE_DELETE_RELESE( m_pFont ); } //---------------------------------------------------- // XFontの作成 //---------------------------------------------------- HRESULT CResourceXFont::Create( CONST UINT width, CONST UINT height ) { LPDIRECT3DDEVICE9& pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); if( D3DXCreateFont(pd3dDevice, height, width, FW_MEDIUM, NULL, FALSE, SHIFTJIS_CHARSET, OUT_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH | FF_MODERN, "MSPゴシック", &m_pFont) ) { DEBUG::PrintfColor( DEBUG::H_RED, "Create Font Failed...\n" ); return E_FAIL; } DEBUG::PrintfColor(DEBUG::H_PURPLE, "Create Font Successfully\n" ); return S_OK; } //---------------------------------------------------- // 色の設定 //---------------------------------------------------- void CResourceXFont::SetColor( CONST D3DXCOLOR color ) { m_color = color; } //---------------------------------------------------- // 可変引数に変換 //---------------------------------------------------- inline char* CResourceXFont::OutPutStringArgList( char* buff, CONST LPSTR str, va_list argList ) { char buf[2048]; _vsnprintf_s( buf, _countof(buf), str, argList ); OutputDebugStringA( buf ); ::CopyMemory( buff, buf, sizeof( buf ) ); return buff; } //---------------------------------------------------- // 色を変更しながらテキストの描画 //---------------------------------------------------- void CResourceXFont::DrawColor( CONST long xPos, CONST long yPos, CONST D3DXCOLOR color, CONST LPSTR str, ... ) { RECT rect = { xPos, yPos, 0, 0 }; char buf[2048]; ::ZeroMemory( buf, sizeof( buf ) ); va_list args; // カラーの変更 m_color = color; va_start( args, str ); this->OutPutStringArgList( buf, str, args ); m_pFont->DrawTextA( NULL, buf, -1, &rect, DT_CALCRECT, NULL ); m_pFont->DrawTextA( NULL, buf, -1, &rect, DT_LEFT | DT_BOTTOM, color ); va_end( args ); } //---------------------------------------------------- // テキストの描画 //---------------------------------------------------- void CResourceXFont::Draw( CONST long xPos, CONST long yPos, CONST LPSTR str, ... ) { RECT rect = { xPos, yPos, 0, 0 }; char buf[1024]; ::ZeroMemory( buf,sizeof( buf ) ); va_list args; va_start( args, str ); this->OutPutStringArgList( buf, str, args ); m_pFont->DrawTextA( NULL, buf, -1, &rect, DT_CALCRECT, NULL ); m_pFont->DrawTextA( NULL, buf, -1, &rect, DT_LEFT | DT_BOTTOM, m_color ); va_end( args ); }<file_sep> #include "../../KaiFrameWorkHeader/DirectX9Header/CDirectX9FrameWork.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDirectX9FrameWork::CDirectX9FrameWork( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDirectX9FrameWork::~CDirectX9FrameWork( void ) { } //---------------------------------------------------- // DirectX9の初期化 //---------------------------------------------------- HRESULT CDirectX9FrameWork::Init( void ) { CONST HWND& hWnd = CWindowSystem::GethWnd(); LPDIRECT3D9& pd3d = CDirectX9FrameWork::Getpd3d(); LPDIRECT3DDEVICE9& pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); D3DPRESENT_PARAMETERS d3dpp; if( NULL == ( pd3d = Direct3DCreate9(D3D_SDK_VERSION ))) { //Direct3Dオブジェクトの作成失敗 return E_FAIL; } ZeroMemory( &d3dpp, sizeof(d3dpp)); d3dpp.Windowed = TRUE; // ウィンドウモード d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // 映像信号に同期してフリップする d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // バックバッファのフォーマットは現在設定されているものを使う d3dpp.EnableAutoDepthStencil = TRUE; // デプスバッファ(Zバッファ)とステンシルバッファを作成 d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // デプスバッファとして16bitを使う if( FAILED( pd3d->CreateDevice( D3DADAPTER_DEFAULT, // プライマリアダプタを選択 D3DDEVTYPE_HAL, // ハードウェアによる描画処理を選択 hWnd, // ウィンドウハンドル D3DCREATE_HARDWARE_VERTEXPROCESSING | // ハードウェアによる頂点計算を選択 D3DCREATE_MULTITHREADED , // マルチスレッドのフラグをONにする &d3dpp, // D3D Object &pd3dDevice ))) { DEBUG::PrintfColor( DEBUG::H_RED, "---- Init DirectX Failed... ----\n\n" ); return E_FAIL; // 成功すればデバイスが作られる } pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); // Zバッファを使用 pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); // αブレンドを行う pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); // αソースカラーの指定 pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); // αデスティネーションカラーの指定 pd3dDevice->SetRenderState( D3DRS_CULLMODE,D3DCULL_NONE ); pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); pd3dDevice->SetFVF( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ); DEBUG::PrintfColor( DEBUG::H_GREEN, "---- Init DirectX Successfully ---- \n\n" ); return D3D_OK; // 生成成功 } <file_sep>//---------------------------------------------------- // CXFont // DirectXを使用した文字作成 // // @date 2013/6/20 // @update 2013/12/6 // @author T.kawashita //---------------------------------------------------- #ifndef _C_RESOURCE_XFONT_H_ #define _C_RESOURCE_XFONT_H_ #include <d3dx9.h> #include "../DirectX9Header/CDirectX9FrameWork.h" #include "../UtilityHeader/Macro.hpp" class CResourceXFont { private: LPD3DXFONT m_pFont; D3DXCOLOR m_color; public: // コンストラクタ CResourceXFont (void); // デストラクタ virtual ~CResourceXFont (void); //---------------------------------------------------- // @name Create // @content フォントの作成 // @param width 1文字の横幅 // @param height 1文字の高さ // @return 作成できたかどうか // @date 2013/6/20 //---------------------------------------------------- HRESULT Create( CONST UINT width, CONST UINT height ); //---------------------------------------------------- // @name SetColor // @content フォントの色の設定 // @param color フォントの色 // @return none // @date 2013/12/6 //---------------------------------------------------- void SetColor ( CONST D3DXCOLOR color ); //---------------------------------------------------- // @name OutPutStringArgList // @content 可変引数に変換 // @param str 文字列 // @param argList 可変引数配列 // @return char* 変換した文字列 // @date 2013/12/6 //---------------------------------------------------- inline char* OutPutStringArgList ( char* buff ,CONST LPSTR str, va_list argList ); //---------------------------------------------------- // @name DrawColor // @content カラーを変更しながらのテキストの描画 // @param xPos X座標 // @param yPos Y座標 // @param color 色情報 // @param str 描画したい文字列 // @return none // @date 2013/6/20 // @update 2013/12/6 可変引数に変更 //---------------------------------------------------- void DrawColor ( CONST long xPos, CONST long yPos, CONST D3DXCOLOR color, CONST LPSTR str,... ); //---------------------------------------------------- // @name Draw // @content テキストの描画 // @param xPos X座標 // @param yPos Y座標 // @param str 描画したい文字列 // @return none // @date 2013/12/6 //---------------------------------------------------- void Draw ( CONST long xPos, CONST long yPos, CONST LPSTR str,... ); }; #endif _C_RESOURCE_XFONT_H_<file_sep>//---------------------------------------------------- // COriginalMesh Header // メッシュから情報を抜き出すヘッダー // // @date 2013/8/7 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_ORIGINAL_MESH_H_ #define _C_ORIGINAL_MESH_H_ #include <d3dx9.h> #include "../UtilityHeader/Macro.hpp" #include "../DirectX9Header/CDirectX9FrameWork.h" //#include "../GameMathHeader/CCollision.h" #define VERTEX_NUM (3) // 頂点数 #define CLONE_FVF ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) struct Position { float x,y,z; }; //---------------------------------------------------- // オリジナルメッシュのトライアングル頂点構造体 //---------------------------------------------------- typedef struct TAGtORIGINALMESHVERTEX { D3DXVECTOR3 pos; D3DCOLOR diffuse; FLOAT tu,tv; }tagTORIGINALMESHVERTEX; // 結線情報 struct MyConnect { WORD idx[3]; }; //---------------------------------------------------- // オリジナルメッシュ用構造体 //---------------------------------------------------- typedef struct TAGtORIGINALMESH { UINT numFaces; // ポリゴン面数 UINT numVertex; // 頂点数 MyConnect* connect; // 結線情報 tagTORIGINALMESHVERTEX* vertex; // 頂点情報 }tagTORIGINALMESH; struct MyTriangle { tagTORIGINALMESHVERTEX vertex[3]; D3DXVECTOR3 angle; D3DXVECTOR3 d; Position center; Position normal; int m_vLife; // 生存値 bool isExist; // 生存確認 D3DXVECTOR3 m_vLogPos; // 位置情報 D3DXMATRIX mat; MyTriangle() { angle.x = 0.0f; angle.y = 0.0f; angle.z = 0.0f; d.x = 0.2f; d.y = 0.2f; d.z = 0.2f; D3DXMatrixIdentity(&mat); } }; class COriginalMesh { private: MyTriangle* pTriangle; // トライアングルの先頭 D3DXMATRIX m_worldMtx; // 行列 tagTORIGINALMESH m_cloneData; // クローンメッシュ用データ public: COriginalMesh ( void ); ~COriginalMesh ( void ); //---------------------------------------------------- // オリジナルメッシュ作成 //---------------------------------------------------- tagTORIGINALMESH* CreateOriginalMesh ( tagTORIGINALMESH* cloneData, CONST LPSTR filePath ); public: //---------------------------------------------------- // ポリゴン面数 取得 // @data none // @return[UINT] ポリゴン面数 //---------------------------------------------------- UINT GetFaces (void) { return m_cloneData.numFaces; } //---------------------------------------------------- // 頂点座標 取得 //---------------------------------------------------- D3DXVECTOR3* GetVertexVec (int faceNum,int verNum) { return &(pTriangle+faceNum)->vertex[verNum].pos; } public: // void Init ( LPD3DXMESH lpMesh,THITCIRCLE* colData2 ); // void MoveClone3D ( void ); // bool ColorClone3D ( void ); // void RotationClone3D ( void ); // void TraiangleTransform ( D3DXMATRIX mat ); // void LocalToWorld ( D3DXMATRIX mat ); //---------------------------------------------------- // クローンを生成する // @data lpMesh // @return bool // @overload //---------------------------------------------------- // bool Create ( LPD3DXMESH lpMesh ); }; #endif _C_ORIGINAL_MESH_H_<file_sep>//---------------------------------------------------- // CBillBoard // ビルボードのクラス // // @date 2013/6/15 // @update 2013/12/12 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_BILLBOARD_H_ #define _C_BILLBOARD_H_ #include <Windows.h> #include <d3dx9.h> // 頂点フォーマット(ビルボード用) typedef struct TAGtBILLBORDVERTEX { D3DXVECTOR3 pos; D3DCOLOR color; float tu,tv; }tagTBILLBORDVERTEX; class CBillBoard { private: D3DXMATRIX m_mtx; // ビルボード用の行列 D3DXVECTOR3 m_pos; // ビルボードの位置座標 D3DXVECTOR3 m_size; // ビルボードのサイズ D3DCOLOR m_color; // カラー値 int m_maxAlfa; // 開始時のα値 tagTBILLBORDVERTEX m_vertex[4]; // ビルボードの頂点座標 public: // 引数なしコンストラクタ CBillBoard() { m_pos.x = 0.0f; m_pos.y = 0.0f; m_pos.z = 0.0f; D3DXMatrixIdentity( &m_mtx ); } // 引数を設定するコンストラクタ CBillBoard( float x, float y, float z, float xSize, float ySize, D3DCOLOR color) { m_pos.x = x; m_pos.y = y; m_pos.z = z; m_size.x = xSize; m_size.y = ySize; m_color = color; D3DXMatrixIdentity( &m_mtx ); this->SetVertex(); m_maxAlfa = 255; } // デストラクタ ~CBillBoard(){} public: // ビルボード用の行列の取得 D3DXMATRIX* GetMat() { return &m_mtx; } // ビルボード用の頂点情報の取得 const tagTBILLBORDVERTEX* GetVertex() { return m_vertex; } // ビルボード用座標の取得 const D3DXVECTOR3* GetPos() { return &m_pos; } public: // α値の取得 const int GetAlfa ( void ) { return ( m_color >> 24 ); } // α値のセット void SetAlfa ( int alfa ); void SetDiffuse ( int alfa ); // 最大α値のセット void SetMaxAlfa ( int maxAlfa ); const int GetMaxAlfa( void ) { return m_maxAlfa; } void SetVertex ( void ); // 頂点座標のセット void SetVertex ( int windowX,int windowY ); // 頂点座標のセット(左上原点) void SetPosition ( const float x,const float y,const float z ); // 位置をセット void SetBillboard ( float xSize,float ySize,D3DCOLOR color); // ビルボードのセット void SetBillboard ( float size,D3DCOLOR color ); // ビルボードのセット(サイズ同じ) }; #endif _C_BILLBOARD_H_<file_sep>//---------------------------------------------------- // C2DSprite // 2Dの板ポリゴン(3D座標) // // @date 2013/12/12 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_2D_SPRITE_H_ #define _C_2D_SPRITE_H_ #include <d3dx9.h> #include "../CObjectBase.hpp" // 頂点フォーマット typedef struct TAGtSPRITE { D3DXVECTOR3 pos; D3DCOLOR diffuse; float tu,tv; }tagTSPRITE; class C2DSprite : public CObjectBase { private: D3DXVECTOR3 m_pos; // 位置座標 D3DXVECTOR3 m_size; // スプライトの大きさ protected: tagTSPRITE m_vertex[4]; // 頂点座標 public: // コンストラクタ C2DSprite ( void ); // デストラクタ virtual ~C2DSprite ( void ); //---------------------------------------------------- // 頂点情報の取得 //---------------------------------------------------- tagTSPRITE* GetVertex ( void ) { return m_vertex; } //---------------------------------------------------- // 位置情報の取得 //---------------------------------------------------- CONST D3DXVECTOR3* GetPos ( void ) { return &m_pos; } //---------------------------------------------------- // スプライトの大きさの取得 //---------------------------------------------------- CONST D3DXVECTOR3* GetSize ( void ) { return &m_size; } //---------------------------------------------------- // @name SetSprite // @content スプライトのセット // @param pos 位置座標 // @param size サイズ // @return none // @date 2013/12/18 //---------------------------------------------------- bool SetSprite ( CONST D3DXVECTOR3* pos, CONST D3DXVECTOR3* size ); //---------------------------------------------------- // @name SetSpritePos // @content スプライトの位置のセット(3次元空間上) // @param x x座標位置 // @param y y座標位置 // @param z z座標位置 // @return none // @date 2013/12/13 //---------------------------------------------------- void SetSpritePos ( CONST float x, CONST float y, CONST float z ); //---------------------------------------------------- // @name MoveSpritePos // @content スプライトの位置移動 // @param x X移動量 // @return y y移動量 // @date z z移動量 // @update 2013/12/18 //---------------------------------------------------- void MoveSpritePos ( CONST float x, CONST float y, CONST float z ); //---------------------------------------------------- // @name MoveSpritePos // @content スプライトの位置移動(vector指定) // @param vec 位置ベクトル // @return none // @date 2013/12/18 //---------------------------------------------------- void MoveSpritePos ( CONST D3DXVECTOR3* vec ); //---------------------------------------------------- // @name SetSpritSize // @content スプライトのサイズをセット // @param xSize 横幅 // @param ySize 縦幅 // @return none // @date 2013/12/13 //---------------------------------------------------- void SetSpriteSize ( CONST float xSize, CONST float ySize ); //---------------------------------------------------- // @name SetVertexPos // @content 頂点の位置のセット(サイズに依存) // @param none // @return none // @date 2013/12/13 //---------------------------------------------------- void SetVertexPos ( void ); //---------------------------------------------------- // @name SetUV // @content テクスチャ座標のセット // @param none // @return none // @date 2013/12/12 //---------------------------------------------------- void SetUV ( void ); //---------------------------------------------------- // @name SetUV // @content テクスチャ座標のセット(パターン数を設定) // @param uPatern 横パターン数 // @param vPatern 縦パターン数 // @param uNum 横の番号 // @param vNum 縦の番号 // @return none // @date 2013/12/13 //---------------------------------------------------- void SetUV ( CONST UINT uPatern, CONST UINT vPatern, CONST UINT uNum, CONST UINT vNum ); //---------------------------------------------------- // @name SetDiffuse // @content 頂点色の設定 // @param r 赤値( 0 〜 255 ) // @param g 緑値( 0 〜 255 ) // @param b 青値( 0 〜 255 ) // @param a α値( 0 〜 255 ) // @return none // @date 2014/1/128 //---------------------------------------------------- void SetDiffuse ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // @name CalcWorldMtx // @content 板ポリゴンの行列をワールド空間上の行列に変換 // @param none // @return none // @date 2013/12/12 //---------------------------------------------------- void CalcWorldMtx ( void ); }; #endif _C_2D_SPRITE_H_<file_sep> #include "../../KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDirectCamera::CDirectCamera( void ) { // 位置・注視点・方向初期化 this->Init(); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDirectCamera::~CDirectCamera( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CDirectCamera::Init( CONST int windowSizeX, CONST int windowSizeY ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); D3DXMatrixIdentity( &m_view ); D3DXMatrixIdentity( &m_projection ); D3DXMatrixIdentity( &m_ortho ); D3DXMatrixIdentity( &m_worldMtx ); // プロジェクション座標変換行列の算出 D3DXMatrixPerspectiveFovLH(&m_projection, D3DXToRadian( 45.0f ), (float)windowSizeX / (float)windowSizeY, 1.0f, 2000.0f); // 正射影変換座標行列の算出 D3DXMatrixOrthoLH(&m_ortho,(float)windowSizeX,(float)-windowSizeY,1.0f,2000.0f); // カメラ座標変換行列の算出 D3DXMatrixLookAtLH(&m_view, &m_vEye, &m_vAt, &m_vUp); // カメラとプロジェクションの変換行列のセット pd3dDevice->SetTransform(D3DTS_VIEW, &m_view); pd3dDevice->SetTransform(D3DTS_PROJECTION, &m_projection); this->SetView(); return true; }//---------------------------------------------------- //---------------------------------------------------- // 初期化(位置+注視点+方向) //---------------------------------------------------- bool CDirectCamera::Init( void ) { m_worldMtx._41 = 0.0f; m_worldMtx._42 = 0.0f; m_worldMtx._43 = -20.0f; // カメラの位置座標 m_worldMtx._31 = 0.0f; m_worldMtx._32 = 0.0f; m_worldMtx._33 = 1.0f; // カメラの注視点座標 m_worldMtx._21 = 0.0f; m_worldMtx._22 = 1.0f; m_worldMtx._23= 0.0f; // カメラの上方向ベクトル return true; } //---------------------------------------------------- // カメラのセット //---------------------------------------------------- bool CDirectCamera::Set( void ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // カメラ座標変換行列の算出 D3DXMatrixLookAtLH( &m_view, &m_vEye, &m_vAt, &m_vUp ); // カメラのセット pd3dDevice->SetTransform( D3DTS_VIEW, &m_view ); return true; } //---------------------------------------------------- // カメラの位置セット //---------------------------------------------------- bool CDirectCamera::SetPosition( CONST float xPos, CONST float yPos, CONST float zPos ) { m_worldMtx._41 = m_worldMtx._41 + xPos; m_worldMtx._42 = m_worldMtx._42 + yPos; m_worldMtx._43 = m_worldMtx._43 + zPos; // ワールド行列にセットした後ワールドに配置 this->SetView(); return true; } //---------------------------------------------------- // カメラの注視点セット //---------------------------------------------------- bool CDirectCamera::SetAt( CONST float xPos, CONST float yPos, CONST float zPos ) { m_worldMtx._31 = m_worldMtx._31 + xPos; m_worldMtx._32 = m_worldMtx._32 + yPos; m_worldMtx._33 = m_worldMtx._33 + zPos; // ワールド行列にセットした後ワールドに配置 this->SetView(); return true; } //---------------------------------------------------- // カメラワールド行列のセット //---------------------------------------------------- bool CDirectCamera::SetView( void ) { m_vEye.x = m_worldMtx._41; m_vEye.y = m_worldMtx._42; m_vEye.z = m_worldMtx._43; m_vAt.x = m_worldMtx._31; m_vAt.y = m_worldMtx._32; m_vAt.z = m_worldMtx._33; m_vUp.x = m_worldMtx._21; m_vUp.y = m_worldMtx._22; m_vUp.z = m_worldMtx._23; // カメラをワールドに配置 this->Set(); return true; } //---------------------------------------------------- // モデルのベクトルを利用しての追従カメラ // モデルの後ろの位置にカメラを置いたまま追従される //---------------------------------------------------- void CDirectCamera::Tracking( CONST D3DXMATRIX* pMtx, CONST D3DXVECTOR3* pVec , CONST float distance) { // カメラの位置セット m_vEye.x = pVec->x * distance + pMtx->_41; m_vEye.y = pVec->y * distance + pMtx->_42; m_vEye.z = pVec->z * distance + pMtx->_43; // カメラの注視点座標 m_vAt.x = pMtx->_41; m_vAt.y = pMtx->_42; m_vAt.z = pMtx->_43; // ジンバルロックを防ぐ m_vUp.x = pMtx->_21; m_vUp.y = pMtx->_22; m_vUp.z = pMtx->_23; // ワールド位置にカメラを配置 this->Set(); } //---------------------------------------------------- // 主観カメラ( ベクトルを考慮していない ) //---------------------------------------------------- void CDirectCamera::Tracking( CONST D3DXMATRIX* pMtx, CONST float at ) { // カメラの注視点更新 m_vAt.x = pMtx->_31 * at + pMtx->_41; m_vAt.y = pMtx->_32 * at + pMtx->_42; m_vAt.z = pMtx->_33 * at + pMtx->_43; // カメラの位置更新 m_vEye.x = pMtx->_41; m_vEye.y = pMtx->_42; m_vEye.z = pMtx->_43; // カメラの上方向更新(ジンバルロックを防ぐ) m_vUp.x = pMtx->_21; m_vUp.y = pMtx->_22; m_vUp.z = pMtx->_23; // ワールド位置に配置 this->Set(); } //---------------------------------------------------- // カメラを向いた画像描画(ビルボード) //---------------------------------------------------- D3DXMATRIX* CDirectCamera::SetBillBoardMtx( D3DXMATRIX* pBillBoardMtx, CONST D3DXVECTOR3* pBillBoardPos ) { D3DXMatrixIdentity( pBillBoardMtx ); pBillBoardMtx->_11 = m_view._11; pBillBoardMtx->_12 = m_view._21; pBillBoardMtx->_13 = m_view._31; pBillBoardMtx->_21 = m_view._12; pBillBoardMtx->_22 = m_view._22; pBillBoardMtx->_23 = m_view._32; pBillBoardMtx->_31 = m_view._13; pBillBoardMtx->_32 = m_view._23; pBillBoardMtx->_33 = m_view._33; pBillBoardMtx->_41 = pBillBoardPos->x; pBillBoardMtx->_42 = pBillBoardPos->y; pBillBoardMtx->_43 = pBillBoardPos->z; pBillBoardMtx->_14 = 0.0f; pBillBoardMtx->_24 = 0.0f; pBillBoardMtx->_34 = 0.0f; pBillBoardMtx->_44 = 1.0f; return pBillBoardMtx; } //---------------------------------------------------- // カメラが動いても変化しない画像描画(ビルボード) //---------------------------------------------------- D3DXMATRIX* CDirectCamera::SetBillBoardMtx( D3DXMATRIX* pBillBoardMtx, CONST float distance ) { D3DXMatrixIdentity( pBillBoardMtx ); pBillBoardMtx->_11 = m_view._11; pBillBoardMtx->_12 = m_view._12; pBillBoardMtx->_13 = m_view._13; pBillBoardMtx->_21 = m_view._21; pBillBoardMtx->_22 = m_view._22; pBillBoardMtx->_23 = m_view._23; pBillBoardMtx->_31 = m_view._31; pBillBoardMtx->_32 = m_view._32; pBillBoardMtx->_33 = m_view._33; pBillBoardMtx->_41 = m_vEye.x + m_vAt.x * -1.0f * distance; pBillBoardMtx->_42 = m_vEye.y + m_vAt.y * -1.0f * distance; pBillBoardMtx->_43 = m_vEye.z + m_vAt.z * -1.0f * distance; pBillBoardMtx->_14 = 0.0f; pBillBoardMtx->_24 = 0.0f; pBillBoardMtx->_34 = 0.0f; pBillBoardMtx->_44 = 1.0f; return pBillBoardMtx; } //---------------------------------------------------- // クォータニオンの計算 //---------------------------------------------------- bool CDirectCamera::CalcLocalQuaternion( CONST D3DXVECTOR3* pAxis, CONST float degree ) { D3DXQUATERNION localQuater; D3DXMATRIX rotationMat; D3DXMatrixIdentity( &rotationMat ); // 行列からクォータニオンを生成 D3DXQuaternionRotationMatrix( &localQuater, &m_worldMtx ); // 任意の軸を回転軸としてクォータニオンを回転させる D3DXQuaternionRotationAxis( &localQuater, pAxis, D3DXToRadian( degree ) ); // クォータニオンから行列を求める D3DXMatrixRotationQuaternion( &rotationMat, &localQuater ); D3DXMatrixMultiply( &m_worldMtx, &m_worldMtx,&rotationMat ); // カメラをワールドに配置 this->SetView(); return true; } //---------------------------------------------------- // ローカルクォータニオンX回転 //---------------------------------------------------- void CDirectCamera::LocalRotationQuaterX( CONST float degree ) { D3DXVECTOR3 axis; axis.x = m_worldMtx._11; axis.y = m_worldMtx._12; axis.z = m_worldMtx._13; // クォータニオン計算 this->CalcLocalQuaternion( &axis, degree ); } //---------------------------------------------------- // ローカルクォータニオンY回転 //---------------------------------------------------- void CDirectCamera::LocalRotationQuaterY( CONST float degree ) { D3DXVECTOR3 axis; axis.x = m_worldMtx._21; axis.y = m_worldMtx._22; axis.z = m_worldMtx._23; // クォータニオン計算 this->CalcLocalQuaternion( &axis, degree ); } //---------------------------------------------------- // ローカルクォータニオンZ回転 //---------------------------------------------------- void CDirectCamera::LocalRotationQuaterZ( CONST float degree ) { D3DXVECTOR3 axis; axis.x = m_worldMtx._31; axis.y = m_worldMtx._32; axis.z = m_worldMtx._33; // クォータニオン計算 this->CalcLocalQuaternion( &axis, degree ); } //---------------------------------------------------- // ローカル任意軸クォータニオン回転 //---------------------------------------------------- void CDirectCamera::LocalRotationQuater( CONST D3DXVECTOR3* pVec, CONST float degree ) { D3DXVECTOR3 axis; axis.x = pVec->x; axis.y = pVec->y; axis.z = pVec->z; // クォータニオン回転計算 this->CalcLocalQuaternion( &axis, degree ); }<file_sep> #include "CModeSelectPlayerManager.h" const float PLAYER_MOVE_DEFAULT = 0.2f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CModeSelectPlayerManager::CModeSelectPlayerManager( void ) { // プレイヤーのインスタンス化 m_pModeSelectPlayer = new C2DSprite; m_pResModeSelectPlayerPath = PLAYER_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResModeSelectPlayerPath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CModeSelectPlayerManager::~CModeSelectPlayerManager( void ) { SAFE_DELETE( m_pModeSelectPlayer ); } //---------------------------------------------------- //初期化 //---------------------------------------------------- bool CModeSelectPlayerManager::Init( void ) { // プレイヤーの初期化 m_pModeSelectPlayer->Init(); m_pModeSelectPlayer->CalcWorldMtx(); m_pModeSelectPlayer->SetSpritePos( -1.0f, 2.0f, 2.0f ); m_pModeSelectPlayer->SetSpriteSize( 5.0f, 5.0f ); m_pModeSelectPlayer->SetUV( 4, 4, 1, 1 ); m_eMovePlayerStatus = eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone; m_moveValue = 0.0f; return true; } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CModeSelectPlayerManager::Uninit( void ) { return true; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CModeSelectPlayerManager::Run( void ) { switch( m_eMovePlayerStatus ) { // 通常状態 case eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone: break; // 左移動 case eModeSelectMovePlayerStatus::eModeSelectPlayerMoveLeft: this->MoveLeft( PLAYER_MOVE_DEFAULT ); m_pModeSelectPlayer->SetUV( 4, 4, 1, 3 ); break; // 右移動 case eModeSelectMovePlayerStatus::eModeSelectPlayerMoveRight: this->MoveRight( PLAYER_MOVE_DEFAULT ); m_pModeSelectPlayer->SetUV( 4, 4, 1, 2 ); break; // 上移動 case eModeSelectMovePlayerStatus::eModeSelectPlayerMoveUp: this->MoveUp( PLAYER_MOVE_DEFAULT ); m_pModeSelectPlayer->SetUV( 4, 4, 1, 4 ); break; // 下移動 case eModeSelectMovePlayerStatus::eModeSelectPlayerMoveDown: this->MoveDown( PLAYER_MOVE_DEFAULT ); m_pModeSelectPlayer->SetUV( 4, 4, 1, 1 ); break; } } //---------------------------------------------------- // 右移動 //---------------------------------------------------- void CModeSelectPlayerManager::MoveRight( CONST float speed ) { m_pModeSelectPlayer->MoveSpritePos( speed, 0.0f,0.0f ); m_moveValue += speed; if( m_moveValue >= 4.0f ) { m_moveValue = 0.0f; m_eMovePlayerStatus = eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone; } } //---------------------------------------------------- // 左移動 //---------------------------------------------------- void CModeSelectPlayerManager::MoveLeft( CONST float speed ) { m_pModeSelectPlayer->MoveSpritePos( -speed, 0.0f,0.0f ); m_moveValue -= speed; if( m_moveValue <= -4.0f ) { m_moveValue = 0.0f; m_eMovePlayerStatus = eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone; } } //---------------------------------------------------- // 上移動 //---------------------------------------------------- void CModeSelectPlayerManager::MoveUp( CONST float speed ) { m_pModeSelectPlayer->MoveSpritePos( 0.0f, 0.0f, speed ); m_moveValue += speed; if( m_moveValue >= 4.0f ) { m_moveValue = 0.0f; m_eMovePlayerStatus = eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone; } } //---------------------------------------------------- // 下移動 //---------------------------------------------------- void CModeSelectPlayerManager::MoveDown( CONST float speed ) { m_pModeSelectPlayer->MoveSpritePos( 0.0f, 0.0f, -speed ); m_moveValue -= speed; if( m_moveValue <= -4.0f ) { m_moveValue = 0.0f; m_eMovePlayerStatus = eModeSelectMovePlayerStatus::eModeSelectPlayerMoveNone; } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CModeSelectPlayerManager::Draw( void ) { // プレイヤー描画 CDirectDrawSystem::GetInstance()->DrawSprite( CResourceManager::GetInstance()->GetTexture( m_pResModeSelectPlayerPath )->Get(), m_pModeSelectPlayer->GetVertex(), m_pModeSelectPlayer->GetWorldMtx() ); }<file_sep> #include "CScoreManager.h" const float ConstScoreValueXPos = 600.0f; const float ConstScoreValueYPos = 20.0f; const float ConstScoreValueXSize = 100.0f; const float ConstScoreValueYSize = 22.0f; const float ConstScoreDigitXPos = ConstScoreValueXPos - 65.0f; const float ConstScoreDigitYPos = ConstScoreValueYPos + 30.0f; const float ConstScoreDigitXSize = 38.0f; const float ConstScoreDigitYSize = 38.0f; const float COnstScoreDigitDistance = 24.0f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CScoreManager::CScoreManager( void ) { m_pScore = new CScore; m_pScoreValue = new C2DSpriteRHW; m_pResScoreValue = GAME_SCOREVALUE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResScoreValue ); m_pScoreDigit = new C2DSpriteRHW[SCORE_DIGIT_NUM]; m_pResScoreDigit = GAME_SCOREDIGIT_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResScoreDigit ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CScoreManager::~CScoreManager( void ) { SAFE_DELETE( m_pScore ); SAFE_DELETE( m_pScoreValue ); SAFE_DELETE_ALLAY( m_pScoreDigit ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CScoreManager::Init( void ) { m_pScore->Init(); m_pScoreValue->SetVertexPos( ConstScoreValueXPos, ConstScoreValueYPos, ConstScoreValueXSize, ConstScoreValueYSize ); // スコアの0000000 for( int i = 0; i < SCORE_DIGIT_NUM; ++ i ) { m_pScoreDigit[i].SetVertexPos( ConstScoreDigitXPos + ( COnstScoreDigitDistance * i ), ConstScoreDigitYPos, ConstScoreDigitXSize, ConstScoreDigitYSize ); m_pScoreDigit[i].SetUV( 10, 1, 1, 1 ); } return true; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CScoreManager::Run( void ) { int score = m_pScore->m_record; for( int i = SCORE_DIGIT_NUM - 1; i >= 0; -- i ) { int scoreDigit = score % 10; score = score / 10; m_pScoreDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CScoreManager::Uninit( void ) { return true; } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CScoreManager::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreValue )->Get(), m_pScoreValue->GetVertex() ); for( int i = 0; i < SCORE_DIGIT_NUM; ++ i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigit )->Get(), m_pScoreDigit[i].GetVertex() ); } } <file_sep>//---------------------------------------------------- // CScoreManager // ゲームのスコアのマネージャー // ( ゲーム中のスコアを管理するだけ ) // // @date 2014/2/4 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCORE_MANAGER_H_ #define _C_SCORE_MANAGER_H_ #include <Windows.h> #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteRHW.h" #include "../../ObjectSource/CScore.hpp" #define SCORE_DIGIT_NUM (7) class CScoreManager { private: CScore* m_pScore; // スコア集計用 // スコア表示用 C2DSpriteRHW* m_pScoreValue; // 文字 LPSTR m_pResScoreValue; C2DSpriteRHW* m_pScoreDigit; // 数字 LPSTR m_pResScoreDigit; public: // スコアの取得 CScore* GetScore ( void ) { return m_pScore; } public: CScoreManager ( void ); // コンストラクタ ~CScoreManager ( void ); // デストラクタ public: bool Init ( void ); bool Uninit ( void ); void Draw ( void ); void Run ( void ); public: void BrightChange ( bool isBright ) { if( isBright == true ) { m_pScoreValue->SetDiffuse( 255, 255, 255, 255 ); for( int i = 0; i < SCORE_DIGIT_NUM; ++ i ){ m_pScoreDigit[i].SetDiffuse( 255, 255, 255, 255 ); } } else { m_pScoreValue->SetDiffuse( 100, 100, 100, 255 ); for( int i = 0; i < SCORE_DIGIT_NUM; ++ i ){ m_pScoreDigit[i].SetDiffuse( 100, 100, 100, 255 ); } } } }; #endif _C_SCORE_MANAGER_H_<file_sep> #include "CTimeManager.h" const float ConstTimeValueXPos = 380.0f; const float ConstTimeValueYpos = 20.0f; const float ConstTimeValueXSize = 110.0f; const float ConstTimeValueYSize = 22.0f; const float ConstTimeDigitXPos = ConstTimeValueXPos - 40.0f; const float ConstTimeDigitYpos = ConstTimeValueYpos + 30.0f; const float ConstTimeDigitXSize = 38.0f; const float ConstTimeDigitYSize = 38.0f; const float ConstTimeDigitDistance = 24.0f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CTimeManager::CTimeManager( void ) { m_pResTimeFilePath = TIME_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTimeFilePath ); m_pTime = new C2DSpriteRHW; m_pResTimeDigitFilePath = TIMEDIGIT_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTimeDigitFilePath ); m_pTimeDigit = new C2DSpriteRHW[5]; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CTimeManager::~CTimeManager( void ) { SAFE_DELETE( m_pTime ); SAFE_DELETE_ALLAY( m_pTimeDigit ); } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CTimeManager::Draw() { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTimeFilePath )->Get(),m_pTime->GetVertex() ); for( int i = 0; i < 5; ++ i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTimeDigitFilePath )->Get(),m_pTimeDigit[i].GetVertex() ); } } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CTimeManager::Init( CONST UINT time ) { m_pTime->SetVertexPos( ConstTimeValueXPos, ConstTimeValueYpos, ConstTimeValueXSize, ConstTimeValueYSize ); // 00:00 for( int i = 0; i < 5; ++ i ) { m_pTimeDigit[i].SetVertexPos( ConstTimeDigitXPos + ( ConstTimeDigitDistance * i ), ConstTimeDigitYpos, ConstTimeDigitXSize, ConstTimeDigitYSize ); m_pTimeDigit[i].SetUV( 11,1,1,1 ); } m_pTimeDigit[2].SetUV( 11, 1, 11, 1 ); m_time = time * 60; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CTimeManager::Run( void ) { m_time --; int time = m_time / 60; // m_pTimeDigit[0].SetUV( 11, 1, ( ( time ) + 1 ), 1 ); // 10分 m_pTimeDigit[1].SetUV( 11,1,( ( time / 60 ) + 1 ), 1 ); // 1分 m_pTimeDigit[3].SetUV( 11,1,( time % 60 / 10 ) + 1 , 1 ); // 10秒 m_pTimeDigit[4].SetUV( 11,1,( time % 60 % 10 ) + 1, 1 ); // 1秒 } //---------------------------------------------------- // タイムアップ処理 //---------------------------------------------------- bool CTimeManager::TimeUP( void ) { if( m_time == 0 ) { return true; } return false; } <file_sep> #include "CPauseManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CPauseManager::CPauseManager( void ) { // ポーズ背景 m_pPauseBack = new C2DSpriteAlphaBlend; m_pResPauseBackFilePath = PAUSE_BACK_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPauseBackFilePath ); // ポーズ文字 m_pPause = new C2DSpriteAlphaBlend; m_pResPauseFilePath = PAUSE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPauseFilePath ); // リトライ文字 m_pRetry = new C2DSpriteAlphaBlend; m_pResRetryFilePath = RETRY_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResRetryFilePath ); // リジューム文字 m_pResume = new C2DSpriteAlphaBlend; m_pResResumeFilePath = RESUME_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResResumeFilePath ); // タイトル文字 m_pTitle = new C2DSpriteAlphaBlend; m_pResTitleFilePath = BACKTITLE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTitleFilePath ); // カーソル m_pCursol = new C2DSpriteRHW; m_pResCursolFilePath = CURSOL_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResCursolFilePath ); // 選択エフェクト m_pPauseEffect = new C2DSpriteAlphaBlend( eFadeState::FADE_IN ); m_pResPauseEffectFilePath = PAUSEEFFECT_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPauseEffectFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CPauseManager::~CPauseManager( void ) { SAFE_DELETE( m_pPauseBack ); // ポーズの背景 SAFE_DELETE( m_pPause ); // Pause SAFE_DELETE( m_pRetry ); // Retry SAFE_DELETE( m_pResume ); // Resume SAFE_DELETE( m_pTitle ); // Title SAFE_DELETE( m_pCursol ); // カーソル SAFE_DELETE( m_pPauseEffect ); // エフェクト } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CPauseManager::Init( void ) { m_isPause = false; m_ePauseState = ePauseStatus::RESUME; m_pPauseBack->SetVertexPos( 400.0f, 300.0f, 400.0f, 240.0f ); m_pPause->SetVertexPos( 400.0f,160.0f,250.0f,80.0f ); m_pResume->SetVertexPos( 400.0f,250.0f,180.0f,40.0f ); m_pRetry->SetVertexPos( 400.0f,300.0f,180.0f,40.0f ); m_pTitle->SetVertexPos( 400.0f,350.0f,180.0f,40.0f ); m_pPauseEffect->SetVertexPos( 400.0f,250.0f,190.0f,40.0f ); m_pCursol->SetVertexPos( 270.0f, 250.0f, 48.0f, 48.0f ); } //---------------------------------------------------- // ポーズに入るたびに初期化 //---------------------------------------------------- void CPauseManager::InitPause( void ) { m_ePauseState = ePauseStatus::RESUME; m_pPauseEffect->SetVertexPos( 400.0f,250.0f,190.0f,40.0f ); m_pCursol->SetVertexPos( 270.0f, 250.0f, 48.0f, 48.0f ); } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CPauseManager::Uninit( void ) { } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CPauseManager::Run() { m_pPauseEffect->Fade( 255, 70, 5 ); switch( m_ePauseState ) { case RESUME: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_UP )) { m_ePauseState = TITLE; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pTitle->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pTitle->GetCenter()->y ); } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_DOWN )) { m_ePauseState = RETRY; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pRetry->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pRetry->GetCenter()->y ); } break; case RETRY: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_UP )) { m_ePauseState = RESUME; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pResume->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pResume->GetCenter()->y ); } else if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_DOWN )) { m_ePauseState = TITLE; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pTitle->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pTitle->GetCenter()->y ); } break; case TITLE: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_UP )) { m_ePauseState = RETRY; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pRetry->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pRetry->GetCenter()->y ); } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_DOWN )) { m_ePauseState = RESUME; m_pCursol->SetVertexPos( m_pCursol->GetCenter()->x,m_pResume->GetCenter()->y ); m_pPauseEffect->SetVertexPos( m_pPauseEffect->GetCenter()->x,m_pResume->GetCenter()->y ); } break; default: break; } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CPauseManager::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResPauseBackFilePath )->Get(), m_pPauseBack->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResPauseFilePath )->Get(),m_pPause->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResResumeFilePath )->Get(),m_pResume->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResRetryFilePath )->Get(),m_pRetry->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTitleFilePath )->Get(),m_pTitle->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResCursolFilePath )->Get(),m_pCursol->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResPauseEffectFilePath )->Get(),m_pPauseEffect->GetVertex() ); } <file_sep>//---------------------------------------------------- // CTimeManager Header // タイムの管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_TIME_MANAGER_H_ #define _C_TIME_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteRHW.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" class CTimeManager { private: LPSTR m_pResTimeFilePath; C2DSpriteRHW *m_pTime; LPSTR m_pResTimeDigitFilePath; C2DSpriteRHW *m_pTimeDigit; private: int m_time; public: // 時間のアドレス取得 int* GetTime ( void ) { return &m_time; } public: CTimeManager ( void ); ~CTimeManager ( void ); public: void Draw ( void ); void Init ( CONST UINT time ); void Run ( void ); bool TimeUP ( void ); public: void BrightChange ( bool isBright ) { if( isBright == true ) { m_pTime->SetDiffuse( 255, 255, 255, 255 ); for( int i = 0; i < 5; ++ i ){ m_pTimeDigit[i].SetDiffuse( 255, 255, 255, 255 ); } } else { m_pTime->SetDiffuse( 100, 100, 100, 255 ); for( int i = 0; i < 5; ++ i ){ m_pTimeDigit[i].SetDiffuse( 100, 100, 100, 255 ); } } } }; #endif _C_TIME_MANAGER_H_<file_sep>//---------------------------------------------------- // CDiceRandSystem // サイコロの乱数のシステム // // @date 2013/11/28 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DICE_RANDSYSTEM_H_ #define _C_DICE_RANDSYSTEM_H_ #include <Windows.h> #include <time.h> #include "../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CXorShift.hpp" #define RNDALLAY_NUM ( 100 ) //---------------------------------------------------- // 乱数用の配列 //---------------------------------------------------- // 上面の乱数 const UINT upperFaceRndAllay[ RNDALLAY_NUM ] = {1,2,1,5,2,5,1,5,5,4,4,2,1,6,4,1,3,5,2,4,2,4,3,5,6,1,1,3,1,1,4,2,4,6,4,4,2,5,5,3,4, 6,3,5,3,5,4,5,2,3,5,6,2,6,2,5,6,2,6,1,4,3,5,1,3,3,2,2,6,5,6,6,6,5,3,5,5,1,6,6,4,5, 4,4,1,5,4,3,6,2,4,3,4,5,1,4,6,6,2,3}; // 横面の回転用の乱数 const UINT aroundFaceRndAllay[ RNDALLAY_NUM ] = {1,2,1,2,1,1,1,3,2,0,1,2,3,1,2,3,2,0,2,0,0,0,3,0,2,1,0,0,2,0,2,0,1,0,2,1,0,1,1,2,3, 0,3,0,0,3,3,1,0,1,0,2,2,0,0,1,2,0,2,3,3,3,2,3,3,1,2,2,2,2,2,3,1,1,2,0,1,2,3,2,2,3, 0,1,1,2,1,0,1,2,3,3,0,2,0,1,0,0,1,0}; class CDiceRandSystem { private: CDiceRandSystem(){} public: // デストラクタ ~CDiceRandSystem(){} // シングルトン定義 static CDiceRandSystem* GetInstance( void ) { static CDiceRandSystem rndSystem; return &rndSystem; } public: //---------------------------------------------------- // @name InitSeed // @content Seedの初期化 // @param none // @return bool 成功か失敗 // @date 2013/11/29 //---------------------------------------------------- bool InitSeed ( void ) { CXorShift::GetInstance()->InitSeed(time(NULL)); return true; } private: //---------------------------------------------------- // @name GetAllayRnd // @content 配列の添え字用の乱数を取得 // @param maxNum 取得したい乱数の最大値 // @return UINT 0〜maxNumの範囲の乱数 // @date 2013/11/28 //---------------------------------------------------- UINT GetAllayRnd ( CONST UINT maxNum ) { // 0〜RNDALLAY_NUM範囲の乱数取得 return UINT(CXorShift::GetInstance()->GetRandom(0,maxNum - 1)); } public: //---------------------------------------------------- // @name GetUpperFace // @content 上面の面の番号の乱数取得 // @param none // @return UINT 上面の面の目の乱数(1〜6) // @date 2013/11/28 //---------------------------------------------------- CONST UINT GetUpperFace ( void ) { unsigned int rnd = this->GetAllayRnd( RNDALLAY_NUM ); return upperFaceRndAllay[ rnd ]; } //---------------------------------------------------- // @name GetAroundFace // @content 横面の回転乱数を取得 // @param rnd 乱数(範囲0〜RNDALLAY_NUM) // @return UINT 横面の回転乱数数(1〜3) // @date 2013/11/28 //---------------------------------------------------- CONST UINT GetAroundFace ( void ) { unsigned int rnd = this->GetAllayRnd( RNDALLAY_NUM ); return aroundFaceRndAllay[ rnd ]; } //---------------------------------------------------- // @name GetPos // @content ランダムでポジションの配列の番号取得(配列情報の最大値) // @param maxAllay 配列情報の添え字の最大値 // @return UINT 乱数添え字番号 // @date 2013/12/2 //---------------------------------------------------- CONST UINT GetPos ( CONST UINT maxAllay ) { unsigned int rnd = this->GetAllayRnd( maxAllay ); return rnd; } }; #endif _C_DICE_RANDSYSTEM_H_<file_sep>//---------------------------------------------------- // CTitleBackManager Header // タイトルの背景処理の管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_TITLE_BACK_MANAGER_H_ #define _C_TITLE_BACK_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/CObjectBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" class CTitleBackManager { private: C2DSpriteAlphaBlend* m_pAlphaBlend; C2DSpriteAlphaBlend* m_pTitleBack; LPSTR m_pResTitleBackFilePath; C2DSpriteAlphaBlend* m_pPushStartPlay; LPSTR m_pResPushStartPlayFilePath; C2DSpriteAlphaBlend* m_pTitleLogo; LPSTR m_pResTitleLogoFilePath; C2DSpriteAlphaBlend* m_pTitleRemake; LPSTR m_pResTitleRemakeFilePath; private: bool m_isFade; // フェードのフラグ public: CTitleBackManager ( void ); ~CTitleBackManager ( void ); public: void Run ( void ); void Draw ( void ); void Init ( void ); void Uninit ( void ); //---------------------------------------------------- // Titleのフェード //---------------------------------------------------- bool Fade ( void ); //---------------------------------------------------- // Fadeフラグのセット // @data isFade // return none //---------------------------------------------------- void SetIsFade ( bool isFade ) { m_isFade = isFade; } //---------------------------------------------------- // Fadeフラグのゲット // @data none // @return isFade //---------------------------------------------------- bool GetIsFade ( void ) { return m_isFade; } }; #endif _C_TITLE_BACK_MANAGER_H_<file_sep>//---------------------------------------------------- // CJoystick // JoyStick実装 // // @date 2013/12/8 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_JOYSTICK_H_ #define _C_JOYSTICK_H_ #include <Windows.h> #include <XInput.h> #pragma comment(lib,"xinput.lib") #pragma comment(lib,"Xinput9_1_0.lib") #define INPUT_DEADZONE ( 0.24f * FLOAT(0x7FFF) ) #define MAX_JOYSTICK ( 4 ) /* #define XINPUT_GAMEPAD_DPAD_UP 0x0001 // 十字キー上 #define XINPUT_GAMEPAD_DPAD_DOWN 0x0002 // 十字キー下 #define XINPUT_GAMEPAD_DPAD_LEFT 0x0004 // 十字キー左 #define XINPUT_GAMEPAD_DPAD_RIGHT 0x0008 // 十字キー右 #define XINPUT_GAMEPAD_START 0x0010 // スタートボタン #define XINPUT_GAMEPAD_BACK 0x0020 // 戻るボタン #define XINPUT_GAMEPAD_LEFT_THUMB 0x0040 // L3ボタン(左スティック押し込み) #define XINPUT_GAMEPAD_RIGHT_THUMB 0x0080 // R3ボタン(右スティック押し込み) #define XINPUT_GAMEPAD_LEFT_SHOULDER 0x0100 // L1ボタン #define XINPUT_GAMEPAD_RIGHT_SHOULDER 0x0200 // R1ボタン #define XINPUT_GAMEPAD_A 0x1000 // Aボタン #define XINPUT_GAMEPAD_B 0x2000 // Bボタン #define XINPUT_GAMEPAD_X 0x4000 // Xボタン #define XINPUT_GAMEPAD_Y 0x8000 // Yボタン */ typedef struct tagTXINPUTJOYSTICK { UINT id; // ジョイスティックの番号 XINPUT_STATE inputState; // 入力状態 XINPUT_VIBRATION vibration; // 振動状態 WORD triggerState; // トリガー状態 WORD releaseState; // リリース状態 }TXINPUTJOYSTICK; class CJoyStick { private: CJoyStick ( void ) { ::ZeroMemory( &m_joyStick,sizeof( m_joyStick ) ); } CJoyStick ( CONST CJoyStick& joyStick ){} CJoyStick& operator= ( CONST CJoyStick& joyStick ){} private: TXINPUTJOYSTICK m_joyStick[ MAX_JOYSTICK ]; public: // インスタンス取得場所 static CJoyStick* GetInstance() { static CJoyStick joyStick; return &joyStick; } //---------------------------------------------------- // @name Update // @content ジョイスティックの更新 // @param none // @return none // @date 2013/12/8 //---------------------------------------------------- void Update ( void ) { DWORD dwResult; for( DWORD i = 0; i < MAX_JOYSTICK; ++ i ) { // バイブレーション初期化 this->UpdateVibration( i ); // キー情報初期化 WORD logInputState = m_joyStick[i].inputState.Gamepad.wButtons; // WORD logAxisState = m_joyStick[i].m_pressAxis; // BYTE logTriggerState = m_joyStick[i].m_triggerPress; ::ZeroMemory( &m_joyStick[i].inputState, sizeof(XINPUT_STATE) ); // Simply get the state of the controller from XInput. dwResult = XInputGetState( i, &m_joyStick[i].inputState ); if( dwResult == ERROR_SUCCESS ) { // Controller is connected if( -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE < m_joyStick[i].inputState.Gamepad.sThumbLX && -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE < m_joyStick[i].inputState.Gamepad.sThumbLY && m_joyStick[i].inputState.Gamepad.sThumbLX < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE && m_joyStick[i].inputState.Gamepad.sThumbLY < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ) { m_joyStick[i].inputState.Gamepad.sThumbLX = 0; m_joyStick[i].inputState.Gamepad.sThumbLY = 0; } if( -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE < m_joyStick[i].inputState.Gamepad.sThumbRX && -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE < m_joyStick[i].inputState.Gamepad.sThumbRY && m_joyStick[i].inputState.Gamepad.sThumbRX < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE && m_joyStick[i].inputState.Gamepad.sThumbRY < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ) { m_joyStick[i].inputState.Gamepad.sThumbRX = 0; m_joyStick[i].inputState.Gamepad.sThumbRY = 0; } // ボタンのトリガー検出 m_joyStick[i].triggerState = (m_joyStick[i].inputState.Gamepad.wButtons ^ logInputState) & m_joyStick[i].inputState.Gamepad.wButtons; // ボタンのリリース検出 m_joyStick[i].releaseState = (m_joyStick[i].inputState.Gamepad.wButtons ^ logInputState) & logInputState; } } } //---------------------------------------------------- // @name UpdateVibration // @content バイブレーションの更新 // @param joyStickID ジョイスティックID // @return none // @date 2013/12/8 //---------------------------------------------------- void UpdateVibration ( CONST UINT joyStickID ) { XInputSetState( joyStickID, &m_joyStick[ joyStickID ].vibration ); m_joyStick[ joyStickID ].vibration.wLeftMotorSpeed = 0; m_joyStick[ joyStickID ].vibration.wRightMotorSpeed = 0; } //---------------------------------------------------- // @name GetPressButton // @content 指定したボタンのプレスキー状態取得 // @param joyStickID ジョイスティックID // @param buttonID ボタンID // @return DWORD 押したボタン番号のプレス状態 // @date 2013/12/8 //---------------------------------------------------- DWORD GetPressButton ( CONST UINT joyStickID, DWORD buttonID ) { return ( m_joyStick[ joyStickID ].inputState.Gamepad.wButtons ) &buttonID; } //---------------------------------------------------- // @name GetTriggerButton // @content 指定したボタンのトリガーキー状態取得 // @param joyStickID ジョイスティックID // @param buttonID ボタンID // @return DWORD 押したボタン番号のトリガー状態 // @date 2013/12/8 //---------------------------------------------------- DWORD GetTriggerButton ( CONST UINT joyStickID, DWORD buttonID ) { return ( m_joyStick[ joyStickID ].triggerState ) &buttonID; } //---------------------------------------------------- // @name GetReleaseButton // @content 指定したボタンのリリースキー状態取得 // @param joyStickID ジョイスティックID // @param buttonID ボタンID // @return DWORD 押したボタン番号のリリース状態 // @date 2013/12/8 //---------------------------------------------------- DWORD GetReleaseButton ( CONST UINT joyStickID, DWORD buttonID ) { return ( m_joyStick[ joyStickID ].releaseState ) & buttonID; } //---------------------------------------------------- // @name Vibration // @content バイブレーション // @param joyStickID ジョイスティックID // @param leftVibRate 左振動の値(0〜65535) // @param rigthVibRate 右振動の値(0〜65535) // @none // @date 2013/12/8 //---------------------------------------------------- void Vibration ( CONST UINT joyStickID, USHORT leftVibRate, USHORT rightVibRate ) { // オーバーフローの禁止 leftVibRate &= 0xFFFF; rightVibRate &= 0xFFFF; m_joyStick[ joyStickID ].vibration.wLeftMotorSpeed = min( 65535, leftVibRate + m_joyStick[ joyStickID ].vibration.wLeftMotorSpeed ); m_joyStick[ joyStickID ].vibration.wRightMotorSpeed = min( 65535, rightVibRate + m_joyStick[ joyStickID ].vibration.wRightMotorSpeed ); } }; #endif _C_JOYSTICK_H_ <file_sep>//---------------------------------------------------- // CSceneResult Header // リザルトシーン // // @date 2014/2/14 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_RESULT_H_ #define _C_SCENE_RESULT_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../UserSource/CUserManager.h" class CSceneResult : public CSceneBase { private: // Result文字 C2DSpriteRHW *m_pResultValue; LPSTR m_pResResultValueFilePath; // スコア数字 LPSTR m_pResScoreDigitFilePath; // Score C2DSpriteRHW *m_pScoreValue; LPSTR m_pResScoreValueFilePath; C2DSpriteRHW *m_pScoreDigit; // MaxChain C2DSpriteRHW *m_pMaxChainValue; LPSTR m_pResMaxChainValueFilePath; C2DSpriteRHW *m_pMaxChainDigit; // 1〜6用 C2DSpriteRHW *m_pOnePip; LPSTR m_pResOneTextureFilePath; C2DSpriteRHW *m_pOnePipDigit; C2DSpriteRHW *m_pTwoPip; LPSTR m_pResTwoTextureFilePath; C2DSpriteRHW *m_pTwoPipDigit; C2DSpriteRHW *m_pThreePip; LPSTR m_pResThreeTextureFilePath; C2DSpriteRHW *m_pThreePipDigit; C2DSpriteRHW *m_pFourPip; LPSTR m_pResFourTextureFilePath; C2DSpriteRHW *m_pFourPipDigit; C2DSpriteRHW *m_pFivePip; LPSTR m_pResFiveTextureFilePath; C2DSpriteRHW *m_pFivePipDigit; C2DSpriteRHW *m_pSixPip; LPSTR m_pResSixTextureFilePath; C2DSpriteRHW *m_pSixPipDigit; C2DSpriteRHW *m_pPushEnter; LPSTR m_pResPushEnterFilePath; // αブレンドを実装するためのもの C2DSpriteAlphaBlend *m_pBack; bool m_isFade; int m_scoreDigitNum; int m_maxChainDigitNum; int m_oneDigitNum; int m_twoDigitNum; int m_threeDigitNum; int m_fourDigitNum; int m_fiveDigitNum; int m_sixDigitNum; public: CSceneResult ( CSceneChange* change ); CSceneResult ( void ); ~CSceneResult ( void ); public: void Initialize ( void ) override; // 初期化処理 void Finalize ( void ) override; // 終了処理 void Run ( void ) override; // 更新処理 void Draw ( void ) override; // 描画処理 bool Load ( void ) override; // ロード処理 }; #endif _C_SCENE_RESULT_H_<file_sep>********************************************* 自分用に作ったFramWorkです ********************************************* CWindowsSystem.cpp,h ウィンドウの作成やウィンドウのクラスの生成用クラス実装 timeBeginの部分とPeekMessegeの部分更新 デストラクタにてtimeEnd追加。 2013/5/8  メッセージの受け取り方をGetMessage関数とPeekMessage関数の二つにわけた。 CDirectBase.cpp,h DirectXのための初期化などを定めたクラス CDirectGraphics3D.cpp,h 3D描画のためのクラスと処理を定めたクラス CDirectGraphics2D.cpp,h 2D描画のためのクラスと処理を定めたクラス CDirectGraphicsSystem.cpp,h 2D,3Dともに描画に必要な処理を定めたクラス CDirectResource.cpp,h 2D,3D描画に必要なテクスチャの処理を定めたクラス CDirectInput.cpp,h 入力系機器の情報用クラス実装 ウィンドウハンドルをシングルトンで制御したため必要な部分でGetしている GameInfo.h ゲームの定数などをまとめるヘッダー CConsole.h コンソールを作成・文字表示を行うためのクラス CFps.h FPSを計測・表示・調整するためのクラス CDirectMeshClone.cpp,h クローンメッシュ用のクラス<file_sep> #include "CSnowObj.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSnowObj::CSnowObj() { m_rand = new CRandSystem(); m_snow = new C2DParticle[100](); for( int i = 0; i < 100; ++ i ) { m_snow[i].SetSprite( &D3DXVECTOR3( 10.0f, 0.0f, 0.0f ), &D3DXVECTOR3( 3.0f, 3.0f, 0.0f ) ); } m_pResSnowFilePath = PARTICLE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResSnowFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSnowObj::~CSnowObj() { SAFE_DELETE_ALLAY( m_snow ); SAFE_DELETE( m_rand ); } //---------------------------------------------------- // エミッター //---------------------------------------------------- void CSnowObj::Emitter ( void ) { if( m_rand->GetRand( 4 ) <= 2 ) { D3DXVECTOR3 speed = D3DXVECTOR3( 0.0f,0.5f, 0.0f ); D3DXVECTOR3 dir = D3DXVECTOR3( 0.0f,-0.5f,0.0f ); for( int i = 0; i < 100; i ++ ){ if( m_snow[i].GetLife() <= 0 ) { m_snow[i].SetSpritePos( 0.0f, 4.0f, 0.0f); m_snow[i].SetParticle ( &D3DXVECTOR3( 0.0f, 0.5f, 0.0f ), &D3DXVECTOR3( 0.0f, -0.5f, 0.0f ) , 2000 ); break; } } } } //---------------------------------------------------- // 移動 //---------------------------------------------------- void CSnowObj::Move ( void ) { for( int i = 0; i < 100; ++ i ) { if( m_snow[i].GetLife() > 0 ) { m_snow[i].Move(); // ライフを減らす /* m_snow[i].LifeDown( m_rand->GetRand( 1,5 )); m_snow[i].SetAlfa( m_snow[i].GetAlfa() - 1 ); if( m_snow[i].GetAlfa() <= 0 ) { m_snow[i].SetLife( 0 ); } } */ } } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSnowObj::Draw( CDirectCamera* directCamera ) { for( int i = 0; i < 100; ++ i ) { if( m_snow[i].GetLife() > 0 ) { m_snow[i].CalcWorldMtx( directCamera->GetView() ); CDirectDrawSystem::GetInstance()->DrawSprite( CResourceManager::GetInstance()->GetTexture( m_pResSnowFilePath )->Get(), m_snow[i].GetVertex(),m_snow[i].GetWorldMtx() ); } } }<file_sep> #include "../../KaiFrameWorkHeader/ResourceHeader/CResourceXFile.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CResourceXFile::CResourceXFile( void ) { m_pMeshMaterials = nullptr; m_pMeshTexture = nullptr; m_pMesh = nullptr; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CResourceXFile::~CResourceXFile( void ) { SAFE_DELETE_FREE( m_pMeshMaterials ); // マテリアルの解放 if( m_pMeshTexture != nullptr ) { // テクスチャの解放 for( int i = 0; ( m_pMeshTexture[i] )&&( ( unsigned ) i < m_materialsCount ); i ++ ){ m_pMeshTexture[i]->Release(); m_pMeshTexture[i] = nullptr; } } SAFE_DELETE_FREE( m_pMeshTexture ); // テクスチャのクリア SAFE_DELETE_RELESE( m_pMesh ); // メッシュの解放 } //---------------------------------------------------- // Xファイルのロード //---------------------------------------------------- HRESULT CResourceXFile::Load( CONST LPSTR filePath ) { // 3Dデバイスのポインタをシングルトンで取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); DEBUG::PrintfColor( DEBUG::H_CYAN, "%s\n",filePath ); // Xファイル読み込み if( FAILED(D3DXLoadMeshFromX (filePath, D3DXMESH_MANAGED, pd3dDevice, NULL, &m_pMaterialsBuffer, NULL, &m_materialsCount, &m_pMesh))) { // 読み込み失敗 DEBUG::PrintfColor( DEBUG::H_RED, " Load XFile Failed... \n\n" ); return E_FAIL; } // マテリアルをセット this->SetMaterials(); DEBUG::PrintfColor( DEBUG::H_GREEN, "Load XFile Successfully\n" ); return S_OK; } //---------------------------------------------------- // マテリアルのセット //---------------------------------------------------- HRESULT CResourceXFile::SetMaterials( void ) { // 3Dデバイスのポインタをシングルトンで取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); D3DXMATERIAL *pMaterials = (D3DXMATERIAL *)m_pMaterialsBuffer->GetBufferPointer(); // マテリアルの総数だけ、マテリアルとテクスチャの配列を動的に確保 m_pMeshMaterials = (D3DMATERIAL9*)malloc(sizeof(D3DMATERIAL9)*m_materialsCount); m_pMeshTexture = (LPDIRECT3DTEXTURE9*)malloc(sizeof(LPDIRECT3DTEXTURE9)*m_materialsCount); // マテリアルをセットしていく for( int i = 0;( unsigned )i < m_materialsCount;i ++ ){ m_pMeshMaterials[ i ] = pMaterials[ i ].MatD3D; m_pMeshMaterials[ i ].Ambient = m_pMeshMaterials[ i ].Diffuse; // テクスチャ描画 if( pMaterials[i].pTextureFilename != "" && pMaterials[i].pTextureFilename != NULL ) { // テクスチャ読み込み if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, pMaterials[ i ].pTextureFilename, &m_pMeshTexture[ i ] ) ) ) { m_pMeshTexture[ i ] = NULL; DEBUG::PrintfColor(DEBUG::H_RED, "Load XFile To Texture Failed...\n" ); return E_FAIL; } } else { m_pMeshTexture[ i ] = NULL; } } DEBUG::PrintfColor( DEBUG::H_GREEN, "Load XFile To Texture Successfuly\n" ); return S_OK; } <file_sep>//---------------------------------------------------- // CSceneModeSelect // モードセレクト画面 // // @date 2014/2/4 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_MODESELECT_ #define _C_SCENE_MODESELECT_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Light.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/CObjectBase.hpp" #include "../../ManagerSource/ModeSelect/CModeSelectBackManager.h" #include "../../ManagerSource/ModeSelect/CModeSelectPlayerManager.h" //---------------------------------------------------- // モードセレクト用のステータス //---------------------------------------------------- typedef enum { eModeTitle, eModeGamePlay, eModeOption, eModeExit, eModeRanking, eModeRecord, }eModeSelectState; const eModeSelectState modeAllay[6] ={ eModeSelectState::eModeTitle, eModeSelectState::eModeGamePlay, eModeSelectState::eModeOption, eModeSelectState::eModeExit, eModeSelectState::eModeRanking, eModeSelectState::eModeRecord }; class CSceneModeSelect : public CSceneBase { private: CDirectCamera* m_pDirectCamera; CDirectLight* m_pDirectLight; CModeSelectBackManager* m_pModeSelectBackManager; CModeSelectPlayerManager* m_pModeSelectPlayerManager; eModeSelectState m_eMode; // モード int m_modeIndexNo; // モードの添え字番号 bool m_isFade; // フェードフラグ public: CSceneModeSelect ( void ); CSceneModeSelect ( CSceneChange* change ); ~CSceneModeSelect ( void ); public: void Initialize ( void ) override; void Finalize ( void ) override; void Run ( void ) override; void Draw ( void ) override; bool Load ( void ) override; }; #endif _C_SCENE_MODESELECT_<file_sep>//---------------------------------------------------- // C3DObjectAlphaBlend // αブレンドする必要があるObject // // @date 2013/12/4 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_3D_OBJECT_ALPHABLEND_H_ #define _C_3D_OBJECT_ALPHABLEND_H_ #include <d3dx9.h> #include "../CObjectBase.hpp" class C3DObjectAlphaBlend : public CObjectBase { private: D3DXCOLOR m_color; // 色情報 public: // コンストラクタ C3DObjectAlphaBlend ( void ); // デストラクタ virtual ~C3DObjectAlphaBlend ( void ); //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ); //---------------------------------------------------- // @name SetColor // @content 色の設定 // @param r 赤値( 0 ~ 255 ) // @param g 緑値( 0 ~ 255 ) // @param b 青値( 0 ~ 255 ) // @return none // @date 2013/12/17 //---------------------------------------------------- void SetColor ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // @name GetColor // @content 色の取得 // @param none // @return D3DXCOLOR* 色情報 // @date 2013/12/4 //---------------------------------------------------- D3DXCOLOR* GetColor ( void ); }; #endif _C_3D_OBJECT_ALPHABLEND_H_<file_sep>//---------------------------------------------------- // CModelViewStage // モデルビューのステージ管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MODELVIEW_STAGE_MANAGER_H_ #define _C_MODELVIEW_STAGE_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DebugHeader/CDebugStage.h" class CModelViewStage { private: CDebugStage *m_pStage; public: CModelViewStage ( void ); ~CModelViewStage ( void ); public: void Init ( void ); void Uninit ( void ); void Draw ( void ); }; #endif _C_MODELVIEW_STAGE_MANAGER_H_<file_sep>//---------------------------------------------------- // CSpaceParticle Header // 空間パーティクル // // @date 2013/8/26 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SPACE_PARTICLE_H_ #define _C_SPACE_PARTICLE_H_ #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/BillBoard/CParticle.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CRandSystem.hpp" #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" class CSpaceParticle { private: CRandSystem *m_pRand; // 乱数 CParticle *m_pSpaceParticle; // パーティクルの粒子 LPSTR m_pSpacePatricleFilePath; // ファイルパス int m_spaceCnt; bool m_isSpaceParticle; public: CSpaceParticle ( void ); ~CSpaceParticle ( void ); public: void Emitter ( void ); void Move ( void ); void Draw ( CDirectCamera* directCamera ); }; #endif _C_SPACE_PARTICLE_H_<file_sep>//---------------------------------------------------- // CResourceManager // リソースを管理・保持するクラス // // @date 2013/12/5 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_RESOURCE_MANAGER_H_ #define _C_RESOURCE_MANAGER_H_ #include <d3dx9.h> #include <map> #include <string> #include "CResourceXFile.h" #include "CResourceTexture.h" #include "CResourceXFont.h" #include "CResourcePath.hpp" using namespace std; class CResourceManager { private: CResourceManager() { } CResourceManager( CONST CResourceManager& obj ){} CResourceManager& operator=( CONST CResourceManager& obj ){} public: //インスタンスの取得(シングルトン) static CResourceManager* GetInstance() { static CResourceManager resourceManager; return &resourceManager; } private: map< LPSTR , CResourceTexture* > m_texturerResource; map< LPSTR , CResourceXFile* > m_xFileResource; map< UINT , CResourceXFont* > m_xFontResource; public: // デストラクタ ~CResourceManager ( void ); public: //---------------------------------------------------- // @name LoadXFile // @content XFileをロードしてMapにセットする // @param resourcePath リソースのパス // @return bool 成功か失敗 // @date 2013/12/5 //---------------------------------------------------- bool LoadXFile ( CONST LPSTR resourcePath ); //---------------------------------------------------- // @name GetXFile // @content MapからXFileの取得 // @param resourcePath XFileのパス // @return CResourceXFile* XFileのアドレス // @date 2013/12/5 //---------------------------------------------------- CResourceXFile* GetXFile ( CONST LPSTR resourcePath ); //---------------------------------------------------- // @name LoadTexture // @content TextureをロードしてMapにセットする // @param resourcePath Textureのパス // @return bool 成功か失敗 // @date 2013/12/5 //---------------------------------------------------- bool LoadTexture ( CONST LPSTR resourcePath ); //---------------------------------------------------- // @name GetTexture // @content Mapからテクスチャの取得 // @param resourcePath Textureのパス // @return CResourceTexture* Textureのアドレス // @date 2013/12/5 //---------------------------------------------------- CResourceTexture* GetTexture ( CONST LPSTR resourcePath ); //---------------------------------------------------- // @name CreateFont // @content XFontを作成してMapにセットする // @param xFontNo どのXFontかを識別する番号 // @param width 横幅 // @param height 縦幅 // @return bool 成功か失敗 // @date 2013/12/16 //---------------------------------------------------- bool CreateXFont ( CONST UINT xFontNo, CONST UINT width, CONST UINT height ); //---------------------------------------------------- // @name GetXFont // @content XFontのインスタンスの取得 // @param xFontNo Mapに格納しているxFontの番号 // @return CResourceXFont* XFontのインスタンス // @date 2013/12/6 // @update 2013/12/16 引数にNoを追加 //---------------------------------------------------- CResourceXFont* GetXFont ( CONST UINT xFontNo ); //---------------------------------------------------- // @name Relese // @content Mapの情報を全てリリース // @param none // @return none // @date 2013/12/5 //---------------------------------------------------- void Relese ( void ); //---------------------------------------------------- // @name Relese // @content Mapの情報をファイルパスで指定解放 // @param resourcePath ファイルのパス // @return none // @date 2013/12/5 //---------------------------------------------------- void Relese ( CONST LPSTR resourcePath ); }; #endif _C_RESOURCE_MANAGER_H_<file_sep>/*データベース作成*/ CREATE DATABASE XI_RemakeDB; /*データベース選択*/ use XI_RemakeDB; /*ユーザテーブル作成*/ create table User( userID VARCHAR(10) UNIQUE KEY, name VARCHAR(10) NOT NULL, id VARCHAR(10) NOT NULL, pass VARCHAR(10) NOT NULL, PRIMARY KEY(userID,name) ); /*scoreテーブル作成*/ create table Score( scoreID VARCHAR(10), record INT(10), onePip INT(3), twoPip INT(3), threePip INT(3), fourPip INT(3), fivePip INT(3), sixPip INT(3), maxChain INT(3), userID VARCHAR(10) NOT NULL, userName VARCHAR(10) NOT NULL, PRIMARY KEY(scoreID), FOREIGN KEY(userID,userName) REFERENCES user(userID,name) ON DELETE CASCADE ); /*Scoreテーブル用Insert*/ INSERT INTO User Values('U000000','test','test','test'); INSERT INTO score values('S000000',0,0,0,0,0,0,0,0,'U000000','test'); /*Userが作成された時に自動的にスコアを0クリアしてスコアテーブルを作成するトリガ*/ drop trigger insertusertri; DELIMITER // CREATE TRIGGER insertusertri AFTER INSERT ON user FOR EACH ROW BEGIN /*現在のスコアテーブルの最大Noを取得するための変数*/ DECLARE triMaxScoreId VARCHAR(10); DECLARE triMaxScoreWork VARCHAR(1); /*スコアIDを取得するための変数*/ DECLARE triScoreId VARCHAR(8); /*一番左の文字を取得*/ SELECT SubStr(Max(scoreID), 1, 1) INTO triMaxScoreWork FROM score; /*その他の数字の部分を抜出し数値に変換後,左を0埋めして保存している文字を左につける*/ SELECT CONCAT(triMaxScoreWork, LPAD( SUBSTR(MAX(scoreID),2,7) + 1, 6 ,'0' ) ) INTO triMaxScoreId FROM score; /*スコアテーブルに追加する*/ INSERT INTO score values(triMaxScoreId,0,0,0,0,0,0,0,0,New.userID,New.name); END; // DELIMITER ; /*テストデータ用*/ INSERT INTO User Values('U000001','test','test','test'); INSERT INTO User Values('U000002','punpuku','1234abcd','abcd1234'); <file_sep> #include "CTitleSoundManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CTitleSoundManager::CTitleSoundManager( void ) { m_pSound = new CXAudio2(); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CTitleSoundManager::~CTitleSoundManager( void ) { if( m_pSound != NULL ) { delete m_pSound; m_pSound = NULL; } } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CTitleSoundManager::Init( void ) { m_pSound->Init(); m_pSound->LoadWav( TITLE_BGM,"resource/sound/title.wav"); m_pSound->LoadWav( TITLE_BUTTON,"resource/sound/titleButton.wav"); } //---------------------------------------------------- // 音再生 //---------------------------------------------------- void CTitleSoundManager::Play( const int soundNo,bool isLoop ) { m_pSound->Run( soundNo,1.0f,isLoop ); } //---------------------------------------------------- // 音停止 //---------------------------------------------------- void CTitleSoundManager::Stop( const int soundNo ) { m_pSound->Stop( soundNo ); } <file_sep>//---------------------------------------------------- // CPauseManager Header // ポーズの管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_PAUSE_MANAGER_H_ #define _C_PAUSE_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" typedef enum PAUSE_STATUS { RESUME, RETRY, TITLE, GAMEOVER }ePauseStatus; class CPauseManager { private: C2DSpriteAlphaBlend *m_pPauseBack; LPSTR m_pResPauseBackFilePath; C2DSpriteAlphaBlend *m_pPause; LPSTR m_pResPauseFilePath; C2DSpriteAlphaBlend *m_pRetry; LPSTR m_pResRetryFilePath; C2DSpriteAlphaBlend *m_pResume; LPSTR m_pResResumeFilePath; C2DSpriteAlphaBlend *m_pTitle; LPSTR m_pResTitleFilePath; C2DSpriteRHW *m_pCursol; LPSTR m_pResCursolFilePath; C2DSpriteAlphaBlend *m_pPauseEffect; LPSTR m_pResPauseEffectFilePath; private: bool m_isPause; // ポーズのフラグ ePauseStatus m_ePauseState; // ポーズのステータス public: CPauseManager ( void ); // コンストラクタ ~CPauseManager ( void ); // デストラクタ public: void Draw ( void ); void Run ( void ); void Init ( void ); void InitPause ( void ); void Uninit ( void ); public: //---------------------------------------------------- // @name GetIsPause // @content ポーズのフラグ // @param none // @return bool ポーズ中かどうか // @date 2014/2/12 //---------------------------------------------------- bool GetIsPause ( void ) { return m_isPause; } //---------------------------------------------------- // @name SetisPause // @content ポーズ中かどうかのセット // @param bool ポーズ中かどうか // @return none // @date 2014/2/12 //---------------------------------------------------- void SetIsPause ( bool isPause ) { m_isPause = isPause; } //---------------------------------------------------- // @name SetIsPause // @content ポーズ中かどうかのセット(入れ替え) // @param none // @return none // @date 2014/2/12 //---------------------------------------------------- void SetIsPause ( void ) { m_isPause ^= true; } //---------------------------------------------------- // @name GetPauseState // @content ポーズのステータスをセット // @param none // @return ePauseState ポーズのステータス // @date 2014/2/12 //---------------------------------------------------- ePauseStatus GetPauseState ( void ) { return m_ePauseState; } }; #endif _C_PAUSE_MANAGER_H_<file_sep> #include "CDiceInfoObj.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDiceInfoObj::CDiceInfoObj( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDiceInfoObj::~CDiceInfoObj( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CDiceInfoObj::Init( void ) { m_isExist = true; this->InitWorldMtx(); return true; } //---------------------------------------------------- // 回転行列をコピーしてワールド行列にセット //---------------------------------------------------- void CDiceInfoObj::CopyRotationMtx( CONST D3DXMATRIX* worldMtx ) { m_worldMtx._11 = worldMtx->_11; m_worldMtx._12 = worldMtx->_12; m_worldMtx._13 = worldMtx->_13; m_worldMtx._21 = worldMtx->_21; m_worldMtx._22 = worldMtx->_22; m_worldMtx._23 = worldMtx->_23; m_worldMtx._31 = worldMtx->_31; m_worldMtx._32 = worldMtx->_32; m_worldMtx._33 = worldMtx->_33; }<file_sep>/************************************************************* * @file CInputMouse.h * @brief CInputMouseクラスヘッダー * @note 特になし * @author <NAME> * @date 2013/07/31 *************************************************************/ #ifndef _Include_CInputMouse_h_ // インクルードガード #define _Include_CInputMouse_h_ //------------------------------------------------------------ // インクルード //------------------------------------------------------------ #include<Windows.h> #include<queue> //------------------------------------------------------------ // 定数、構造体定義 //------------------------------------------------------------ namespace MOUSECODE { namespace PRESS { enum { LEFT = 0x0000004, MIDDLE = 0x0000002, RIGHT = 0x0000001, }; } namespace TRIGGER { enum { LEFT = 0x0000040, MIDDLE = 0x0000020, RIGHT = 0x0000010, }; } namespace RELEASE { enum { LEFT = 0x0000400, MIDDLE = 0x0000200, RIGHT = 0x0000100, }; } } /*!----------------------------------------------------------- // @class CInputMouse // @brief マウス入力管理クラス // @note 特になし // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ class CInputMouse { public: /// デストラクタ ~CInputMouse() { } /*!----------------------------------------------------------- // @brief シングルトンによる呼び出し // @note 特になし // @param[in] なし // @return 自身の参照 // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ static CInputMouse* GetInstance() { static CInputMouse singleton; return &singleton; } /*!----------------------------------------------------------- // @brief ウィンドウハンドルセット // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ void SetWindowHandle(HWND hWnd) { m_hWnd = hWnd; } /*!----------------------------------------------------------- // @brief マウスの入力状態更新 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ void Update() { HWND hWnd = GetForegroundWindow(); m_isNowActive = (m_hWnd!=hWnd)? FALSE : TRUE; //アクティブでなければreturn if( m_isNowActive == FALSE ) return; //過去の入力状態にシフト m_inputState = m_inputState<<12; //現在の入力状態取得 m_inputState |= (GetKeyState(VK_LBUTTON)&0x80)>>5; m_inputState |= (GetKeyState(VK_MBUTTON)&0x80)>>6; m_inputState |= (GetKeyState(VK_RBUTTON)&0x80)>>7; //トリガーリリース検出 m_inputState |= ( (m_inputState<<4)^(m_inputState>>8)&(m_inputState<<4) )&0x70 ; m_inputState |= ( ( (m_inputState<<8)^(m_inputState>>4) )&(m_inputState>>4) )&0x700; } /*!----------------------------------------------------------- // @brief マウスホイールの更新 // @note プロシージャで更新しないと精度がガタ落ち // @param[in] zDelta ホイールの状態 // @return なし // @author <NAME> // @date 2013/08/01 ------------------------------------------------------------*/ void UpdateWheel(SHORT zDelta) { m_zQueue.push(zDelta/120); } /*!----------------------------------------------------------- // @brief マウスのスクリーン相対座標取得 // @note 特になし // @param[out] pPos 出力するマウスの移動相対座標 // @return なし // @author <NAME> // @date 2013/08/05 ------------------------------------------------------------*/ void GetRelativeCursorPos(LPPOINT pPos) { this->UpdateCursorPos(); pPos->x = m_nowCursorPos.x-m_logCursorPos.x; pPos->y = m_nowCursorPos.y-m_logCursorPos.y; } /*!----------------------------------------------------------- // @brief マウスのスクリーン絶対座標取得 // @note 特になし // @param[in] pPos 出力するマウスのスクリーン絶対座標 // @return なし // @author <NAME> // @date 2013/08/01 ------------------------------------------------------------*/ void GetAbsoluteCursorPos(LPPOINT pPos) { this->UpdateCursorPos(); pPos->x = m_nowCursorPos.x; pPos->y = m_nowCursorPos.y; } /*!----------------------------------------------------------- // @brief マウス座標の更新 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/08/05 ------------------------------------------------------------*/ void UpdateCursorPos() { if( m_isNowActive == FALSE) return; m_logCursorPos.x = m_nowCursorPos.x; m_logCursorPos.y = m_nowCursorPos.y; ::GetCursorPos(&m_nowCursorPos); ScreenToClient(m_hWnd,&m_nowCursorPos); } /*!----------------------------------------------------------- // @brief マウスの中央ホイールの回転角度取得 // @note 特になし // @param[in] なし // @return ホイールの回転角度(-1or1) // @author <NAME> // @date 2013/08/01 ------------------------------------------------------------*/ SHORT GetWheelRotation() { if( m_zQueue.empty() ) return 0; SHORT rtn = m_zQueue.back(); m_zQueue.pop(); return rtn; } /*!----------------------------------------------------------- // @brief マウスの入力状態取得 // @note 特になし // @param[in] なし // @return 入力状態のビット // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ BYTE GetPressButton(SHORT mask) { return (BYTE)(m_inputState&mask); } /*!----------------------------------------------------------- // @brief マウスの入力状態取得 // @note 特になし // @param[in] なし // @return 入力状態のビット // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ BYTE GetTriggerButton(SHORT mask) { return (BYTE)( (m_inputState&mask)>>4 ); } /*!----------------------------------------------------------- // @brief マウスの入力状態取得 // @note 特になし // @param[in] なし // @return 入力状態のビット // @author <NAME> // @date 2013/07/31 ------------------------------------------------------------*/ BYTE GetReleaseButton(SHORT mask) { return (BYTE)( (m_inputState&mask)>>8 ); } private: HWND m_hWnd; BOOL m_isNowActive; SHORT m_inputState; POINT m_logCursorPos; POINT m_nowCursorPos; std::queue<SHORT> m_zQueue; private: /// コンストラクタ CInputMouse() { m_hWnd = NULL; m_isNowActive = TRUE; m_nowCursorPos.x = 0; m_nowCursorPos.y = 0; m_logCursorPos.x = 0; m_logCursorPos.y = 0; m_inputState = 0; } }; inline CInputMouse* sInputMouseMgr() { return CInputMouse::GetInstance(); } #endif // _Include_CInputMouse_h_<file_sep> #include "CDiceInfoManager.h" const float ConstInfoXPos = 200.0f; const float ConstInfoYPos = 70.0f; const float ConstInfoXSize = 110.0f; const float ConstInfoYSize = 110.0f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDiceInfoManager::CDiceInfoManager( void ) { m_pInfo = new C2DSpriteRHW; m_pResInfoFilePath = GAME_DICEINFO_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResInfoFilePath ); m_pDiceInfo = new CDiceInfoObj; m_pResInfoDiceFilePath = DICE_XFILEPATH; CResourceManager::GetInstance()->LoadXFile( m_pResInfoDiceFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDiceInfoManager::~CDiceInfoManager( void ) { SAFE_DELETE( m_pDiceInfo ); SAFE_DELETE( m_pInfo ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CDiceInfoManager::Init( void ) { m_pInfo->SetVertexPos( ConstInfoXPos, ConstInfoYPos, ConstInfoXSize, ConstInfoYSize ); m_pDiceInfo->Init(); m_pDiceInfo->MoveWorldPos( -21.0f, 10.0f, 5.0f ); return true; } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CDiceInfoManager::Uninit( void ) { return true; } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CDiceInfoManager::Draw( void ) { // Infoの画像 CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResInfoFilePath )->Get(), m_pInfo->GetVertex() ); // Info用のダイス if( m_pDiceInfo->GetIsExist() == true ) { CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( m_pResInfoDiceFilePath ), m_pDiceInfo->GetWorldMtx() ); } } //---------------------------------------------------- // ダイスインフォのダイスのセット //---------------------------------------------------- void CDiceInfoManager::SetInfoDice( CONST D3DXMATRIX* mainDiceWorldMtx ) { m_pDiceInfo->CopyRotationMtx( mainDiceWorldMtx ); } <file_sep> #include "../../KaiFrameWorkHeader/WindowsHeader/CWindowSystem.h" //---------------------------------------------------- // スクリーンの大きさを指定しない(初期値)コンストラクタ //---------------------------------------------------- CWindowSystem::CWindowSystem(void) { this->screenWidth = DEFAULT_WINDOW_X; this->screenHeight = DEFAULT_WINDOW_Y; // ウィンドウ作成 this->CreateWnd(); // クライアントサイズの設定 this->SetClientSize(); //メッセージ取出し PeekMessage(&msg,NULL,0,0,PM_REMOVE); // ms単位で時間取得 timeBeginPeriod(1); } //---------------------------------------------------- // スクリーンの大きさを指定したコンストラクタ //---------------------------------------------------- CWindowSystem::CWindowSystem( CONST UINT screenWidth, CONST UINT screenHeight) { this->screenWidth = screenWidth; this->screenHeight = screenHeight; // ウィンドウ作成 this->CreateWnd(); // クライアントサイズの設定 this->SetClientSize(); //メッセージ取出し PeekMessage(&msg,NULL,0,0,PM_REMOVE); // ms単位で時間取得 timeBeginPeriod(1); } //---------------------------------------------------- // フルスクリーンモードで起動するためのコンストラクタ //---------------------------------------------------- CWindowSystem::CWindowSystem(bool isFullScr) { this->screenWidth = WINDOW_MAX_X; this->screenHeight = WINDOW_MAX_Y; // ウィンドウ作成 this->CreateWnd(); // クライアントサイズの設定 this->SetClientSize(); //メッセージ取出し PeekMessage(&msg,NULL,0,0,PM_REMOVE); // ms単位で時間取得 timeBeginPeriod(1); } //---------------------------------------------------- // ウィンドウ作成 //---------------------------------------------------- HRESULT CWindowSystem::CreateWnd(void) { HWND& hWnd = CWindowSystem::GethWnd(); HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL); // ウィンドウクラスの作成 SetWindowClass(); hWnd = CreateWindow(wc.lpszClassName, GAME_TITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, screenWidth, screenHeight, NULL, NULL, hInstance, NULL); // ウィンドウが作成できたかエラーチェック if( hWnd == NULL ) { DEBUG::PrintfColor(DEBUG::H_RED,"---- Create Window Failed... ----\n\n" ); return E_FAIL; } ShowWindow(hWnd, SW_SHOWNORMAL); UpdateWindow(hWnd); DEBUG::PrintfColor(DEBUG::H_GREEN, "---- Create Window Successfully ----\n\n" ); return S_OK; } //---------------------------------------------------- // ウィンドウクラス生成 //---------------------------------------------------- HRESULT CWindowSystem::SetWindowClass(void) { HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.hInstance = hInstance; wc.lpszClassName = WINDOW_CLASS_NAME; wc.lpfnWndProc = (WNDPROC)WndProc; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; wc.cbClsExtra = 0; wc.cbWndExtra = 0; // 作成できたかをチェック if(!RegisterClassEx(&wc) ){ MessageBox(NULL,"設計エラー","bb",MB_OK); return E_FAIL; } return S_OK; } //---------------------------------------------------- // ウィンドウを表示 //---------------------------------------------------- HRESULT CWindowSystem::SetShowWindow(void) { HWND& hWnd = CWindowSystem::GethWnd(); ShowWindow(hWnd, SW_SHOWNORMAL); return S_OK; } //---------------------------------------------------- // メッセージ送出(毎フレーム受け取る) //---------------------------------------------------- BOOL CWindowSystem::PeekEventMessage(void) { if( PeekMessage(&msg,NULL,0,0,PM_REMOVE) ) { if(this->msg.message == WM_QUIT) return false; // メッセージ処理 TranslateMessage(&msg); DispatchMessage(&msg); } return true; } //---------------------------------------------------- // メッセージ送出(イベントを受け取った時のみ) //---------------------------------------------------- BOOL CWindowSystem::GetEventMessage(void) { if( GetMessage(&msg, NULL, 0, 0) ) { if( msg.message == WM_QUIT ) { return false; } // メッセージ処理 TranslateMessage(&msg); DispatchMessage(&msg); } return true; } //---------------------------------------------------- // ウィンドウプロシージャ //---------------------------------------------------- LRESULT CALLBACK CWindowSystem::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch( message ) { // ウィンドウ破棄 case WM_DESTROY: PostQuitMessage(0); break; case WM_CLOSE: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } //---------------------------------------------------- // クライアントサイズの設定 //---------------------------------------------------- void CWindowSystem::SetClientSize() { RECT rect; // サイズ用ワーク HWND& hWnd = CWindowSystem::GethWnd(); GetClientRect(hWnd,&rect); // クライアント部分のサイズの取得 clientSize.x = rect.right - rect.left; clientSize.y = rect.bottom - rect.top; } <file_sep>//---------------------------------------------------- // 3DObjectShape // 経常描画のためのヘッダー // スフィア,ボックス // // @date 2013/7/10 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_3D_OBJECT_SHAPE_H_ #define _C_3D_OBJECT_SHAPE_H_ #include <d3dx9.h> #include "../../DirectX9Header/CDirectX9FrameWork.h" #include "../CObjectBase.hpp" class C3DObjectShape : public CObjectBase { private: LPD3DXMESH m_pMesh; // メッシュデータ D3DMATERIAL9 m_materials; // マテリアルデータ public: C3DObjectShape ( void ); virtual ~C3DObjectShape ( void ); //---------------------------------------------------- // @name CreateSphere // @content スフィアの生成 // @param radius 半径 // @return bool 作成できたか出来なかったか // @date 2013/7/10 //---------------------------------------------------- bool CreateSphere ( CONST float radius ); //---------------------------------------------------- // @name CreateBox // @content ボックスの生成 // @param size 大きさ // @return bool 作成できたか出来なかったか // @date 2013/7/10 //---------------------------------------------------- bool CreateBox ( CONST D3DXVECTOR3* size ); //---------------------------------------------------- // @name SetDiffuse // @content ディフューズ色の設定 // @param r 赤値( 0 〜 255 ) // @param g 緑値( 0 〜 255 ) // @param b 青値( 0 〜 255 ) // @param a α値 ( 0 〜 255 ) // @return none // @date 2013/7/10 // @update 2013/12/17 引数の値をUINT型にし 1.0から255対応 //---------------------------------------------------- void SetDiffuse ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // @name SetAmbient // @content アンビエント色の設定 // @param r 赤値( 0 〜 255 ) // @param g 緑値( 0 〜 255 ) // @param b 青値( 0 〜 255 ) // @param a α値 ( 0 〜 255 ) // @return none // @date 2013/710 // @update 2013/12/17 引数の値をUINT型にし 1.0から255対応 //---------------------------------------------------- void SetAmbient ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // メッシュデータの取得 // @data none // @return LPD3DXMESH //---------------------------------------------------- CONST LPD3DXMESH GetMesh ( void ) { return m_pMesh; } //---------------------------------------------------- // マテリアルデータの取得 // @data none // @return D3DMATRIAL9* //---------------------------------------------------- CONST D3DMATERIAL9* GetMaterial ( void ) { return &m_materials; } }; #endif _C_3D_OBJECT_SHAPE_H_<file_sep> #include "../../KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" //---------------------------------------------------- // レンダリング開始 //---------------------------------------------------- BOOL CDirectDrawSystem::BeginScene( void ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 0, 0, 0 ), 1.0f, 0); if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { // 描画開始 return true; } return false; } //---------------------------------------------------- // レンダリング終了 //---------------------------------------------------- void CDirectDrawSystem::EndScene( void ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->EndScene(); } //---------------------------------------------------- // 2Dレンダリング( 同次座標計算あり ) //---------------------------------------------------- void CDirectDrawSystem::DrawSpriteRHW( CONST LPDIRECT3DTEXTURE9 pTexture,CONST tagTSPRITERHW* pVertex ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // αブレンドを行う pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE,TRUE ); // 透過処理を行う pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA ); // 描画の型変換 pd3dDevice->SetFVF( FVF_VERTEX_SPRITERHW ); // テクスチャ描画 pd3dDevice->SetTexture( 0,pTexture ); // ポリゴン描画 pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, pVertex, sizeof( tagTSPRITERHW ) ); } //---------------------------------------------------- // 2Dレンダリング( 同次座標計算あり テクスチャなし ) //---------------------------------------------------- void CDirectDrawSystem::DrawSpriteRHW( CONST tagTSPRITERHW *pVertex ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 描画の型変換 pd3dDevice->SetFVF( FVF_VERTEX_SPRITERHW ); // テクスチャ描画しない pd3dDevice->SetTexture( 0,NULL ); // ポリゴン描画 pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, pVertex, sizeof( tagTSPRITERHW ) ); } //---------------------------------------------------- // 2Dスプライトレンダリング( 同次座標計算なし テクスチャあり ) //---------------------------------------------------- void CDirectDrawSystem::DrawSprite( CONST LPDIRECT3DTEXTURE9 pTexture, tagTSPRITE* pSpriteVertex, CONST D3DXMATRIX* pWorldMtx ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // ライティング計算はしない。深度バッファには書き込まない pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA ); // 光源計算オフ(頂点の色が有効になる) pd3dDevice->SetRenderState( D3DRS_LIGHTING,FALSE ); // Zバッファを無効化(アルファブレンドを有効にするため) pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,FALSE ); // テクスチャステージステート pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAOP,D3DTOP_MODULATE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG2,D3DTA_DIFFUSE ); pd3dDevice->SetTexture( 0, pTexture ); // テクスチャをセット pd3dDevice->SetFVF( FVF_VERTEX_SPRITE ); // 頂点の型をセット pd3dDevice->SetTransform( D3DTS_WORLD, pWorldMtx ); // ワールド行列をセット // レンダリング pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, pSpriteVertex, sizeof(tagTSPRITE) ); } //---------------------------------------------------- // ビルボードレンダリング //---------------------------------------------------- void CDirectDrawSystem::DrawBillBoard( CONST LPDIRECT3DTEXTURE9 pTexture, CONST D3DXMATRIX* pBillboardMtx, CONST tagTBILLBORDVERTEX* pBillboardVertex ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // ライティング計算はしない。深度バッファには書き込まない pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA ); // 光源計算オフ(頂点の色が有効になる) pd3dDevice->SetRenderState( D3DRS_LIGHTING,FALSE ); // Zバッファを無効化(アルファブレンドを有効にするため) pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,FALSE ); // テクスチャステージステート pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAOP,D3DTOP_MODULATE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG2,D3DTA_DIFFUSE ); pd3dDevice->SetTexture( 0,pTexture ); // テクスチャをセット pd3dDevice->SetFVF( FVF_VERTEX_BILLBOARD ); // 頂点の型をセット pd3dDevice->SetTransform( D3DTS_WORLD,pBillboardMtx ); // ワールド行列をセット // レンダリング pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN,2,pBillboardVertex,sizeof(tagTBILLBORDVERTEX) ); } //---------------------------------------------------- // 3Dモデルレンダリング //---------------------------------------------------- void CDirectDrawSystem::Draw3D( CResourceXFile *pModel, CONST D3DXMATRIX *pWorldMtx ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 光源計算オン pd3dDevice->SetRenderState( D3DRS_LIGHTING,TRUE ); // Zバッファを有効化 pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,TRUE ); pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // 頂点の型をセット pd3dDevice->SetFVF( FVF_VERTEX_3D ); // メッシュをマテリアル単位で描画 pd3dDevice->SetTransform( D3DTS_WORLD,pWorldMtx); // レンダリング for( unsigned int i = 0; i < pModel->GetMaterialCount(); ++ i ){ pd3dDevice->SetMaterial( &pModel->GetMeshMaterial()[i] ); pd3dDevice->SetTexture( 0,pModel->GetMeshTexture()[i] ); pModel->GetMesh()->DrawSubset( i ); } } //---------------------------------------------------- // 3Dモデルレンダリング(textureの指定) //---------------------------------------------------- void CDirectDrawSystem::Draw3D( CResourceXFile* pModel, CONST D3DXMATRIX* pWorldMtx, BOOL isTexture ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 光源計算オン pd3dDevice->SetRenderState( D3DRS_LIGHTING,TRUE ); // Zバッファを有効化 pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,TRUE ); pd3dDevice->SetFVF( FVF_VERTEX_3D ); if( isTexture == false ) { pd3dDevice->SetTexture( 0,NULL ); // テクスチャなし } pd3dDevice->SetTransform( D3DTS_WORLD,pWorldMtx ); // レンダリング for( unsigned int i = 0; i < pModel->GetMaterialCount(); ++i ){ pd3dDevice->SetMaterial( &pModel->GetMeshMaterial()[i] ); pModel->GetMesh()->DrawSubset( i ); } } //---------------------------------------------------- // 3Dモデルレンダリング( 色指定 ) //---------------------------------------------------- void CDirectDrawSystem::Draw3D( CResourceXFile* pModel, CONST D3DXMATRIX* pWorldMtx, D3DXCOLOR* color ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 光源計算オン pd3dDevice->SetRenderState( D3DRS_LIGHTING,TRUE ); // Zバッファを有効化 pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,TRUE ); pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // 頂点の型をセット pd3dDevice->SetFVF( FVF_VERTEX_3D ); // メッシュをマテリアル単位で描画 pd3dDevice->SetTransform( D3DTS_WORLD,pWorldMtx); // レンダリング for( unsigned int i = 0; i < pModel->GetMaterialCount(); ++ i ){ D3DMATERIAL9 workMat; // 色を作る ::CopyMemory( &workMat,&pModel->GetMeshMaterial()[i],sizeof( D3DMATERIAL9 ) ); workMat.Diffuse.r = pModel->GetMeshMaterial()[i].Diffuse.r * color->r; workMat.Diffuse.g = pModel->GetMeshMaterial()[i].Diffuse.g * color->g; workMat.Diffuse.b = pModel->GetMeshMaterial()[i].Diffuse.b * color->b; workMat.Diffuse.a = pModel->GetMeshMaterial()[i].Diffuse.a * color->a; pd3dDevice->SetMaterial( &workMat ); pd3dDevice->SetTexture( 0,pModel->GetMeshTexture()[i] ); pModel->GetMesh()->DrawSubset( i ); } } //---------------------------------------------------- // クローン3Dモデルレンダリング //---------------------------------------------------- void CDirectDrawSystem::Draw3DClone( UINT numFaces, CONST LPDIRECT3DTEXTURE9 textureData, tagTORIGINALMESHVERTEX* pCloneVertex, CONST D3DXMATRIX* pCloneMtx ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); //pd3dDevice->SetFVF( FVF_VERTEX_CLONE ); pd3dDevice->SetTexture( 0, textureData ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE,true ); // αブレンドの処理を有効にする for( UINT i = 0; i < numFaces; ++ i ){ pd3dDevice->SetTransform(D3DTS_WORLD,pCloneMtx); pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP,1,pCloneVertex,sizeof(tagTORIGINALMESHVERTEX)); } } //---------------------------------------------------- // クローン3Dモデルレンダリング(テクスチャなし) //---------------------------------------------------- void CDirectDrawSystem::Draw3DClone( UINT numFaces, tagTORIGINALMESHVERTEX* pCloneVertex, CONST D3DXMATRIX* pCloneMtx ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); //pd3dDevice->SetFVF( FVF_VERTEX_CLONE ); pd3dDevice->SetTexture( 0, NULL ); // クローンの3Dモデルレンダリング for( UINT i = 0; i < numFaces; ++ i ){ pd3dDevice->SetTransform( D3DTS_WORLD, pCloneMtx ); pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP,1,&pCloneVertex[i],sizeof( tagTORIGINALMESHVERTEX ) ); } } //---------------------------------------------------- // 形状レンダリング ( スフィア,ボックス ) //---------------------------------------------------- void CDirectDrawSystem::DrawShape( CONST D3DXMATRIX* worldMtx, CONST D3DMATERIAL9* shapeMat, CONST LPD3DXMESH shapeMesh ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); // αブレンドを行う pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); // αソースカラーの指定 pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); // αデスティネーションカラーの指定 pd3dDevice->SetRenderState(D3DRS_LIGHTING,TRUE); // ライトの計算をON pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE,TRUE); // 行列をセット pd3dDevice->SetTransform( D3DTS_WORLD,worldMtx ); // テクスチャのセット pd3dDevice->SetTexture( 0,NULL ); // マテリアルのセット pd3dDevice->SetMaterial( shapeMat ); // レンダリング shapeMesh->DrawSubset(0); } //---------------------------------------------------- // パーティクルレンダリング // 加算合成あり,ライト計算なし,αブレンドあり //---------------------------------------------------- void CDirectDrawSystem::DrawParticle( CONST LPDIRECT3DTEXTURE9 pTexture, CONST D3DXMATRIX* pBillboardMtx, CONST tagTBILLBORDVERTEX* pBillboardVertex ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE,TRUE ); pd3dDevice->SetRenderState( D3DRS_SRCBLEND,D3DBLEND_SRCALPHA ); pd3dDevice->SetRenderState( D3DRS_BLENDOP,D3DBLENDOP_ADD ); pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_ONE ); // 加算合成 // ライティング計算はしない。深度バッファには書き込まない pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA ); // 光源計算オフ(頂点の色が有効になる) pd3dDevice->SetRenderState( D3DRS_LIGHTING,FALSE ); // Zバッファを無効化(アルファブレンドを有効にするため) pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,FALSE ); // テクスチャステージステート pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAOP,D3DTOP_MODULATE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE ); pd3dDevice->SetTextureStageState( 0,D3DTSS_ALPHAARG2,D3DTA_DIFFUSE ); pd3dDevice->SetTexture( 0,pTexture ); // テクスチャセット pd3dDevice->SetFVF( FVF_VERTEX_BILLBOARD ); // 頂点の型セット pd3dDevice->SetTransform( D3DTS_WORLD,pBillboardMtx ); // ワールド行列をセット // レンダリング pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN,2,pBillboardVertex,sizeof(tagTBILLBORDVERTEX) ); } //---------------------------------------------------- // デバッグステージレンダリング // テクスチャなし //---------------------------------------------------- void CDirectDrawSystem::DrawDebugStage ( CONST UINT numLines, CONST tagTDEBUGVERTEX* pDebugStageVertex ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); D3DXMATRIX workMtx; D3DXMatrixIdentity( &workMtx ); // ライティング計算はしない。深度バッファには書き込まない pd3dDevice->SetRenderState( D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA ); // 光源計算オフ(頂点の色が有効になる) pd3dDevice->SetRenderState( D3DRS_LIGHTING,FALSE ); // Zバッファを無効化(アルファブレンドを有効にするため) pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE,FALSE ); pd3dDevice->SetTexture( 0,NULL ); pd3dDevice->SetFVF( FVF_VERTEX_DEBUG ); pd3dDevice->SetTransform( D3DTS_WORLD,&workMtx ); // レンダリング pd3dDevice->DrawPrimitiveUP( D3DPT_LINELIST,numLines,pDebugStageVertex,sizeof( tagTDEBUGVERTEX ) ); } <file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteRHW.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C2DSpriteRHW::C2DSpriteRHW( void ) { // 頂点座標・色を初期化 for( int i = 0; i < 4; ++ i ){ m_vertex[i].pos.x = 0.0f; m_vertex[i].pos.y = 0.0f; m_vertex[i].pos.z = 0.0f; m_vertex[i].diffuse = D3DCOLOR_RGBA(255,255,255,255); m_vertex[i].rhw = 1.0f; } m_center.x = 0.0f; m_center.y = 0.0f; m_size.x = 0.0f; m_size.y = 0.0f; m_halfSize.x = 0.0f; m_halfSize.y = 0.0f; // テクスチャ座標初期化 this->SetUV( 1,1,1,1 ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C2DSpriteRHW::~C2DSpriteRHW( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool C2DSpriteRHW::Init( void ) { // 頂点座標・色を初期化 for( int i = 0; i < 4; ++ i ){ m_vertex[i].pos.x = 0.0f; m_vertex[i].pos.y = 0.0f; m_vertex[i].pos.z = 0.0f; m_vertex[i].diffuse = D3DCOLOR_RGBA(255,255,255,255); m_vertex[i].rhw = 1.0f; } m_center.x = 0.0f; m_center.y = 0.0f; m_size.x = 0.0f; m_size.y = 0.0f; // テクスチャ座標初期化 this->SetUV( 1,1,1,1 ); return true; } //---------------------------------------------------- // スプライト頂点座標のセット //---------------------------------------------------- void C2DSpriteRHW::SetVertexPos( CONST float centerX, CONST float centerY, CONST float width, CONST float height ) { m_halfSize.x = width / 2; m_halfSize.y = height / 2; m_vertex[0].pos.x = centerX - m_halfSize.x; m_vertex[0].pos.y = centerY - m_halfSize.y; m_vertex[1].pos.x = centerX + m_halfSize.x; m_vertex[1].pos.y = centerY - m_halfSize.y; m_vertex[2].pos.x = centerX - m_halfSize.x; m_vertex[2].pos.y = centerY + m_halfSize.y; m_vertex[3].pos.x = centerX + m_halfSize.x; m_vertex[3].pos.y = centerY + m_halfSize.y; m_center.x = centerX; m_center.y = centerY; m_size.x = width; m_size.y = height; } //---------------------------------------------------- // スプライト頂点座標のセット //---------------------------------------------------- void C2DSpriteRHW::SetVertexPos( CONST float centerX, CONST float centerY ) { m_vertex[0].pos.x = centerX - m_halfSize.x; m_vertex[0].pos.y = centerY - m_halfSize.y; m_vertex[1].pos.x = centerX + m_halfSize.x; m_vertex[1].pos.y = centerY - m_halfSize.y; m_vertex[2].pos.x = centerX - m_halfSize.x; m_vertex[2].pos.y = centerY + m_halfSize.y; m_vertex[3].pos.x = centerX + m_halfSize.x; m_vertex[3].pos.y = centerY + m_halfSize.y; }; //---------------------------------------------------- // スプライト頂点座標のセット //---------------------------------------------------- void C2DSpriteRHW::SetVertexPos( CONST D3DXVECTOR2* center ) { m_vertex[0].pos.x = center->x - m_halfSize.x; m_vertex[0].pos.y = center->y - m_halfSize.y; m_vertex[1].pos.x = center->x + m_halfSize.x; m_vertex[1].pos.y = center->y - m_halfSize.y; m_vertex[2].pos.x = center->x - m_halfSize.x; m_vertex[2].pos.y = center->y + m_halfSize.y; m_vertex[3].pos.x = center->x + m_halfSize.x; m_vertex[3].pos.y = center->y + m_halfSize.y; } //---------------------------------------------------- // テクスチャ座標セット(画像が1パターン) //---------------------------------------------------- void C2DSpriteRHW::SetUV( void ) { m_vertex[0].tu = 0.0f; m_vertex[0].tv = 0.0f; m_vertex[1].tu = 1.0f; m_vertex[1].tv = 0.0f; m_vertex[2].tu = 0.0f; m_vertex[2].tv = 1.0f; m_vertex[3].tu = 1.0f; m_vertex[3].tv = 1.0f; } //---------------------------------------------------- // テクスチャ座標セット(UVパターンを設定) //---------------------------------------------------- void C2DSpriteRHW::SetUV( CONST UINT uPatern, CONST UINT vPatern, CONST UINT uNum, CONST UINT vNum ) { m_vertex[0].tu = 1.0f / uPatern * ( uNum - 1 ); m_vertex[0].tv = 1.0f / vPatern * ( vNum - 1 ); m_vertex[1].tu = 1.0f / uPatern * uNum; m_vertex[1].tv = 1.0f / vPatern * ( vNum - 1 ); m_vertex[2].tu = 1.0f / uPatern * ( uNum - 1 ); m_vertex[2].tv = 1.0f / vPatern * vNum; m_vertex[3].tu = 1.0f / uPatern * uNum; m_vertex[3].tv = 1.0f / vPatern * vNum; } //---------------------------------------------------- // ディフューズ色のセット //---------------------------------------------------- void C2DSpriteRHW::SetDiffuse( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ) { for( int i = 0; i < 4; ++ i ){ m_vertex[i].diffuse = D3DCOLOR_RGBA( r, g, b, a ); } } <file_sep> #include "../../KaiFrameWorkHeader/DirectX9Header/CXAudio2.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CXAudio2::CXAudio2( void ) { m_pXAudio2 = NULL; m_pMasteringVoice = NULL; for( int i = 0; i < MAX_WAV; ++ i ) { m_pSourceVoice[ i ] = NULL; m_pWavBuffer[ i ] = NULL; m_dwWavSize[ i ] = 0; } m_reserveNumber = 0; for(int i = 0; i < 10; i++) { m_FadeFlag[i] = 0; } m_volBGM = 1.0f; //BGM音量の初期設定 m_volSE = 1.0f; //SE音量の初期設定 m_stepBGM = 4; m_stepSE = 4; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CXAudio2::~CXAudio2( void ) { for( int i = 0; i < MAX_WAV; ++i ) { Stop( i ); // とりあえず曲をストップ if( m_pSourceVoice[ i ] != NULL ) { m_pSourceVoice[ i ]->DestroyVoice(); } if( m_pWavBuffer[ i ] != NULL ) { delete m_pWavBuffer[ i ]; m_pWavBuffer[ i ] = NULL; } } if( m_pXAudio2 != NULL ) { m_pXAudio2->Release(); m_pXAudio2 = NULL; } } //---------------------------------------------------- // 初期化 //---------------------------------------------------- HRESULT CXAudio2::Init( void ) { CoInitializeEx( NULL, COINIT_MULTITHREADED ); if( FAILED( XAudio2Create( &m_pXAudio2, XAUDIO2_DEBUG_ENGINE ) ) ) { CoUninitialize(); return E_FAIL; } if( FAILED( m_pXAudio2->CreateMasteringVoice( &m_pMasteringVoice ) ) ) { CoUninitialize(); return E_FAIL; } return S_OK; } //---------------------------------------------------- // Wavデータの読み込み //---------------------------------------------------- boolean CXAudio2::LoadWav( CONST UINT index, CONST LPSTR fileName ) { // すでにデータが入っているとき if( m_pWavBuffer[ index ] ) { return false; } // 範囲外のとき if( index >= MAX_WAV || index < 0 ) { return false; } HMMIO hMmio=NULL; // WindowsマルチメディアAPIのハンドル(WindowsマルチメディアAPIはWAVファイル関係の操作用のAPI) DWORD dwWavSize=0; // WAVファイル内 WAVデータのサイズ(WAVファイルはWAVデータで占められているので、ほぼファイルサイズと同一) WAVEFORMATEX* pwfex; // WAVのフォーマット 例)16ビット、44100Hz、ステレオなど MMCKINFO ckInfo; // チャンク情報 MMCKINFO riffckInfo; // 最上部チャンク(RIFFチャンク)保存用 PCMWAVEFORMAT pcmWaveForm; //WAVファイル内のヘッダー情報(音データ以外)の確認と読み込み hMmio = mmioOpenA( fileName, NULL, MMIO_ALLOCBUF | MMIO_READ ); //ファイルポインタをRIFFチャンクの先頭にセットする mmioDescend( hMmio, &riffckInfo, NULL, 0 ); // ファイルポインタを'f' 'm' 't' ' ' チャンクにセットする ckInfo.ckid = mmioFOURCC('f', 'm', 't', ' '); mmioDescend( hMmio, &ckInfo, &riffckInfo, MMIO_FINDCHUNK ); //フォーマットを読み込む mmioRead( hMmio, ( HPSTR ) &pcmWaveForm, sizeof( pcmWaveForm ) ); pwfex = ( WAVEFORMATEX* )new CHAR[ sizeof( WAVEFORMATEX ) ]; memcpy( pwfex, &pcmWaveForm, sizeof( pcmWaveForm ) ); pwfex->cbSize = 0; mmioAscend( hMmio, &ckInfo, 0 ); // WAVファイル内の音データの読み込み ckInfo.ckid = mmioFOURCC('d', 'a', 't', 'a'); mmioDescend( hMmio, &ckInfo, &riffckInfo, MMIO_FINDCHUNK );//データチャンクにセット dwWavSize = ckInfo.cksize; m_pWavBuffer[ index ] = new BYTE[ dwWavSize ]; // 動的確保 mmioRead( hMmio, ( HPSTR )m_pWavBuffer[ index ], dwWavSize ); //ソースボイスにデータを詰め込む if( FAILED( m_pXAudio2->CreateSourceVoice( &m_pSourceVoice[ index ], pwfex ) ) ) { MessageBox(0,"ソースボイス作成失敗",0,MB_OK); delete[] pwfex; return false; } delete[] pwfex; m_dwWavSize[ index ] = dwWavSize; m_reserveNumber ++; return true;; } //---------------------------------------------------- // Wavデータの解放 //---------------------------------------------------- boolean CXAudio2::Release( CONST UINT index ) { if( m_pSourceVoice[ index ] != NULL ) { m_pSourceVoice[ index ]->DestroyVoice(); m_pSourceVoice[ index ] = NULL; } if( m_pWavBuffer[ index ] != NULL ) { delete m_pWavBuffer[ index ]; m_pWavBuffer[ index ] = NULL; } m_reserveNumber--; return true; } //---------------------------------------------------- // サウンドの再生 //---------------------------------------------------- boolean CXAudio2::Run( CONST UINT index, CONST FLOAT volume, CONST bool isLoop ) { if( !m_pSourceVoice[ index ] ) { return false; } m_pSourceVoice[ index ]->Stop( 0, 0 ); m_pSourceVoice[ index ]->FlushSourceBuffers(); m_pSourceVoice[ index ]->SetVolume( volume ); XAUDIO2_BUFFER buffer = {0}; buffer.pAudioData = m_pWavBuffer[ index ]; buffer.Flags = XAUDIO2_END_OF_STREAM; buffer.AudioBytes = m_dwWavSize[ index ]; //ループの設定 if( isLoop ){ buffer.LoopCount = XAUDIO2_LOOP_INFINITE; } if( FAILED( m_pSourceVoice[ index ]->SubmitSourceBuffer( &buffer ) ) ) { MessageBox( NULL, "ソースボイスにサブミット失敗", "", MB_OK ); return false; } m_pSourceVoice[ index ]->Start( 0, XAUDIO2_COMMIT_NOW ); return true; } //---------------------------------------------------- // サウンドの停止 //---------------------------------------------------- inline boolean CXAudio2::Stop( CONST UINT index ) { if( !m_pSourceVoice[ index ] ) { return false; } m_pSourceVoice[ index ]->Stop( 0, 0 ); m_pSourceVoice[ index ]->FlushSourceBuffers(); return true; } //---------------------------------------------------- // サウンドの一時停止 //---------------------------------------------------- inline boolean CXAudio2::Pause( CONST UINT index ) { if( !m_pSourceVoice[ index ] ) { return false; } m_pSourceVoice[ index ]->Stop( 0, 0 ); return true; } //---------------------------------------------------- // サウンドの音量変更 //---------------------------------------------------- inline boolean CXAudio2::ChengeVolume( CONST UINT index, CONST FLOAT volume ) { m_pSourceVoice[ index ]->SetVolume( volume ); return true; } //---------------------------------------------------- // サウンドにフェードをかけて停止する。毎ループ呼び出す。 //---------------------------------------------------- boolean CXAudio2::FadeStopManeger( CONST FLOAT volume ) { static float fadeVol = volume; for(int i=0; i<MAX_WAV; i++) { if(m_FadeFlag[ i ] == 1) { m_pSourceVoice[ i ]->GetVolume(&fadeVol); if(fadeVol <= 0.0f) { Stop( i ); m_FadeFlag[ i ] = 0; } else { fadeVol -= 0.125f; //ループごとに下げる音量 if( fadeVol < 0.0f) { fadeVol = 0.0f; } m_pSourceVoice[ i ]->SetVolume( volume ); } } } return true; } //---------------------------------------------------- // BGMの音量取得 //---------------------------------------------------- inline float CXAudio2::GetVolumeBGM( void ) { return m_volBGM; } //---------------------------------------------------- // SEの音量取得 //---------------------------------------------------- inline float CXAudio2::GetVolumeSE( void ) { return m_volSE; } //---------------------------------------------------- // BGMの音量をセット //---------------------------------------------------- inline float CXAudio2::SetVolumeBGM( FLOAT volume ) { m_volBGM = volume; return m_volBGM; } //---------------------------------------------------- // SEの音量をセット //---------------------------------------------------- inline float CXAudio2::SetVolumeSE( FLOAT volume ) { m_volSE = volume; return m_volSE; } //---------------------------------------------------- // BGMのstep(倍率)をGetする //---------------------------------------------------- inline int CXAudio2::GetStepBGM( void ) { return m_stepBGM; } //---------------------------------------------------- // SEのstep(倍率)をGetする //---------------------------------------------------- inline int CXAudio2::GetStepSE( void ) { return m_stepSE; } //---------------------------------------------------- // BGMのstep(倍率)をSetする //---------------------------------------------------- inline int CXAudio2::SetStepBGM( int step ) { m_stepBGM = step; return m_stepBGM; } //---------------------------------------------------- // SEのstep(倍率)をSetする //---------------------------------------------------- inline int CXAudio2::SetStepSE( int step ) { m_stepSE = step; return m_stepSE; } //---------------------------------------------------- // Fadeをかけて停止するサウンドの番号を指示する //---------------------------------------------------- boolean CXAudio2::StopwithFade( CONST UINT index, int num ) { m_FadeFlag[ index ] = num; return true; } <file_sep> #include "CMySQLScoreManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CMySQLScoreManager::CMySQLScoreManager( void ) { m_scoreID = ""; m_userID = ""; m_userName = ""; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CMySQLScoreManager::~CMySQLScoreManager( void ) { } //---------------------------------------------------- // ハイスコアの更新 //---------------------------------------------------- bool CMySQLScoreManager::UpdateHighScore( CONST std::string* updateSql ) { // MySQLと接続 if( CMySQLManager::GetInstance()->ConnectDatabase() == true ) { std::string conditionSql = COMBINE_STRING( 3,"userID = '", m_userID.c_str(), "'" ); if( CMySQLManager::GetInstance()->Update( &(std::string)SCORE_TABLE, updateSql, &conditionSql ) == true ) { // 更新成功 CMySQLManager::GetInstance()->UnConnectionDatabase(); return true; } CMySQLManager::GetInstance()->UnConnectionDatabase(); // MYSQLから切断 return false; } // MySQL接続失敗 return false; } //---------------------------------------------------- // スコアの取得 //---------------------------------------------------- CScore* CMySQLScoreManager::GetScore( CScore* score ) { // MySQLと接続 if( CMySQLManager::GetInstance()->ConnectDatabase() == true ) { std::string columnSql = COMBINE_STRING( 1, "record,onePip,twoPip,threePip,fourPip,fivePip,sixPip,maxChain" ); std::string conditionSql = COMBINE_STRING( 3,"userID = '", m_userID.c_str(), "'" ); MYSQL_ROW field = nullptr; // テーブルからスコアを取得してメンバにセット field = CMySQLManager::GetInstance()->Search( field, &(std::string)SCORE_TABLE, &columnSql, &conditionSql); score->m_record = atoi(field[0]); score->m_oneChainNum = atoi(field[1]); score->m_twoChainNum = atoi(field[2]); score->m_threeChainNum = atoi(field[3]); score->m_fourChainNum = atoi(field[4] ); score->m_fiveChainNum = atoi(field[5]); score->m_sixChainNum = atoi(field[6]); score->m_chainNum = atoi(field[7]); CMySQLManager::GetInstance()->UnConnectionDatabase(); // MYSQLから切断 return score; } // 接続失敗 CMySQLManager::GetInstance()->UnConnectionDatabase(); // MYSQLから切断 return score; }<file_sep> #include "CPlayer.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CPlayer::CPlayer( void ) { m_pAABB = new THITAABB; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CPlayer::~CPlayer( void ) { SAFE_DELETE( m_pAABB ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CPlayer::Init( void ) { // スプライトの設定 this->SetSprite( &D3DXVECTOR3( 0.0f,4.0f,0.0f ), &D3DXVECTOR3( 5.0f, 4.0f, 0.0f )); this->SetUV( 4, 4, 1, 1 ); // ダイスとの当たり判定用の仮想AABBを作成 D3DXVECTOR3 aabbPos = D3DXVECTOR3( this->GetXPos() , this->GetYPos(), this->GetZPos() ); D3DXVECTOR3 aabbSize = D3DXVECTOR3( 0.5f, 8.0f , 0.5f ); m_pAABB = CCollision::GetInstance()->SetAABB( m_pAABB, &aabbPos, &aabbSize ); // ステータス初期化 m_status = ePlayerStatus::eOnDice; m_moveStatus = ePlayerMoveStatus::eMoveNone; return true; } //---------------------------------------------------- // 終了処理 //---------------------------------------------------- bool CPlayer::Uninit( void ) { return true; } //---------------------------------------------------- // 前移動 //---------------------------------------------------- void CPlayer::MoveFront( CONST float speed ) { MoveSpritePos( 0.0f, 0.0f, speed ); this->SetUV( 4, 4, 1, 4 ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); } //---------------------------------------------------- // 後移動 //---------------------------------------------------- void CPlayer::MoveBack( CONST float speed ) { MoveSpritePos( 0.0f, 0.0f, -speed ); this->SetUV( 4, 4, 1, 1 ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); } //---------------------------------------------------- // 右移動 //---------------------------------------------------- void CPlayer::MoveRight( CONST float speed ) { MoveSpritePos( speed, 0.0f, 0.0f ); this->SetUV( 4, 4, 1, 2 ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); } //---------------------------------------------------- // 左移動 //---------------------------------------------------- void CPlayer::MoveLeft( CONST float speed ) { MoveSpritePos( -speed, 0.0f, 0.0f ); this->SetUV( 4, 4, 1, 3 ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); } //---------------------------------------------------- // ダウン処理 //---------------------------------------------------- void CPlayer::MoveDown( CONST float speed ) { MoveSpritePos( 0.0f, -speed, 0.0f ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); } //---------------------------------------------------- // アップ処理 //---------------------------------------------------- void CPlayer::MoveUp( CONST float speed ) { MoveSpritePos( 0.0f, speed, 0.0f ); // AABB位置更新 this->SetAABB(); CDebugMode::m_pPlayerBox.SetWorldPos( GetXPos(), GetYPos(), GetZPos() ); }<file_sep>//---------------------------------------------------- // CDirectDrawSystem Header // DirectXの描画システム // // @date 2013/5/1 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DIRECTX9_DRAW_SYSTEM_H_ #define _C_DIRECTX9_DRAW_SYSTEM_H_ // 内部ヘッダー読み込み #include <d3dx9.h> // 外部ヘッダー読み込み #include "../DirectX9Header/CDirectX9FrameWork.h" #include "../GameObjectHeader/2D/C2DSprite.h" #include "../GameObjectHeader/2D/C2DSpriteRHW.h" #include "../GameObjectHeader/CObjectBase.hpp" #include "../GameObjectHeader/BillBoard/CBillBoard.h" #include "../DebugHeader/CDebugStage.h" #include "../ResourceHeader/COriginalMesh.h" #include "../ResourceHeader/CResourceXFile.h" #include "../ResourceHeader/CResourceTexture.h" #define FVF_VERTEX_SPRITERHW ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // Sprite(RHWあり)描画用FVF #define FVF_VERTEX_SPRITE ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // Sprite描画用FVF #define FVF_VERTEX_3D ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // 3D描画用FVF #define FVF_VERTEX_MESH ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // クローンモデル用FVF #define FVF_VERTEX_BILLBOARD ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // ビルボード用FVF #define FVF_VERTEX_DEBUG ( D3DFVF_XYZ | D3DFVF_DIFFUSE ) // デバッグ用FVF #define FVF_VERTEX_CLONE ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) // クローン用FVF class CDirectDrawSystem { private: // コンストラクタ CDirectDrawSystem ( void ){} CDirectDrawSystem ( CONST CDirectDrawSystem& input ){} // コピーコンストラクタを防ぐ CDirectDrawSystem operator= ( CONST CDirectDrawSystem& input ){} // メンバの代入を防ぐ public: // デストラクタ ~CDirectDrawSystem ( void ){} // 自身のインスタンス取得 static CDirectDrawSystem* GetInstance ( void ) { static CDirectDrawSystem drawSystem; return &drawSystem; } BOOL BeginScene ( void ); // レンダリング開始 void EndScene ( void ); // レンダリング終了 //---------------------------------------------------- // @name SetFVF // @content 頂点の型をセット // @param fvf 頂点の型 // @return none // @date 2013/7/1 //---------------------------------------------------- void SetFVF ( CONST DWORD fvf ) { // デバイスのポインタを取得 LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 頂点の型セット pd3dDevice->SetFVF( fvf ); } //---------------------------------------------------- // @name Present // @content レンダリング情報をwindowに送信 // @param none // @return none // @date 2013/7/1 //---------------------------------------------------- void Present ( void ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 描画情報送信 pd3dDevice->Present(NULL,NULL,NULL,NULL); } //---------------------------------------------------- // @name SetFillMode // @content レンダリング状態を変更(WireFrame,Point,Solid) // @param fillMode 変更したいレンダリングモード // @return none // @date 2013/7/30 //---------------------------------------------------- void SetFillMode ( CONST D3DFILLMODE fillMode ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // 描画状態の変更 pd3dDevice->SetRenderState( D3DRS_FILLMODE,fillMode ); } //---------------------------------------------------- // @name SetCallMode // @content カリングの状態を変更 // @param isCullMode // @return none // @date 2013/7/31 //---------------------------------------------------- void SetCallMode ( CONST BOOL isCullMode ) { // デバイスポインタの取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); if( isCullMode ) pd3dDevice->SetRenderState( D3DRS_CULLMODE,D3DCULL_CCW ); // カリングON} else pd3dDevice->SetRenderState( D3DRS_CULLMODE,D3DCULL_NONE ); // カリングOFF } public: //---------------------------------------------------- // @name DrawSpriteRHW // @content スプライトレンダリング(同次座標計算あり) // @param pTexture テクスチャ // @param pVertex 頂点情報 // @return none // @date 2013/7/3 // @update 2013/12/13 関数名の変更 //---------------------------------------------------- void DrawSpriteRHW ( CONST LPDIRECT3DTEXTURE9 pTexture, CONST tagTSPRITERHW* pVertex ); //---------------------------------------------------- // @name DrawSpriteRHW // @content スプライトレンダリング(同次座標計算あり) // @param pVertex 頂点情報 // @return none // @date 2013/7/4 // @update 2013/12/13 関数名の変更 //---------------------------------------------------- void DrawSpriteRHW ( CONST tagTSPRITERHW* pVertex ); //---------------------------------------------------- // @name DrawSprite // @content スプライトレンダリング(同次座標計算なし) // @param pTexture テクスチャ // @param pVertex 頂点情報 // @param pWorldMtx ワールド行列 // @return none // date 2013/12/12 //---------------------------------------------------- void DrawSprite ( CONST LPDIRECT3DTEXTURE9 pTexture,tagTSPRITE* pSpriteVertex, CONST D3DXMATRIX* pWorldMtx ); public: //---------------------------------------------------- // @name Draw3D // @content 3Dモデルレンダリング // @param pModel モデルデータ // @param pWorldMtx モデル行列 // @return none // @date 2013/7/5 //---------------------------------------------------- void Draw3D ( CResourceXFile* pModel, CONST D3DXMATRIX *pWorldMtx ); //---------------------------------------------------- // @name Draw3D // @content 3Dモデルレンダリング( textureの指定 ) // @param pModel モデルデータ // @param pWorldMtx モデル行列 // @param isTexture テクスチャのありなし // @return none // @date 2013/7/6 //---------------------------------------------------- void Draw3D ( CResourceXFile* pModel, CONST D3DXMATRIX *pWorldMtx, BOOL isTexture ); //---------------------------------------------------- // @name Draw3D // @content 3Dモデルレンダリング( 色指定 ) // @param pModel モデルデータ // @param pWorldMtx モデル行列 // @param color 色情報 // @return none // @date 2013/12/4 //---------------------------------------------------- void Draw3D ( CResourceXFile* pModel, CONST D3DXMATRIX *pWorldMtx, D3DXCOLOR* color ); public: //---------------------------------------------------- // @name Draw3DClone // @content クローン3Dモデルレンダリング( テクスチャあり ) // @param numFaces 面数 // @param pTexture テクスチャ // @param pCloneVertex クローン頂点 // @param pCloneMtx クローン行列 // @return none // @date 2013/7/10 //---------------------------------------------------- void Draw3DClone ( UINT numFaces, LPDIRECT3DTEXTURE9 pTexture, tagTORIGINALMESHVERTEX* pCloneVertex, CONST D3DXMATRIX* pCloneMtx ); //---------------------------------------------------- // @name Draw3DClone // @content クローン3Dモデルレンダリング( テクスチャなし ) // @param numFaces 面数 // @param pCloneVertex クローンの頂点情報 // @param pCloneMat クローンの行列 // @return none // @date 2013/7/12 //---------------------------------------------------- void Draw3DClone ( UINT numFaces, tagTORIGINALMESHVERTEX* pCloneVertex, CONST D3DXMATRIX* pCloneMtx ); //---------------------------------------------------- // @name DrawShape // @content 形状レンダリング // @param pWorldMtx ワールド行列 // @param pShapeMat 形状マテリアル // @aram pShapeMesh 形状メッシュ // @return none // @date 2013/7/15 //---------------------------------------------------- void DrawShape ( CONST D3DXMATRIX* pWorldMtx,CONST D3DMATERIAL9* pShapeMat, CONST LPD3DXMESH pShapeMesh ); public: //---------------------------------------------------- // @name DrawBillBoard // @content ビルボードレンダリング // @param pTexture ビルボードのテクスチャ // @param pBillBoardMtx ビルボードの行列 // @param pBillBoardVertexビルボードの頂点情報 // @return none // @date 2013/7/18 //---------------------------------------------------- void DrawBillBoard( CONST LPDIRECT3DTEXTURE9 pTexture, CONST D3DXMATRIX* pBillBoardMtx, CONST tagTBILLBORDVERTEX* pBillBoardVertex ); //---------------------------------------------------- // @name DrawParticle // @content パーティクルレンダリング // @param pTexture パーティクルのテクスチャ // @param pBillBoardMtx ビルボードの行列 // @param pBillBoardVertexビルボードの頂点情報 // @return none // @date 2013/7/19 //---------------------------------------------------- void DrawParticle ( CONST LPDIRECT3DTEXTURE9 pTexture, CONST D3DXMATRIX* pBillBoardMtx, CONST tagTBILLBORDVERTEX* pBillBoardVertex ); public: //---------------------------------------------------- // @name DrawDebugStage // @content デバッグステージレンダリング // @param numLines ライン数 // @param pDebugStageVertex デバッグステージの頂点情報 // @return none // @date 2013/8/25 //---------------------------------------------------- void DrawDebugStage ( CONST UINT numLines, CONST tagTDEBUGVERTEX* pDebugStageVertex ); }; #endif _C_DIRECTX9_DRAW_SYSTEM_H_<file_sep> #include "CMessageBar.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CMessageBar::CMessageBar( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CMessageBar::~CMessageBar( void ) { } //---------------------------------------------------- // 指定位置にバーを移動 //---------------------------------------------------- bool CMessageBar::RepositionRight( CONST float posX, CONST float speed ) { if( m_center.x >= posX ) { return true; } m_center.x += speed; this->SetVertexPos( m_center.x, m_center.y ); return false; } //---------------------------------------------------- // 指定位置にバーを移動 //---------------------------------------------------- bool CMessageBar::RepositionLeft( CONST float posX, CONST float speed ) { if( m_center.x <= posX ) { return true; } m_center.x -= speed; this->SetVertexPos( m_center.x, m_center.y ); return false; } <file_sep> #include "CPlayerManager.h" const float ConstPlayerSpeed = 0.2f; const float ConstPlayerToDiceDistanceX = 0.5f; const float ConstPlayerToDiceDistanceZ = 0.3f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CPlayerManager::CPlayerManager( void ) { m_pPlayer = new CPlayer; m_pPlayerFilePath = PLAYER_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pPlayerFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CPlayerManager::~CPlayerManager( void ) { SAFE_DELETE_ALLAY( m_pPlayer ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CPlayerManager::Init( void ) { m_pPlayer->Init(); // 当たり判定用データ作成(ダイスの↑) CDebugMode::m_pPlayerBox.CreateBox( &m_pPlayer->GetAABB()->size ); CDebugMode::m_pPlayerBox.Init(); CDebugMode::m_pPlayerBox.SetDiffuse( 0, 0, 0, 150 ); CDebugMode::m_pPlayerBox.SetAmbient( 0, 0, 255, 0 ); return true; } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CPlayerManager::Uninit( void ) { return true; } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CPlayerManager::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSprite( CResourceManager::GetInstance()->GetTexture( m_pPlayerFilePath )->Get(),m_pPlayer->GetVertex(),m_pPlayer->GetWorldMtx() ); } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CPlayerManager::Run( void ) { this->Move(); switch( m_pPlayer->GetPlayerStatus() ) { case ePlayerStatus::eOnStage: break; // ダイス消え始め中 case ePlayerStatus::eOnDiceDeleteStart: this->Down(); break; // ダイス消え中 case ePlayerStatus::eOnDiceDelete: break; // ダイス出現中 case ePlayerStatus::eOnDiceAppear: this->Up( DICE_UP_SPEED ); break; } } //---------------------------------------------------- // 移動 //---------------------------------------------------- void CPlayerManager::Move( void ) { // 前移動 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_UP ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_UP )) { this->MoveFront(); } // 後移動 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_DOWN ) ) { this->MoveBack(); } // 右移動 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_RIGHT ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_RIGHT ) ) { this->MoveRight(); } // 左移動 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_LEFT ) || CJoyStick::GetInstance()->GetPressButton( 0, XINPUT_GAMEPAD_DPAD_LEFT ) ) { this->MoveLeft(); } } //---------------------------------------------------- // 前移動 //---------------------------------------------------- void CPlayerManager::MoveFront( void ) { // ステージの一番前との判定 if( m_pPlayer->GetZPos() <= CStageBlockManager::GetInstance()->GetZSize() ) { // プレイヤーのインデックス番号取得 UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( m_pPlayer->GetXPos(), m_pPlayer->GetZPos() ); // プレイヤーの状態によって前移動の動きを変える switch( m_pPlayer->GetPlayerStatus() ) { // ダイス上 case ePlayerStatus::eOnDice: // 後ろ移動していたら前には動けない if( CDiceObjManager::GetInstance()->GetMainDice()->rollState == DICE_ROLLSTATE_BACK ) { break; } // ダイスの前の方まで移動したら if( this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ + 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // ダイスが移動中だったらプレイヤーが飛び出ないように設定 if( CDiceObjManager::GetInstance()->GetMainDice()->rollState != eDiceRollState::DICE_ROLLSTATE_NONE ) { break; } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == false || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 前にダイスがない場合はダイス移動 CDiceObjManager::GetInstance()->MoveFront(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveFront ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusStartAppear || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusDelete ) ) { // 前のダイスが出現し始めもしくは消え中だったらダイス移動 CDiceObjManager::GetInstance()->MoveFront(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveFront ); } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; // 出現し始め case ePlayerStatus::eOnDiceAppearStart: // 出現し始め中にダイスの前の方まで移動したら if( this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ + 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == false ) { // ダイスが前にない場合はステージにのせる m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex -7 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex -7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // ダイスが前にあってダイスが通常状態の場合は移動できない break; } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; // 出現中 case ePlayerStatus::eOnDiceAppear: // 出現中にダイスの前の方まで移動したら if( this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ + 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == false ) { break; } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; // 消え始め case ePlayerStatus::eOnDiceDeleteStart: // 消え始め中にダイスの前の方まで移動したら if( this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ + 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == false ) { // 動かさない break; } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; /// 消え中 case ePlayerStatus::eOnDiceDelete: // 消え中にダイスの前の方まで移動したら if( this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ + 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 前にダイスがない場合はステージに乗せる if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == false ) { m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } // 前のダイスの状態によって移動させない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { break; } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; // ステージ上にいる case ePlayerStatus::eOnStage: // プレイヤーが一番前の列にいたら移動のみ if( playerIndex <= 6 ) { m_pPlayer->MoveFront( ConstPlayerSpeed ); break; } // もし目の前にダイスがあれば移動できない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 7 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetIsDice() == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() != DICE_STATUS::e_statusStartAppear && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice()->GetStatus() != DICE_STATUS::e_statusDelete ) { if( !this->IsHitPlayerToDiceZ( ConstPlayerToDiceDistanceZ, CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 7 )->GetDice() ) ) { // 目の前にダイスがあったら動かさない break; } } m_pPlayer->MoveFront( ConstPlayerSpeed ); // 移動 break; default: break; } } } //---------------------------------------------------- // 後移動 //---------------------------------------------------- void CPlayerManager::MoveBack( void ) { // ステージの一番後ろとの判定 if( m_pPlayer->GetZPos() >= -CStageBlockManager::GetInstance()->GetZSize() ) { // プレイヤーのインデックス番号取得 UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( m_pPlayer->GetXPos(), m_pPlayer->GetZPos() ); // プレイヤーの状態によって後移動の動きを変える switch( m_pPlayer->GetPlayerStatus() ) { // ダイス上 case ePlayerStatus::eOnDice: if( CDiceObjManager::GetInstance()->GetMainDice()->rollState == DICE_ROLLSTATE_FRONT ) { break; } // ダイスの後ろまで移動したら if( this->IsHitPlayerToDiceZ ( -ConstPlayerToDiceDistanceZ + -0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // ダイスが移動中の場合は飛び出ないようにする if( CDiceObjManager::GetInstance()->GetMainDice()->rollState != eDiceRollState::DICE_ROLLSTATE_NONE ) { break; } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == false || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // ダイスが後ろにない場合はダイスを移動 CDiceObjManager::GetInstance()->MoveBack(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveBack ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusStartAppear || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusDelete ) ) { // 後ろのダイスが出現し始めもしくは消え中だったら移動可能 CDiceObjManager::GetInstance()->MoveBack(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveBack ); } } m_pPlayer->MoveBack( ConstPlayerSpeed ); // 移動 break; // 出現し始め case ePlayerStatus::eOnDiceAppearStart: // 出現し始め中にダイスの後ろの方まで移動したら if( this->IsHitPlayerToDiceZ ( -ConstPlayerToDiceDistanceZ + - 0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == false ) { // 後ろにダイスがない場合はステージにのせる m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 後ろにダイスがあって通常状態の場合は動かせない break; } } m_pPlayer->MoveBack( ConstPlayerSpeed ); // 移動 break; // 出現中 case ePlayerStatus::eOnDiceAppear: // 出現中にダイスの後ろの方まで移動したら if( this->IsHitPlayerToDiceZ ( -ConstPlayerToDiceDistanceZ + -0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // ブロックが後ろにない場合は動かないし動かせない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == false ) { break; } } m_pPlayer->MoveBack( ConstPlayerSpeed ); // 移動 break; // 消え始め case ePlayerStatus::eOnDiceDeleteStart: // 消え中にダイスの後ろの方まで移動したら if( this->IsHitPlayerToDiceZ ( -ConstPlayerToDiceDistanceZ + -0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == false ) { break; } } m_pPlayer->MoveBack( ConstPlayerSpeed ); break; // 消え中 case ePlayerStatus::eOnDiceDelete: // 消え中にダイスの後ろの方まで移動したら if( this->IsHitPlayerToDiceZ ( -ConstPlayerToDiceDistanceZ + -0.2f, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 後ろにダイスがない場合はステージにのせる if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == false ) { m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } // 後ろのダイスの状態によって移動させない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { break; } } m_pPlayer->MoveBack( ConstPlayerSpeed ); break; // ステージ上 case ePlayerStatus::eOnStage: // プレイヤーが一番後の列にいたら if( playerIndex >= 42 ) { m_pPlayer->MoveBack( ConstPlayerSpeed ); break; } // もし後ろにダイスがあれば if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 7 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetIsDice() == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() != DICE_STATUS::e_statusStartAppear && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice()->GetStatus() != DICE_STATUS::e_statusDelete ) { if( !this->IsHitPlayerToDiceZ( -ConstPlayerToDiceDistanceZ, CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 7 )->GetDice() ) ) { // 後ろにダイスがあったら動かさない break; } } // 移動 m_pPlayer->MoveBack( ConstPlayerSpeed ); break; default: break; } } } //---------------------------------------------------- // 右移動 //---------------------------------------------------- void CPlayerManager::MoveRight( void ) { // ステージの右端かどうか if( m_pPlayer->GetXPos() <= CStageBlockManager::GetInstance()->GetXSize() ) { // プレイヤーのインデックス番号取得 UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( m_pPlayer->GetXPos(), m_pPlayer->GetZPos() ); switch( m_pPlayer->GetPlayerStatus() ) { // ダイス上 case ePlayerStatus::eOnDice: if( CDiceObjManager::GetInstance()->GetMainDice()->rollState == DICE_ROLLSTATE_LEFT ) { break; } // ダイスの右の方まで移動したら判定 if( this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // ダイスが移動中の場合は飛び出さないように設定 if( CDiceObjManager::GetInstance()->GetMainDice()->rollState != eDiceRollState::DICE_ROLLSTATE_NONE ) { break; } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == false || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 右にダイスがない場合はダイス移動 CDiceObjManager::GetInstance()->MoveRight(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveRight ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusStartAppear || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusDelete ) ) { // ダイスが右にあって出現し始めもしくは消え中だったら移動可能 CDiceObjManager::GetInstance()->MoveRight(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveRight ); } } m_pPlayer->MoveRight( ConstPlayerSpeed ); // 移動 break; // 出現し始め case ePlayerStatus::eOnDiceAppearStart: // 出現し始め中にダイスの右の方まで移動したら if( this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == false ) { // 右にダイスがない場合はステージにのせる m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 右にダイスがあって通常状態の場合は動かせない break; } } m_pPlayer->MoveRight( ConstPlayerSpeed ); // 移動 break; // 出現中 case ePlayerStatus::eOnDiceAppear: // 出現中にダイスの右の方まで移動したら if( this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 右にブロックがなかったら動かないし動かせない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == false ) { break; } } m_pPlayer->MoveRight( ConstPlayerSpeed ); // 移動 break; // 消え始め case ePlayerStatus::eOnDiceDeleteStart: // 消え始め中にダイスの右の方まで移動したら if( this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == false ) { break; } } m_pPlayer->MoveRight( ConstPlayerSpeed ); // 移動 break; // 消え中 case ePlayerStatus::eOnDiceDelete: // 消え中にダイスの右の方まで移動したら if( this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 右にダイスがない場合はステージにのせる if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == false ) { m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } // 右のダイスの状態によって移動させない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { break; } } m_pPlayer->MoveRight( ConstPlayerSpeed ); // 移動 break; // ステージ上 case ePlayerStatus::eOnStage: // プレイヤーが一番右列にいたら判定しない if( ( ( playerIndex + 1 ) % 7 ) == 0 ) { m_pPlayer->MoveRight( ConstPlayerSpeed ); break; } // もし右にダイスがあれば if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetIsDice() == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() != DICE_STATUS::e_statusStartAppear && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice()->GetStatus() != DICE_STATUS::e_statusDelete ) { if( !this->IsHitPlayerToDiceX( ConstPlayerToDiceDistanceX + 1.5f, CStageBlockManager::GetInstance()->GetStageBlock( playerIndex + 1 )->GetDice() ) ) { // 右にダイスがあったら動かさない break; } } // 移動 m_pPlayer->MoveRight( ConstPlayerSpeed ); default: break; } } } //---------------------------------------------------- // 左移動 //---------------------------------------------------- void CPlayerManager::MoveLeft( void ) { // ステージの左端との判定 if( m_pPlayer->GetXPos() >= -CStageBlockManager::GetInstance()->GetXSize() ) { // プレイヤーのインデックス番号取得 UINT playerIndex = CStageBlockManager::GetInstance()->GetIndexToPlayerPos( m_pPlayer->GetXPos(), m_pPlayer->GetZPos() ); switch( m_pPlayer->GetPlayerStatus() ) { // ダイス上 case ePlayerStatus::eOnDice: if( CDiceObjManager::GetInstance()->GetMainDice()->rollState == DICE_ROLLSTATE_RIGHT ) { break; } // ダイスの左の方まで移動したら判定 if( this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // ダイスが移動中の場合は飛び出ないように設定 if( CDiceObjManager::GetInstance()->GetMainDice()->rollState != eDiceRollState::DICE_ROLLSTATE_NONE ) { break; } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == false || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 左にダイスがない場合はダイスを移動 CDiceObjManager::GetInstance()->MoveLeft(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveLeft ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == true && ( CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusStartAppear || CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusDelete ) ) { // 左のダイスが出現し始めもしくは消え中だったら移動可能 CDiceObjManager::GetInstance()->MoveLeft(); m_pPlayer->SetMoveStatus( ePlayerMoveStatus::eMoveLeft ); } } m_pPlayer->MoveLeft( ConstPlayerSpeed ); // 移動 break; // 出現し始め case ePlayerStatus::eOnDiceAppearStart: // 出現し始め中にダイスの左の方まで移動したら if( this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == false ) { // 左にダイスがない場合はステージにのせる m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } else if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { // 左にダイスがあって通常状態の場合は動かせない break; } } m_pPlayer->MoveLeft( ConstPlayerSpeed ); // 移動 break; // 出現中 case ePlayerStatus::eOnDiceAppear: // 出現中にダイスの左の方まで移動したら if( this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 左にブロックがなければ動かないし動かせない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == false ) { break; } } m_pPlayer->MoveLeft( ConstPlayerSpeed ); // 移動 break; // 消え始め case ePlayerStatus::eOnDiceDeleteStart: // 消え始め中にダイスの左の方まで移動したら if( this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == false ) { break; } } m_pPlayer->MoveLeft( ConstPlayerSpeed ); // 移動 break; // 消え中 case ePlayerStatus::eOnDiceDelete: // 消え中にダイスの左の方まで移動したら if( this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX, CDiceObjManager::GetInstance()->GetMainDice()->diceObj ) == true ) { // 左にダイスがない場合はステージに乗せる if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == false ) { m_pPlayer->SetSpritePos( m_pPlayer->GetXPos(), 0.0f, m_pPlayer->GetZPos() ); m_pPlayer->SetPlayerStatus( ePlayerStatus::eOnStage ); // ステージの上判定にする m_pDiceInfoManager->SetIsExist( false ); } // 左のダイスの状態によって移動させない if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() == DICE_STATUS::e_statusNormal ) { break; } } m_pPlayer->MoveLeft( ConstPlayerSpeed ); // 移動 break; case ePlayerStatus::eOnStage: // プレイヤーが一番左列にいたら判定しない if( playerIndex % 7 == 0 ) { m_pPlayer->MoveLeft( ConstPlayerSpeed ); break; } // もし左にダイスがあれば if( CStageBlockManager::GetInstance()->GetIsOnDice( playerIndex - 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetIsDice() == true && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() != DICE_STATUS::e_statusStartAppear && CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice()->GetStatus() != DICE_STATUS::e_statusDelete ) { if( !this->IsHitPlayerToDiceX( -ConstPlayerToDiceDistanceX + -1.5f, CStageBlockManager::GetInstance()->GetStageBlock( playerIndex - 1 )->GetDice() ) ) { // 左にダイスがあったら動かさない break; } } // 移動 m_pPlayer->MoveLeft( ConstPlayerSpeed ); default: break; } } } //---------------------------------------------------- // プレイヤーとダイスの判定(X判定) //---------------------------------------------------- bool CPlayerManager::IsHitPlayerToDiceX( CONST float distance, CDiceObj* dice ) { // 判定をずらしておく THITAABB playerAABB; ::CopyMemory( &playerAABB, m_pPlayer->GetAABB(), sizeof( THITAABB ) ); playerAABB.centerPos.x += distance; // ダイスの一定方向まで移動したら if( !CCollision::GetInstance()->IsHitAABB( &playerAABB, dice->GetAABB() ) ) { // 当たっていない状態になった return true; } // 当たっている return false; } //---------------------------------------------------- // プレイヤーとダイスの判定(Z判定) //---------------------------------------------------- bool CPlayerManager::IsHitPlayerToDiceZ( CONST float distance, CDiceObj* dice ) { // 判定をずらしておく THITAABB playerAABB; ::CopyMemory( &playerAABB, m_pPlayer->GetAABB(), sizeof( THITAABB ) ); playerAABB.centerPos.z += distance; // ダイスの一定方向まで移動したら if( !CCollision::GetInstance()->IsHitAABB( &playerAABB, dice->GetAABB() ) ) { // 当たっていない状態になった return true; } // 当たっている状態 return false; } //---------------------------------------------------- // プレイヤーの落下 //---------------------------------------------------- void CPlayerManager::Down( void ) { m_pPlayer->MoveDown( DICE_DOWN_SPEED ); } //---------------------------------------------------- // プレイヤーの上昇 //---------------------------------------------------- void CPlayerManager::Up( CONST float speed ) { m_pPlayer->MoveUp( DICE_UP_SPEED ); } //---------------------------------------------------- // カメラの情報をプレイヤーの行列にセット //---------------------------------------------------- void CPlayerManager::SetCameraToMtx( CONST D3DXMATRIX* view ) { m_pPlayer->CalcWorldMtx( ); }<file_sep> #include "CDiceObj.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDiceObj::CDiceObj( void ) { m_pAABB = new THITAABB; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDiceObj::~CDiceObj( void ) { SAFE_DELETE( m_pAABB ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CDiceObj::Init( void ) { C3DObjectAlphaBlend::Init(); D3DXMatrixIdentity( &m_rotTemp ); // 回転保存用行列を初期化 m_logPos = D3DXVECTOR3( 0.0f,0.0f,0.0f ); // 回転用保存ベクトルを初期化 m_no = 0; // 識別番号を0に設定 m_indexNo = 0; // 添え字番号を0に設定 m_size = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); m_isDice = false; // 出現フラグオフ m_status = DICE_STATUS::e_statusNone; // 出現していない状態にしておく m_beforStatus = DICE_STATUS::e_statusNone; // 前回の状態も同じ状態にしておく m_animeCnt = 0; // アニメーションカウント m_chainNo = 0; // チェイン番号を初期化 m_isChain = false; // チェインしてない状態にセット // 当たり判定の初期化 D3DXVECTOR3 aabbPos = D3DXVECTOR3( this->GetXPos(), this->GetYPos(), this->GetZPos() ); m_pAABB = CCollision::GetInstance()->SetAABB( m_pAABB, &aabbPos, &m_size ); this->InitPip(); // 上面判定用配列初期化 } //---------------------------------------------------- // 回転する前の初期化 //---------------------------------------------------- bool CDiceObj::InitRoll( void ) { m_logPos = this->GetWorldMtx()->m[3]; // 現在のワールド行列を保存 CopyRotationMatrix( &m_rotTemp, this->GetWorldMtx() ); // 回転行列を保存 return true; } //---------------------------------------------------- // 上面判定用配列の初期化 //---------------------------------------------------- bool CDiceObj::InitPip( void ) { // サイコロの上面判定配列にデータを格納 for( int i = 0; i < 7; ++ i ) { m_dicePipAllay[ i ] = i; } return true; } //---------------------------------------------------- // X回転して移動 //---------------------------------------------------- void CDiceObj::MoveX( float x, float y, float z, float rotDir, float speed ) { D3DXMATRIX transMtx,lRotMtx,wRotMtx; // 軸を中心から移動させるための行列作成 D3DXMatrixTranslation( &transMtx, x, y, z ); // 回転行列を作成 D3DXMatrixRotationZ(&lRotMtx,D3DXToRadian( speed * rotDir ) ); // x回転 // 移動行列と回転行列を混ぜる D3DXMatrixMultiply( &wRotMtx, &transMtx, &lRotMtx ); // ワールド行列にセット(中心座標を元に戻す) this->CalcWorldMtx( &m_rotTemp,&wRotMtx ); this->MoveWorldPos( m_logPos.x - x, m_logPos.y - y, m_logPos.z - z ); } //---------------------------------------------------- // Z回転して移動 //---------------------------------------------------- void CDiceObj::MoveZ( float x, float y, float z, float rotDir, float speed ) { D3DXMATRIX transMtx,lRotMtx,wRotMtx; D3DXMatrixIdentity( &transMtx ); D3DXMatrixIdentity( &lRotMtx ); D3DXMatrixIdentity( &wRotMtx ); // 軸を中心から移動させるための行列作成 D3DXMatrixTranslation( &transMtx, x, y, z ); // 回転行列を作成 D3DXMatrixRotationX(&lRotMtx,D3DXToRadian( speed * rotDir ) ); // z回転 // 移動行列と回転行列を混ぜる D3DXMatrixMultiply( &wRotMtx, &transMtx, &lRotMtx); // ワールド行列にセット(中心座標を元に戻す) this->CalcWorldMtx( &m_rotTemp, &wRotMtx ); this->MoveWorldPos( m_logPos.x - x, m_logPos.y - y, m_logPos.z - z ); } //---------------------------------------------------- // X回転のみ //---------------------------------------------------- void CDiceObj::RollX( float degree ) { D3DXMATRIX lRotMtx; this->InitRoll(); // 回転のための初期化 // 回転行列を作成 D3DXMatrixRotationX(&lRotMtx,D3DXToRadian( degree ) ); // ワールド行列にセット(中心座標を元に戻す) this->CalcWorldMtx( &m_rotTemp, &lRotMtx ); this->MoveWorldPos( m_logPos.x, m_logPos.y, m_logPos.z ); } //---------------------------------------------------- // Y回転のみ //---------------------------------------------------- void CDiceObj::RollY( float degree ) { D3DXMATRIX lRotMtx; this->InitRoll(); // 回転のための初期化 // 回転行列を作成 D3DXMatrixRotationY(&lRotMtx,D3DXToRadian( degree ) ); // ワールド行列にセット(中心座標を元に戻す) this->CalcWorldMtx( &m_rotTemp, &lRotMtx ); this->MoveWorldPos( m_logPos.x, m_logPos.y, m_logPos.z ); } //---------------------------------------------------- // Z回転のみ //---------------------------------------------------- void CDiceObj::RollZ( float degree ) { D3DXMATRIX lRotMtx; D3DXMatrixIdentity( &lRotMtx ); this->InitRoll(); // 回転のための初期化 // 回転行列を作成 D3DXMatrixRotationZ(&lRotMtx,D3DXToRadian( degree ) ); // ワールド行列にセット(中心座標を元に戻す) this->CalcWorldMtx( &m_rotTemp, &lRotMtx ); this->MoveWorldPos( m_logPos.x, m_logPos.y, m_logPos.z ); } //---------------------------------------------------- // 回転させた時に回転させた方向によって内部の目を変える //---------------------------------------------------- void CDiceObj::RollChangePip( CONST USHORT rollState ) { m_dicePipAllay[0] = m_dicePipAllay[1]; // 保存用に上面の番号保存 switch( rollState ) { // 右回転 case ROLL_RIGTH_PIP: m_dicePipAllay[1] = m_dicePipAllay[2]; m_dicePipAllay[2] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[5]; m_dicePipAllay[5] = m_dicePipAllay[0]; break; // 左回転 case ROLL_LEFT_PIP: m_dicePipAllay[1] = m_dicePipAllay[5]; m_dicePipAllay[5] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[2]; m_dicePipAllay[2] = m_dicePipAllay[0]; break; // 前回転 case ROLL_FRONT_PIP: m_dicePipAllay[1] = m_dicePipAllay[3]; m_dicePipAllay[3] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[4]; m_dicePipAllay[4] = m_dicePipAllay[0]; break; // 後回転 case ROLL_BACK_PIP: m_dicePipAllay[1] = m_dicePipAllay[4]; m_dicePipAllay[4] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[3]; m_dicePipAllay[3] = m_dicePipAllay[0]; break; // 左右180°回転 case ROLL_HALFH_PIP: m_dicePipAllay[1] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[0]; m_dicePipAllay[0] = m_dicePipAllay[2]; m_dicePipAllay[2] = m_dicePipAllay[5]; m_dicePipAllay[5] = m_dicePipAllay[0]; break; // 前後180°回転 case ROLL_HALFV_PIP: m_dicePipAllay[1] = m_dicePipAllay[6]; m_dicePipAllay[6] = m_dicePipAllay[0]; m_dicePipAllay[0] = m_dicePipAllay[3]; m_dicePipAllay[3] = m_dicePipAllay[4]; m_dicePipAllay[4] = m_dicePipAllay[0]; break; } } //---------------------------------------------------- // 上面が回転しない回転をした時の内部の目を変える //---------------------------------------------------- void CDiceObj::RollYChangePip( void ) { m_dicePipAllay[0] = m_dicePipAllay[2]; m_dicePipAllay[2] = m_dicePipAllay[4]; m_dicePipAllay[4] = m_dicePipAllay[5]; m_dicePipAllay[5] = m_dicePipAllay[3]; m_dicePipAllay[3] = m_dicePipAllay[0]; } //---------------------------------------------------- // 上面と周りの面を同時にセット //---------------------------------------------------- void CDiceObj::SetPip( CONST UINT upperFace, CONST UINT rollNum ) { this->SetUpperPip( upperFace ); this->SetAroundPip( rollNum ); } //---------------------------------------------------- // 上面をセット(1〜6) //---------------------------------------------------- void CDiceObj::SetUpperPip( CONST UINT upperFace ) { switch( upperFace ) { case 1: // 1の場合は何もしない break; case 2: this->RollZ( -90.0f ); this->RollChangePip( ROLL_RIGTH_PIP ); break; case 3: this->RollX( 90.0f ); this->RollChangePip( ROLL_FRONT_PIP ); break; case 4: this->RollX( -90.0f ); this->RollChangePip( ROLL_BACK_PIP ); break; case 5: this->RollZ( 90.0f ); this->RollChangePip( ROLL_LEFT_PIP ); break; case 6: this->RollZ( 180.0f ); this->RollChangePip( ROLL_HALFH_PIP ); break; } } //---------------------------------------------------- // 周りの面をセット(0〜3) //---------------------------------------------------- void CDiceObj::SetAroundPip( CONST UINT rollNum ) { // 回数分右回転させる for( UINT i = 0; i < rollNum; ++ i ) { this->RollY( -90.0f ); this->RollYChangePip(); } } //---------------------------------------------------- // 消滅アニメーション //---------------------------------------------------- bool CDiceObj::DownAnimation( CONST float downSpeed ) { float speed = downSpeed; // 引数の値が0より大きい場合は-1を乗算 if( speed > 0.0f ) { speed *= -1; } // 位置変更 this->MoveWorldPos( 0.0f, speed,0.0f ); // ある一定距離消えたら色を変更 if( this->GetYPos() <= -2.0 && m_status == DICE_STATUS::e_statusStartDelete ) { this->SetColor( 255,0,0,127 ); return true; } // 消えたらダイスをなくす if( this->GetYPos() <= -4.0f && m_status == DICE_STATUS::e_statusDelete ) { this->SetIsDice( false ); return true; } return false; } //---------------------------------------------------- // 出現アニメーション //---------------------------------------------------- bool CDiceObj::UpAnimation( CONST float upSpeed ) { float speed = upSpeed; // 引数の値が0より小さい場合は-1を蒸散 if( speed < 0.0f ) { speed *= -1; } // 位置情報セット this->MoveWorldPos( 0.0f, speed, 0.0f ); // ある程度出てきたら色変更 if( this->GetWorldMtx()->_42 >= -2.0f && m_status == e_statusStartAppear ) { this->SetColor( 255,255,255,255); this->SetIsDice( true ); return true; } // 出てきたら if( this->GetWorldMtx()->_42 >= 0.0f && m_status == e_statusAppear ) { return true; } return false; }<file_sep>//---------------------------------------------------- // CDiceObjManager // サイコロのオブジェクトの管理クラス // // @date 2013/11/20 // @authro T.Kawashita //---------------------------------------------------- #ifndef _C_DICE_OBJ_MANAGER_H_ #define _C_DICE_OBJ_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../GameMathSource/CDiceRandSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CCollision.h" #include "../../SceneSource/DebugScene/CDebugMode.h" #include "../../ObjectSource/GameScene/Particle/CSplitParticle.h" #include "../../ObjectSource/GameScene/CDiceObj.h" #include <list> #include "CStageBlockManager.h" #include "CChainManager.h" #include "../../PlayerSource/CPlayerManager.h" #include "../../ManagerSource/GameScene/CDiceInfoManager.h" #define MAX_DICE_NUM ( 49 ) // サイコロの最大数(ステージ数によって変化させる) #define DICE_DOWN_SPEED ( 0.005f ) // サイコロの出現と削除時のアニメの早さ #define DICE_UP_SPEED ( 0.012f ) // サイコロ出現速度 // サイコロの回転向きステータス enum eDiceRollState { DICE_ROLLSTATE_NONE, DICE_ROLLSTATE_RIGHT, DICE_ROLLSTATE_LEFT, DICE_ROLLSTATE_FRONT, DICE_ROLLSTATE_BACK, DICE_ROLLSTATE_Y }; typedef struct tagTMAINDICE { CDiceObj* diceObj; // メインのサイコロのポインタのみを保存するためのもの eDiceRollState rollState; // 回転ステータス float degree; // 回転角度 D3DXVECTOR3 halfSize; // ダイスの半分のサイズ(移動の軸移動に使う) }TMAINDICE; class CDiceObjManager { private: TMAINDICE* m_pMainDice; // メインのサイコロ CSplitParticle* m_pSplitParticle; // サイコロが動いた時のパーティクル CDiceObjManager ( void ); CDiceObjManager ( CONST CDiceObjManager& diceObjManager ){} CDiceObjManager operator= ( CONST CDiceObjManager& diceObjManager ){} public: // インスタンス取得場所 static CDiceObjManager* GetInstance( void ) { static CDiceObjManager diceObjManager; return &diceObjManager; } //---------------------------------------------------- // メインのダイスを取得 //---------------------------------------------------- TMAINDICE* GetMainDice ( void ) { return m_pMainDice; } //---------------------------------------------------- // ダイスの先頭アドレスを取得 //---------------------------------------------------- CDiceObj* GetDice ( void ) { return m_pDice; } // メンバ private: CDiceObj* m_pDice; // サイコロ LPSTR m_pResDiceFilePath; // サイコロの画像 int m_diceNum; // ダイスの数 int m_appearTime; // ダイスの出現時間管理用 CDiceInfoManager* m_pDiceInfoManager; // ダイスのインフォマネージャー public: ~CDiceObjManager ( void ); // デストラクタ public: void Draw ( CONST D3DXMATRIX* view ); // 描画 void Run ( void ); // 処理 void Init ( void ); // 初期化 void Uninit ( void ); // 終了 void Debug ( void ); // デバッグ用 // サイコロのメイン処理 public: //---------------------------------------------------- // 移動制御 //---------------------------------------------------- void Move ( void ); // 移動の遷移 void MoveRight ( void ); // 右移動 void MoveLeft ( void ); // 左移動 void MoveFront ( void ); // 前移動 void MoveBack ( void ); // 後移動 //---------------------------------------------------- // @name MoveToRoll // @content サイコロの移動+回転 // @param none // @return none // @date 2013/11/27 //---------------------------------------------------- void MoveToRoll ( void ); //---------------------------------------------------- // @name Appear // @content ダイスの出現 // @param none // @return bool 出現できたか出来なかったか // @date 2013/11/27 // @update 2013/12/3 引数の追加 //---------------------------------------------------- bool Appear ( void ); //---------------------------------------------------- // @name AppearManager // @content 出現管理 // @param none // @return none // @date 2014/2/14 //---------------------------------------------------- void AppearManager ( void ); //---------------------------------------------------- // @name Animation // @content ダイスのアニメーション // @param none // @return none // @date 2013/12/4 //---------------------------------------------------- void Animation ( void ); //---------------------------------------------------- // @name SetDiceInfoManager // @content ダイスインフォマネージャーのアドレスをセット // @param diceInfoManager ダイスインフォのマネージャーのインスタンス // @return none // @date 2014/2/10 //---------------------------------------------------- void SetDiceInfoManager ( CDiceInfoManager* diceInfoManager ) { m_pDiceInfoManager = diceInfoManager; } }; #endif _C_DICE_OBJ_MANAGER_H_<file_sep> #include "CModelViewStage.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CModelViewStage::CModelViewStage( void ) { m_pStage = new CDebugStage( 84 ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CModelViewStage::~CModelViewStage( void ) { if( m_pStage != NULL ) { delete m_pStage; m_pStage = NULL; } } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CModelViewStage::Init( void ) { m_pStage->Init( 50.0f ); } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CModelViewStage::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawDebugStage( m_pStage->GetLineNum() / 2,m_pStage->GetVertex() ); } <file_sep> //---------------------------------------------------- // GameInfo.h // ゲームの定数を格納するヘッダー // // @date 2013/5/19 // @author T.Kawashita //---------------------------------------------------- #ifdef _DEBUG #define GAME_STATUS eSceneDebug #else #define GAME_STATUS eSceneTitle #endif #define GAME_TITLE "XI[sai]-Re:make-"<file_sep> #include "CGameStageManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CGameStageManager::CGameStageManager( void ) { m_pGround = new CObjectBase; m_pResGroundFilePath = GAME_STAGE_XFILEPATH; CResourceManager::GetInstance()->LoadXFile( m_pResGroundFilePath ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CGameStageManager::~CGameStageManager( void ) { SAFE_DELETE( m_pGround ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CGameStageManager::Init( void ) { m_pGround->Init(); } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CGameStageManager::Uninit( void ) { } //---------------------------------------------------- // 更新 //---------------------------------------------------- void CGameStageManager::Run( void ) { } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CGameStageManager::Draw() { CDirectDrawSystem::GetInstance()->SetCallMode( true ); CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( m_pResGroundFilePath ) ,m_pGround->GetWorldMtx() ); } <file_sep>//---------------------------------------------------- // CGameStageManager Header // ゲームのステージの管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_GAME_STAGE_MANAGER_H_ #define _C_GAME_STAGE_MANAGER_H_ #include"CDiceObjManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/CObjectBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #define MAX_STAGE_NUM ( MAX_DICE_NUM ) class CGameStageManager { private: CObjectBase* m_pGround; // Stageの3Dオブジェクト LPSTR m_pResGroundFilePath; // Stageの3Dオブジェクト用リソース public: CGameStageManager ( void ); ~CGameStageManager ( void ); public: void Draw ( void ); void Run ( void ); void Init ( void ); void Uninit ( void ); }; #endif _C_GAME_STAGE_MANAGER_H_<file_sep> #include "../../KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CResourceManager::~CResourceManager( void ) { this->Relese(); } //---------------------------------------------------- // XFileをロードしてMapにセットする //---------------------------------------------------- bool CResourceManager::LoadXFile( CONST LPSTR resourcePath ) { // 既にロードされているかどうかチェック auto xFile = m_xFileResource.find( resourcePath ); if( xFile != m_xFileResource.end() ) { // 既にロードされているなら何もしない return false; } CResourceXFile* workXFile = new CResourceXFile; if( !workXFile->Load( resourcePath ) ) { m_xFileResource.insert( map< LPSTR, CResourceXFile* >::value_type( resourcePath, workXFile ) ); return true; } return false; } //---------------------------------------------------- // XFileをMapから取得 //---------------------------------------------------- CResourceXFile* CResourceManager::GetXFile( CONST LPSTR resourcePath ) { return m_xFileResource[resourcePath]; } //---------------------------------------------------- // TextureをロードしてMapにセットする //---------------------------------------------------- bool CResourceManager::LoadTexture( CONST LPSTR resourcePath ) { // 既にロードされているかどうかチェック auto texture = m_texturerResource.find( resourcePath ); if( texture != m_texturerResource.end() ) { // 既にロードされているなら何もしない return false; } CResourceTexture* workTexture = new CResourceTexture; if( workTexture->Load( resourcePath ) ) { m_texturerResource.insert( map< LPSTR, CResourceTexture* >::value_type( resourcePath, workTexture ) ); return true; } return false; } //---------------------------------------------------- // TextureをMapから取得 //---------------------------------------------------- CResourceTexture* CResourceManager::GetTexture( CONST LPSTR resourcePath ) { return m_texturerResource[resourcePath]; } //---------------------------------------------------- // XFontを作成してMapにセットする //---------------------------------------------------- bool CResourceManager::CreateXFont( CONST UINT xFontNo, CONST UINT width, CONST UINT height ) { // 既に作成されている番号かどうかチェック auto xFont = m_xFontResource.find( xFontNo ); if( xFont != m_xFontResource.end() ) { // 既に作成されているなら何もしない return false; } CResourceXFont* workXFont = new CResourceXFont; if( workXFont->Create( width, height ) == S_OK ) { m_xFontResource.insert( map< UINT, CResourceXFont* >::value_type( xFontNo, workXFont ) ); return true; } return false; } //---------------------------------------------------- // XFontの取得 //---------------------------------------------------- CResourceXFont* CResourceManager::GetXFont( CONST UINT xFontNo ) { return m_xFontResource[ xFontNo ]; } //---------------------------------------------------- // Mapから全件解放 //---------------------------------------------------- void CResourceManager::Relese( void ) { // XFileの解放 auto xFile = m_xFileResource.begin(); while( xFile != m_xFileResource.end() ) { SAFE_DELETE( ( *xFile ).second ); xFile ++; } // Textureの解放 auto texture = m_texturerResource.begin(); while( texture != m_texturerResource.end() ) { SAFE_DELETE( ( *texture ).second ); texture ++; } // XFontの解放 auto xFont = m_xFontResource.begin(); while( xFont != m_xFontResource.end() ) { SAFE_DELETE( ( *xFont ).second ); xFont ++; } } //---------------------------------------------------- // Mapから指定解放 //---------------------------------------------------- void CResourceManager::Relese( CONST LPSTR resourcePath ) { } <file_sep>//---------------------------------------------------- // C2DParticle // パーティクルする物体のBaseとなるクラス // // @date 2013/12/18 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_2D_PARTICLE_H_ #define _C_2D_PARTICLE_H_ #include <Windows.h> #include <d3dx9.h> #include "C2DBillBoard.h" class C2DParticle : public C2DBillBoard { private: D3DXVECTOR3 m_speed; // パーティクルの進む速度 D3DXVECTOR3 m_direct; // パーティクルの進む方向 int m_life; // 生存値 float m_rate; // 倍率 bool m_isExist; // 生存フラグ public: // コンストラクタ C2DParticle(); // デストラクタ ~C2DParticle(); public: //---------------------------------------------------- // @name LifeDown // @content ライフを下げる // @param dist 下げる量 // @return none // @date 2013/12/18 //---------------------------------------------------- void LifeDown ( CONST UINT dist ) { m_life = m_life - dist; if( m_life <= 0 ) { m_life = 0; m_isExist = false; } } //---------------------------------------------------- // @name GetExist // @content 生存フラグの取得 // @param none // @return bool 生存フラグ // @date 2014/1/28 //---------------------------------------------------- bool GetExist ( void ) { return m_isExist; } //---------------------------------------------------- // @name GetLife // @content 現在ライフを取得 // @param none // @return UINT ライフ // @date 2013/12/18 //---------------------------------------------------- CONST UINT GetLife ( void ) { return m_life; } //---------------------------------------------------- // @name SetLife // @content ライフをセット // @param life セットするライフ // @return none // @date 2013/12/18 //---------------------------------------------------- void SetLife ( CONST UINT life ) { m_life = life; } public: //---------------------------------------------------- // @name Move // @content パーティクルの移動 // @param none // @return none // @date 2013/12/18 //---------------------------------------------------- void Move ( void ); //---------------------------------------------------- // α値の計算(ライフで考えている) // 倍率を求める //---------------------------------------------------- /*void CalcAlfa ( void ) { int alfa; m_rate = (float)this->GetMaxAlfa() / (float)m_life; alfa =(int)(m_rate * this->GetLife()); this->SetAlfa( alfa ); }*/ //---------------------------------------------------- // @name SetParticle // @content パーティクルのセット // @param speed 速さ // @param dir 向き // @param life ライフのn // @return none // @date // @update //---------------------------------------------------- void SetParticle ( CONST D3DXVECTOR3* speed, CONST D3DXVECTOR3* dir, CONST UINT life ); }; #endif _C_2D_PARTICLE_H_<file_sep>//---------------------------------------------------- // CDiceInfoObj // ダイスINFO用のオブジェクト // // @date 2014/2/13 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DICE_INFO_OBJ_H_ #define _C_DICE_INFO_OBJ_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/3D/C3DObjectAlphaBlend.h" class CDiceInfoObj : public C3DObjectAlphaBlend { private: bool m_isExist; public: void SetIsExist ( bool isExist ) { m_isExist = isExist; } bool GetIsExist ( void ) { return m_isExist; } public: CDiceInfoObj ( void ); // コンストラクタ ~CDiceInfoObj ( void ); // デストラクタ public: bool Init ( void ); // 初期化 void CopyRotationMtx ( CONST D3DXMATRIX* worldMtx ); // 回転行列をコピーしてワールド行列にセット }; #endif _C_DICE_INFO_OBJ_H_<file_sep> #include "CSceneModelView.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneModelView::CSceneModelView( CSceneChange* changeScene ) : CSceneBase(changeScene) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneModelView::Load( void ) { m_pDirectCamera = new CDirectCamera; m_pDirectLight = new CDirectLight; m_pViewObj = new CObjectBase; CResourceManager::GetInstance()->LoadXFile( modelViewPath ); // Manager m_pModelViewBackManager = new CModelViewBackManager; m_pModelViewStage = new CModelViewStage; m_pSnowObjManager = new CSnowObj; return true; } //---------------------------------------------------- // モデルビューシーンの初期化 //---------------------------------------------------- void CSceneModelView::Initialize() { CResourceManager::GetInstance()->CreateXFont( 1, 8, 14 ); m_pDirectCamera->Init( 800,640 ); m_pDirectCamera->SetPosition( 0.0f,10.0f,-10.0f ); m_pViewObj->Init(); // Manager m_pModelViewBackManager->Init(); // 描画モードをポリゴンに変更 CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_SOLID ); // カリングON CDirectDrawSystem::GetInstance()->SetCallMode( false ); // アンビエント値更新 m_pDirectLight->SetStageAmbient( 0x88888888 ); // ライトON m_pDirectLight->Switch( true ); // テクスチャON m_isTexture = true; m_isCull = true; m_isLight = true; m_isMouseHoil = false; m_isMouse = false; m_degree = 0.0f; // モデルビューステージの初期化 m_pModelViewStage->Init(); m_eModelViewState = VIEW_NORMAL; } //---------------------------------------------------- // モデルビューシーンの終了 //---------------------------------------------------- void CSceneModelView::Finalize( void ) { SAFE_DELETE( m_pViewObj ); // 表示するモデル SAFE_DELETE( m_pDirectCamera ); SAFE_DELETE( m_pDirectLight ); SAFE_DELETE( m_pModelViewBackManager ); SAFE_DELETE( m_pModelViewStage ); SAFE_DELETE( m_pSnowObjManager ); } //---------------------------------------------------- // モデルビューシーンの処理 //---------------------------------------------------- void CSceneModelView::Run( void ) { CInputKeyboard::GetInstance()->Update(); m_pSnowObjManager->Emitter(); m_pSnowObjManager->Move(); if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_P ) ) { // m_pSplitParticle->Emitter(); } // m_pViewObj->InitMtx(); this->DrawModeChange(); this->CalcDepthCamera(); this->CalcCameraPos(); this->RotationModel(); // モデルビューワーの終了 if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_ESCAPE ) ) { mSceneChanger->ChangeScene( eSceneDebug ); } /* if( m_pModelViewBackManager->GetIsFade() ) { if( m_pModelViewBackManager->Fade() ) { mSceneChanger->ChangeScene( eSceneTitle ); CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_SOLID ); CDirectDrawSystem::GetInstance()->SetCallMode( true ); } } */ // m_pViewObj->CalcLocalMtx(); } //---------------------------------------------------- // モデルビューシーンの描画 //---------------------------------------------------- void CSceneModelView::Draw( void ) { m_pModelViewStage->Draw(); if( m_isTexture ) { CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( modelViewPath ),m_pViewObj->GetWorldMtx()); } else if( m_isTexture ) { CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( modelViewPath ),m_pViewObj->GetWorldMtx(),NULL ); } // m_pSnowObjManager->Draw( m_pDirectCamera ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 690, 5, D3DXCOLOR( 255,0,0,100 ), "ESC:Exit" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 680, 20, D3DXCOLOR( 255,0,0,100 ), "Right/Left:Rotation" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 600, 35, D3DXCOLOR( 255,0,0,100 ), "F1,F2,F3:ViewChange" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 560, 50, D3DXCOLOR( 255,0,0,100 ), "F4,F5,F6:DrawChange" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 600, 65, D3DXCOLOR( 255,0,0,100 ), "F7:CalingO N/OFF" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 580, 80, D3DXCOLOR( 255,0,0,100 ), "F8:Texture ON/OFF" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 620, 95, D3DXCOLOR( 255,0,0,100 ), "F9:Light ON/OFF" ); CResourceManager::GetInstance()->GetXFont(1)->DrawColor( 670, 110, D3DXCOLOR( 255,0,0,100 ), "F10:Initialize" ); m_pModelViewBackManager->Draw(); } //---------------------------------------------------- // 画像の更新 //---------------------------------------------------- void CSceneModelView::UpdatePict( void ) { this->Initialize(); } //---------------------------------------------------- // カメラの回転 //---------------------------------------------------- void CSceneModelView::RotationCamera( DWORD direction ) { switch( direction ) { // 左移動 case VK_LEFT: m_degree = 1.0f; m_pDirectCamera->LocalRotationQuaterY( m_degree ); break; // 右移動 case VK_RIGHT: m_degree = -1.0f; m_pDirectCamera->LocalRotationQuaterY( m_degree ); break; } } //---------------------------------------------------- // 描画モード変更 //---------------------------------------------------- void CSceneModelView::DrawModeChange( void ) { // X視点 if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F1 ) ) { m_pDirectCamera->Init(); m_pDirectCamera->SetPosition( 40.0f,0.0f,19.0f ); m_eModelViewState = VIEW_X; } // Y視点 if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F2 ) ) { m_pDirectCamera->Init(); m_pDirectCamera->SetPosition( 0.0f,40.0f,19.0 ); m_eModelViewState = VIEW_Y; } // Z視点 if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F3 ) ) { m_pDirectCamera->Init(); m_pDirectCamera->SetPosition( 0.0f,0.0f,-20.0f ); m_eModelViewState = VIEW_Z; } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F4 ) ) { // 点描画 CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_POINT ); } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F5 ) ) { // ワイヤーフレーム CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_WIREFRAME ); } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F6 ) ) { // ポリゴン描画 CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_SOLID ); } // カリングON OFF 切り替え if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F7 ) ) { m_isCull ^= true; CDirectDrawSystem::GetInstance()->SetCallMode( m_isCull ); } // テクスチャON OFF切り替え if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F8 ) ) { m_isTexture ^= true; } // ライトのON OFF切り替え if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F9 ) ) { m_isLight ^= true; m_pDirectLight->Switch( m_isLight ); } // 左回転 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_LEFT ) ) { this->RotationCamera( VK_LEFT ); } // 右回転 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_RIGHT ) ) { this->RotationCamera( VK_RIGHT ); } // クリア if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F10 ) ) { CDirectDrawSystem::GetInstance()->SetFillMode( D3DFILL_SOLID ); CDirectDrawSystem::GetInstance()->SetCallMode( true ); m_isTexture = true; this->Initialize(); } // テクスチャの切り替え /* if( pInput->GetKeyboardTrigger( DIK_RIGHT ) ) { if( m_viewNo < MODEL_CNT - 1 ) { m_viewNo ++; this->UpdatePict(); } } if( pInput->GetKeyboardTrigger( DIK_LEFT ) ) { if( m_viewNo > 0 ) { m_viewNo --; this->UpdatePict(); } } */ } //---------------------------------------------------- // カメラの奥行調整 //---------------------------------------------------- void CSceneModelView::CalcDepthCamera( void ) { // ホイールの上下で奥行を調整 /* if( CInputMouse::GetInstance()->GetWheelRotation() >= 1 ) { switch( m_eModelViewState ) { case VIEW_X: m_pDirectCamera->SetPosition( -CAMERA_DEPTH,0.0f,0.0f ); m_pDirectCamera->SetAt( -CAMERA_DEPTH,0.0f,0.0f ); break; case VIEW_Y: m_pDirectCamera->SetPosition( 0.0f,-CAMERA_DEPTH,0.0f ); m_pDirectCamera->SetAt( 0.0f,-CAMERA_DEPTH,0.0f ); break; case VIEW_Z: m_pDirectCamera->SetPosition( 0.0f,0.0f,CAMERA_DEPTH ); m_pDirectCamera->SetAt( 0.0f,0.0f,CAMERA_DEPTH ); break; case VIEW_NORMAL: m_pDirectCamera->SetPosition( 0.0f,0.0f,CAMERA_DEPTH ); m_pDirectCamera->SetAt( 0.0f,0.0f,CAMERA_DEPTH ); break; } } if( CInputMouse::GetInstance()->GetWheelRotation() <= -1 ) { switch( m_eModelViewState ) { case VIEW_X: m_pDirectCamera->SetPosition( CAMERA_DEPTH,0.0f,0.0f); m_pDirectCamera->SetAt( CAMERA_DEPTH,0.0f,0.0f ); break; case VIEW_Y: m_pDirectCamera->SetPosition( 0.0f,CAMERA_DEPTH,0.0f ); m_pDirectCamera->SetAt( 0.0f,CAMERA_DEPTH,0.0f ); break; case VIEW_Z: m_pDirectCamera->SetPosition( 0.0f,0.0f,-CAMERA_DEPTH ); m_pDirectCamera->SetAt( 0.0f,0.0f,-CAMERA_DEPTH ); break; case VIEW_NORMAL: m_pDirectCamera->SetPosition( 0.0f,0.0f,-CAMERA_DEPTH ); m_pDirectCamera->SetAt( 0.0f,0.0f,-CAMERA_DEPTH ); break; } } */ } //---------------------------------------------------- // カメラの位置調整 //---------------------------------------------------- void CSceneModelView::CalcCameraPos( void ) { static long nowMouseXpos,nowMouseYpos; static long oldMouseXpos,oldMouseYpos; static long mouseXpos,mouseYpos; // カメラ位置の移動 /* if( CInputMouse::GetInstance()->GetTriggerButton() && !m_isMouseHoil ) { nowMouseXpos = pInput->GetMouseXpos(); nowMouseYpos = pInput->GetMouseYpos(); m_isMouseHoil = true; } if( m_isMouseHoil ) { oldMouseXpos = nowMouseXpos; oldMouseYpos = nowMouseYpos; nowMouseXpos = pInput->GetMouseXpos(); nowMouseYpos = pInput->GetMouseYpos(); mouseXpos = nowMouseXpos - oldMouseXpos; mouseYpos = nowMouseYpos - oldMouseYpos; switch( m_eModelViewState ) { case VIEW_X: m_pDirectCamera->SetAt( 0.0f,mouseYpos * 0.1f,mouseXpos * - 0.1f ); m_pDirectCamera->SetPosition( 0.0f,mouseYpos * 0.1f,mouseXpos * -0.1f ); break; case VIEW_Y: m_pDirectCamera->SetAt( mouseXpos * -0.1f,0.0f,mouseYpos * 0.1f ); m_pDirectCamera->SetPosition( mouseXpos * -0.1f,0.0f,mouseYpos * 0.1f ); break; case VIEW_Z: m_pDirectCamera->SetAt( mouseXpos * -0.1f, mouseYpos * 0.1f,0.0f ); m_pDirectCamera->SetPosition( mouseXpos * -0.1f, mouseYpos * 0.1f,0.0f ); break; case VIEW_NORMAL: m_pDirectCamera->SetAt( mouseXpos * 0.1f, mouseYpos * -0.1f,0.0f ); m_pDirectCamera->SetPosition( mouseXpos * 0.1f, mouseYpos * -0.1f,0.0f ); break; } } // 離されたら if( pInput->GetMouseCenterRelease() && m_isMouseHoil ) { m_isMouseHoil = false; } */ } //---------------------------------------------------- // モデルの回転 //---------------------------------------------------- void CSceneModelView::RotationModel( void ) { static long oldXpos,oldYpos,oldZpos; static long nowXpos,nowYpos,nowZpos; static long mouseXpos,mouseYpos,mouseZpos; /* if( pInput->GetMouseLeftTrigger() || pInput->GetMouseRightTrigger() && !m_isMouse ) { nowXpos = pInput->GetMouseXpos(); nowYpos = pInput->GetMouseYpos(); m_isMouse = true; } if( m_isMouse ) { oldXpos = nowXpos; oldYpos = nowYpos; nowXpos = pInput->GetMouseXpos(); nowYpos = pInput->GetMouseYpos(); mouseXpos = nowXpos - oldXpos; mouseYpos = nowYpos - oldYpos; if( mouseXpos != 0 || mouseYpos != 0 ) { m_pViewObj->RotationX( (float)mouseXpos ); m_pViewObj->RotationY( (float)mouseYpos ); switch( m_eModelViewState ) { case VIEW_X: m_pViewObj->CalcRotation( 0.0f, -mouseXpos * 0.01f,-mouseYpos* 0.01f ); break; case VIEW_Y: m_pViewObj->CalcRotation( -mouseYpos * 0.01f ,0.0f,-mouseXpos * 0.01f ); break; case VIEW_Z: m_pViewObj->CalcRotation( -mouseYpos* 0.01f, -mouseXpos * 0.01f,0.0f ); break; case VIEW_NORMAL: m_pViewObj->CalcRotation( -mouseYpos* 0.01f, -mouseXpos * 0.01f,0.0f ); break; } } } if( pInput->GetMouseLeftRelease() || pInput->GetMouseRightRelease() ) { m_isMouse = false; } */ }<file_sep>//---------------------------------------------------- // C2DSpriteAlphaBlend // αブレンドする2DObjectのためのもの // // @date 2013/8/15 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_GRAPHICS_2D_ALPHABLEND_H_ #define _C_GRAPHICS_2D_ALPHABLEND_H_ #include "C2DSpriteRHW.h" //---------------------------------------------------- // フェードのステータス //---------------------------------------------------- enum eFadeState { FADE_IN, FADE_OUT, FADE_STOP }; class C2DSpriteAlphaBlend : public C2DSpriteRHW { private: eFadeState m_eFadeState; public: C2DSpriteAlphaBlend ( void ); C2DSpriteAlphaBlend ( eFadeState fadeState ); virtual ~C2DSpriteAlphaBlend ( void ); public: //---------------------------------------------------- // @name Fade // @content FadeInとFadeOutを繰り返し行う(永久的) // @param alpha 0 〜 255 の範囲 // @return none // @date 2013/8/15 //---------------------------------------------------- void Fade ( CONST USHORT alpha ); //---------------------------------------------------- // @name Fade // @content FadeInとFadeOutを繰り返し行う(永久的・範囲指定) // @param maxAlpha αの最大 // @param minAlpha αの最少 // @param alpha αを増減させる量 // @return none // @date 2013/8/15 //---------------------------------------------------- void Fade ( CONST USHORT maxAlpha, CONST USHORT minAlpha, CONST USHORT alpha ); //---------------------------------------------------- // @name Fade // @content FadeInとFadeoutを繰り返し行う(永久的・止める値指定) // @param maxAlpha αの最大 // @param minAlpha αの最少 // @param alpha αを増減させる量 // @param stopCnt 止める値 // @return none // @date 2013/8/16 //---------------------------------------------------- void Fade ( CONST USHORT maxAlpha, CONST USHORT minAlpha, CONST USHORT alpha, CONST USHORT stopCnt ); //---------------------------------------------------- // @name FadeIn // @content フェードインのみ // @param subAlpha 減らす量 // @return none // @date 2013/8//16 //---------------------------------------------------- bool FadeIn ( CONST USHORT subAlpha ); //---------------------------------------------------- // @name FadeIn // @content フェードインのみ(どこまで減らすかを指定) // @param subAlpha 減らす量 // @param minAlpha 減らす範囲 // @return none // @date 2013/8/16 //---------------------------------------------------- bool FadeIn ( CONST USHORT subAlpha, CONST USHORT minAlpha ); //---------------------------------------------------- // @name FadeOut // @content フェードアウトのみ // @param addAlpha 増やす量 // @return none // @date 2013/8/16 //---------------------------------------------------- bool FadeOut ( CONST USHORT addAlpha ); //---------------------------------------------------- // @name FadeOut // @content フェードアウトのみ(どこまで増やすかを指定) // @param addAlpha 増やす量 // @param maxAlpha 増やす範囲 // @return none // @date 2013/8/16 //---------------------------------------------------- bool FadeOut ( CONST USHORT addAlpha, CONST USHORT maxAlpha ); }; #endif _C_GRAPHICS_2D_ALPHABLEND_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C2DSpriteAlphaBlend::C2DSpriteAlphaBlend( void ) { m_eFadeState = eFadeState::FADE_IN; } //---------------------------------------------------- // コンストラクタ(フェードのステータスを設定) //---------------------------------------------------- C2DSpriteAlphaBlend::C2DSpriteAlphaBlend( eFadeState fadeState ) { m_eFadeState = fadeState; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C2DSpriteAlphaBlend::~C2DSpriteAlphaBlend( void ) { } //---------------------------------------------------- // FadeInとFadeOutを繰り返し行う(永久的) // @data none //---------------------------------------------------- void C2DSpriteAlphaBlend::Fade ( const unsigned short alpha ) { switch( m_eFadeState ) { case FADE_IN: if( FadeIn( alpha ) ) { m_eFadeState = FADE_OUT; } break; case FADE_OUT: if( FadeOut( alpha ) ) { m_eFadeState = FADE_IN; } break; } } //---------------------------------------------------- // FadeInとFadeOutを繰り替えし行う(永久的) // @data 最大と最少 //---------------------------------------------------- void C2DSpriteAlphaBlend::Fade( const unsigned short maxAlpha,const unsigned short minAlpha, const unsigned short alpha ) { switch( m_eFadeState ) { case FADE_IN: if( FadeIn( alpha,minAlpha ) ) { m_eFadeState = FADE_OUT; } break; case FADE_OUT: if( FadeOut( alpha,maxAlpha ) ) { m_eFadeState = FADE_IN; } break; } } //---------------------------------------------------- // FadeInとFadeoutを繰り返し行う(永久的) // @data max min alphaの量 止める値 // @overload //---------------------------------------------------- void C2DSpriteAlphaBlend::Fade( const unsigned short maxAlpha,const unsigned short minAlpha, const unsigned short alpha, const unsigned short stopCnt ) { switch( m_eFadeState ) { case FADE_IN: if( FadeIn( alpha,minAlpha ) ) { m_eFadeState = FADE_OUT; } break; case FADE_OUT: if( FadeIn( alpha,maxAlpha ) ) { m_eFadeState = FADE_IN; } break; case FADE_STOP: break; } } //---------------------------------------------------- // FadeIn(出現) // @data 減らす量 // @overload //---------------------------------------------------- bool C2DSpriteAlphaBlend::FadeIn( const unsigned short subAlpha ) { int alpha; alpha = this->GetAlpha(); if( alpha > 0 ) { alpha = alpha - subAlpha; this->SetDiffuse( 255,255,255,alpha ); return false; } return true; } //---------------------------------------------------- // FadeIn(範囲指定で出現) // @data 減らす量 減らす最大値 // @overload //---------------------------------------------------- bool C2DSpriteAlphaBlend::FadeIn( const unsigned short subAlpha, const unsigned short minAlpha ) { int alpha; alpha = this->GetAlpha(); if( alpha > minAlpha ) { alpha = alpha - subAlpha; this->SetDiffuse( 255,255,255,alpha ); return false; } return true; } //---------------------------------------------------- // FadeOut(消滅) // @data 増やす量 // @overload //---------------------------------------------------- bool C2DSpriteAlphaBlend::FadeOut( const unsigned short addAlpha ) { int alpha; alpha = this->GetAlpha(); if( alpha < 255 ) { alpha = alpha + addAlpha; this->SetDiffuse( 0,0,0,alpha ); return false; } return true; } //---------------------------------------------------- // FadeOut(範囲指定で消滅) // @data 増やす量 増やす最大値 // @overload //---------------------------------------------------- bool C2DSpriteAlphaBlend::FadeOut( const unsigned short addAlpha, const unsigned short maxAlpha ) { int alpha; alpha = this->GetAlpha(); if( alpha < maxAlpha ) { alpha = alpha + addAlpha; this->SetDiffuse( 255,255,255,alpha ); return false; } return true; } <file_sep>//---------------------------------------------------- // CGraphicsAnime Header // アニメーションのモデル // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_GRAPHICS_ANIME_H_ #define _C_GRAPHICS_ANIME_H_ #include "CDirectGraphics3DBase.h" //---------------------------------------------------- // 体のパーツ //---------------------------------------------------- enum { HIP, BODY, HEAD, ARMR0, ARML0, LEGR0, LEGL0, ARMR1, ARML1, LEGR1, LEGL1, PARTSMAX }; //---------------------------------------------------- // 体の構造体 //---------------------------------------------------- struct _3DObjectInitData { int parentObjectNo; int ModelNo; }; class CGraphicsAnime : public CDirectGraphics3DBase { private: D3DVECTOR m_initPos; _3DObjectInitData m_objData; public: CGraphicsAnime ( void ){} virtual ~CGraphicsAnime ( void ){} public: //---------------------------------------------------- // model番号のセット // @data modelNo // @return none //---------------------------------------------------- void SetModelNo ( CONST int modelNo ) { m_objData.ModelNo = modelNo; } //---------------------------------------------------- // 初期座標のセット // @data x y z // @return none //---------------------------------------------------- void SetInitPos ( CONST float x,CONST float y,CONST float z ) { m_initPos.x = x; m_initPos.y = y; m_initPos.z = z; this->SetWorldMtx(); } //---------------------------------------------------- // ワールド座標に初期座標のセット // @data none // @return none //---------------------------------------------------- void SetWorldMtx ( void ) { CDirectGraphics3DBase::SetWorldMtx( m_initPos.x,m_initPos.y,m_initPos.z ); CDirectGraphics3DBase::SetLocalMtx( m_initPos.x,m_initPos.y,m_initPos.z ); } //---------------------------------------------------- // 親の番号セット // @data parentNo // @return none //---------------------------------------------------- void SetParentNo ( CONST int parentNo ) { m_objData.parentObjectNo = parentNo; } //---------------------------------------------------- // 番号取得 // @data none // @return CONST int //---------------------------------------------------- CONST int GetModelNo ( void ) { return m_objData.ModelNo; } //---------------------------------------------------- // 親の番号取得 // @data none // @return CONST int //---------------------------------------------------- CONST int GetParentNo ( void ) { return m_objData.parentObjectNo; } }; #endif _C_GRAPHICS_ANIME_H_<file_sep>/************************************************************* * @file CInputKeyboard.h * @brief CInputKeyboardクラスヘッダー * @note 特になし * @author <NAME> * @date 2013/07/23 *************************************************************/ #ifndef _Include_CInputKeyboard_h_ // インクルードガード #define _Include_CInputKeyboard_h_ //------------------------------------------------------------ // インクルード //------------------------------------------------------------ #include<Windows.h> //------------------------------------------------------------ // 定数、構造体定義 //------------------------------------------------------------ enum { VK_A = 'A', VK_B, VK_C, VK_D, VK_E, VK_F, VK_G, VK_H, VK_I, VK_J, VK_K, VK_L, VK_M, VK_N, VK_O, VK_P, VK_Q, VK_R, VK_S, VK_T, VK_U, VK_V, VK_W, VK_X, VK_Y, VK_Z, }; /*!----------------------------------------------------------- // @struct TKeyboardState // @brief キーボード格納情報構造体 // @note 特になし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ typedef struct tagTInputKeyboard { BYTE m_pressState[256]; BYTE m_triggerState[256]; BYTE m_releaseState[256]; }TInputKeyboard; /*!----------------------------------------------------------- // @class CInputKeyboard // @brief キーボード入力管理クラス // @note 特になし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ class CInputKeyboard { public: /// コンストラクタ CInputKeyboard() { ZeroMemory(&m_keyboardData,sizeof(TInputKeyboard) ); }; /// デストラクタ ~CInputKeyboard(){}; /*!----------------------------------------------------------- // @brief シングルトンによる実体呼び出し // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ static CInputKeyboard* GetInstance() { static CInputKeyboard singleton; return &singleton; } /*!----------------------------------------------------------- // @brief キーボードの状態更新メソッド // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ void Update() { BYTE keyLogState[MAX_KEY_CODE]; //過去のキー情報をバーストコピー memcpy(keyLogState,m_keyboardData.m_pressState,sizeof(BYTE)*MAX_KEY_CODE); ZeroMemory(m_keyboardData.m_pressState,sizeof(BYTE)*MAX_KEY_CODE); //キーボードの入力状態を取得 GetKeyboardState(m_keyboardData.m_pressState); //全キー情報チェック for(int i=0;i<MAX_KEY_CODE;i++) { //トリガー、リリースの判定 m_keyboardData.m_pressState[i] = m_keyboardData.m_pressState[i]&0x80; m_keyboardData.m_triggerState[i] = (m_keyboardData.m_pressState[i] ^ keyLogState[i]) & m_keyboardData.m_pressState[i]; m_keyboardData.m_releaseState[i] = (m_keyboardData.m_pressState[i] ^ keyLogState[i]) & keyLogState[i]; } } /*!----------------------------------------------------------- // @brief プレスキー取得 // @note 特になし // @param[in] keyCode キーコード // @return なし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ BYTE GetPressKeyState(BYTE keyCode) { return m_keyboardData.m_pressState[keyCode]; } /*!----------------------------------------------------------- // @brief トリガーキー取得 // @note 特になし // @param[in] keyCode キーコード // @return なし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ BYTE GetTriggerKeyState(BYTE keyCode) { return m_keyboardData.m_triggerState[keyCode]; } /*!----------------------------------------------------------- // @brief リリースキー取得 // @note 特になし // @param[in] keyCode キーコード // @return なし // @author <NAME> // @date 2013/07/23 ------------------------------------------------------------*/ BYTE GetReleaseKeyState(BYTE keyCode) { return m_keyboardData.m_releaseState[keyCode]; } private: /// 定義 static const int MAX_KEY_CODE = 256; private: /// キーボード格納情報 TInputKeyboard m_keyboardData; }; //シングルトン定義 inline CInputKeyboard* sInputKeyManager() { return CInputKeyboard::GetInstance(); } #endif // _Include_CInputKeyboard_h_<file_sep>//---------------------------------------------------- // CStageBlockObj // ステージのブロックオブジェクト // // @date 2013/11/29 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_STAGE_BLOCK_OBJ_ #define _C_STAGE_BLOCK_OBJ_ #include "CDiceObj.h" class CStageBlockObj { private: int m_no; D3DXVECTOR3 m_pos; CDiceObj* m_pDice; bool m_isOnDice; bool m_isOnPlayer; public: // コンストラクタ CStageBlockObj ( void ); // デストラクタ ~CStageBlockObj ( void ); // 初期化 bool Init ( void ); public: //---------------------------------------------------- // 位置情報を取得 //---------------------------------------------------- D3DXVECTOR3* GetPosition ( void ) { return &m_pos; } //---------------------------------------------------- // ステージのブロックに乗っているダイスの取得 //---------------------------------------------------- CDiceObj* GetDice ( void ) { return m_pDice; } //---------------------------------------------------- // @name CheckOnDice // @content ダイスがあるかどうか取得 // @param none // @return bool あるかないか // @date 2013/11/29 //---------------------------------------------------- bool CheckOnDice ( void ); //---------------------------------------------------- // @name CheckOnPlayer // @content プレイヤーが乗っているかどうか取得 // @param none // @return bool 乗っているかどうか // @date 2014/1/30 //---------------------------------------------------- bool CheckOnPlayer ( void ); //---------------------------------------------------- // @name SetPostion // @content ブロックのポジションをセット // @param x X座標 // @param y Y座標 // @param z Z座標 // @return none // @date 2013/11/29 //---------------------------------------------------- void SetPosition ( float x, float y, float z ); //---------------------------------------------------- // @name SetDice // @content ダイスをセット // @param dice セットしたいダイスのオブジェクトのポインタ // @return none // @date 2013/11/29 //---------------------------------------------------- void SetDice ( CDiceObj* dice ); //---------------------------------------------------- // @name SetNo // @content 番号のセット // @param no セットしたい番号 // @return none // @date 2013/12/2 //---------------------------------------------------- void SetNo ( CONST UINT no ); //---------------------------------------------------- // @name SetIsOnDice // @content ダイスが乗っているかどうかのフラグをセット // @param isDice フラグ // @return none // @date 2013/12/2 //---------------------------------------------------- void SetIsOnDice ( CONST bool isDice ); //---------------------------------------------------- // @name SetIsOnPlayer // @content プレイヤーが乗っているかどうかのフラグをセット // @param isPlayer フラグ // @return none // @date 2014/1/30 //---------------------------------------------------- void SetIsOnPlayer ( CONST bool isPlayer ); //---------------------------------------------------- // @name Draw // @content ステージのブロックを描画 // @param none // @return none // @date 2013/12/2 //---------------------------------------------------- void Draw ( void ); }; #endif _C_STAGE_BLOCK_OBJ_<file_sep>//---------------------------------------------------- // CMessageBar // メッセージバーのオブジェクト // // @date 2014/2/5 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MESSAGE_BAR_H_ #define _C_MESSAGE_BAR_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" class CMessageBar : public C2DSpriteAlphaBlend { public: CMessageBar ( void ); virtual ~CMessageBar ( void ); public: //---------------------------------------------------- // @name RepositionRight // @content ある位置にバーを移動させる(右) // @param posX 移動させたい位置(中心) // @param speed 速さ // @return bool 移動し終わったかどうか // @date 2014/2/5 //---------------------------------------------------- bool RepositionRight ( CONST float posX, CONST float speed ); //---------------------------------------------------- // @name RepositionLeft // @content ある位置にバーを移動させる(左) // @param posX 移動させたい位置(中心) // @param speed 速さ // @return none // @date 2014/2/5 //---------------------------------------------------- bool RepositionLeft( CONST float posX, CONST float speed ); }; #endif _C_MESSAGE_BAR_H_<file_sep> #include "CSplitParticle.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSplitParticle::CSplitParticle( void ) { m_pSplitPartcle = new C2DParticle[50]; for( int i = 0; i < 50; ++ i ) { m_pSplitPartcle[i].SetSprite( &D3DXVECTOR3( 1.0f, 1.0f, 1.0f ), &D3DXVECTOR3( 2.0f, 2.0f, 0.0f ) ); } m_pResParticle = PARTICLE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResParticle ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSplitParticle::~CSplitParticle( void ) { SAFE_DELETE_ALLAY( m_pSplitPartcle ); } //---------------------------------------------------- // エミッター //---------------------------------------------------- void CSplitParticle::Emitter( CONST float xPos, CONST float yPos, CONST float zPos ) { // 速度と方向 D3DXVECTOR3 speed,dir; speed.x = 0.08f; speed.y = 0.0f; speed.z = 0.08f; for( int i = 0; i < 50; ++ i ) { dir.x = (float)CXorShift::GetInstance()->GetRandom( -10, 10 ) / 100; dir.y = 0.0f; dir.z = (float)CXorShift::GetInstance()->GetRandom( -10, 10 ) / 100; m_pSplitPartcle[i].SetSpritePos( xPos, 0.0f, zPos ); m_pSplitPartcle[i].SetParticle( &speed, &dir, 70 ); m_pSplitPartcle[i].SetDiffuse( 255, 255, 0, 100 ); } } //---------------------------------------------------- // 移動 //---------------------------------------------------- void CSplitParticle::Move( void ) { for( int i = 0; i < 50; ++ i ) { if( m_pSplitPartcle[i].GetExist() == true ) { m_pSplitPartcle[i].Move(); m_pSplitPartcle[i].LifeDown( 1 ); } } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSplitParticle::Draw( CONST D3DXMATRIX* view ) { for( int i = 0; i < 50; ++ i ) { if( m_pSplitPartcle[i].GetExist() == true ) { m_pSplitPartcle[i].CalcWorldMtx( view ); CDirectDrawSystem::GetInstance()->DrawSprite( CResourceManager::GetInstance()->GetTexture( m_pResParticle )->Get(), m_pSplitPartcle[i].GetVertex(), m_pSplitPartcle[i].GetWorldMtx() ); } } }<file_sep>//---------------------------------------------------- // CObjectBase // Objectの基底クラス(2D 3D両方対応) // // @date 2013/12/12 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_OBJECT_BASE_H_ #define _C_OBJECT_BASE_H_ #include <d3dx9.h> class CObjectBase { protected: D3DXMATRIX m_worldMtx; // ワールド座標 public: // コンストラクタ CObjectBase ( void ) { D3DXMatrixIdentity( &m_worldMtx ); } // デストラクタ virtual ~CObjectBase ( void ){} public: //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ) { this->InitWorldMtx(); return true; } //---------------------------------------------------- // ワールド行列の取得 //---------------------------------------------------- CONST D3DXMATRIX* GetWorldMtx ( void ) { return &m_worldMtx; } //---------------------------------------------------- // ワールド行列を単位行列化 //---------------------------------------------------- void InitWorldMtx ( void ) { D3DXMatrixIdentity( &m_worldMtx ); } //---------------------------------------------------- // @name SetWorldMtx // @content ワールド行列のセット // @param pInMtx セットしたいワールド行列 // @return none // @date 2014/1/27 //---------------------------------------------------- void SetWorldMtx ( CONST D3DXMATRIX* pInMtx ) { memcpy( &m_worldMtx, pInMtx, sizeof(D3DXMATRIX) ); } //---------------------------------------------------- // @name SetWorldPos // @content ワールド座標のセット // @param xPos X座標 // @param yPos Y座標 // @param zPos Z座標 // @return none // @date 2013/12/12 //---------------------------------------------------- void SetWorldPos ( CONST float xPos, CONST float yPos, CONST float zPos ) { m_worldMtx._41 = xPos; m_worldMtx._42 = yPos; m_worldMtx._43 = zPos; } //---------------------------------------------------- // @name SetWorldPos // @content ワールド座標のセット // @param vec 座標を指定したベクトル // @return none // @date 2013/12/18 //---------------------------------------------------- void SetWorldPos ( CONST D3DXVECTOR3* vec ) { m_worldMtx._41 = vec->x; m_worldMtx._42 = vec->y; m_worldMtx._43 = vec->z; } //---------------------------------------------------- // @name SetWorldPos // @content ワールド座標のセット // @param mtx ワールド座標行列 // @return none // @date 2014/1/17 //---------------------------------------------------- void SetWorldPos ( CONST D3DXMATRIX* mtx ) { m_worldMtx._41 = mtx->_41; m_worldMtx._42 = mtx->_42; m_worldMtx._43 = mtx->_43; } //---------------------------------------------------- // @name CalcWorldMtx // @content 2つの行列を混ぜてワールド座標行列に変換 // @param mtx1 行列1 // @param mtx2 行列2 // @return none // @date 2013/12/12 //---------------------------------------------------- void CalcWorldMtx ( CONST D3DXMATRIX* mtx1, CONST D3DXMATRIX* mtx2 ) { D3DXMatrixMultiply( &m_worldMtx, mtx1, mtx2 ); } //---------------------------------------------------- // @name MoveWorldPos // @content ベクトルを指定してワールド座標を移動 // @param vec ベクトル // @return none // @date 2013/12/12 //---------------------------------------------------- void MoveWorldPos ( CONST D3DXVECTOR3* vec ) { m_worldMtx._41 += vec->x; m_worldMtx._42 += vec->y; m_worldMtx._43 += vec->z; } //---------------------------------------------------- // @name MoveWorldPos // @content 座標を指定してワールド座標を移動 // @param x 足すX座標量 // @param y 足すY座標量 // @param z 足すZ座標量 // @return none // @date 2013/12/12 //---------------------------------------------------- void MoveWorldPos ( CONST float x, CONST float y, CONST float z ) { m_worldMtx._41 += x; m_worldMtx._42 += y; m_worldMtx._43 += z; } //---------------------------------------------------- // 座標の取得 //---------------------------------------------------- CONST float GetXPos( void ) { return m_worldMtx._41; } CONST float GetYPos( void ) { return m_worldMtx._42; } CONST float GetZPos( void ) { return m_worldMtx._43; } }; #endif _C_OBJECT_BASE_H_<file_sep>//---------------------------------------------------- // CResourceXFile // Xファイルリソース // // @date 2013/8/3 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_RESOURCE_XFILE_H_ #define _C_RESOURCE_XFILE_H_ #include <d3dx9.h> #include "../DirectX9Header/CDirectX9FrameWork.h" #include "../UtilityHeader/Macro.hpp" #include "../DebugHeader/CDebugConsole.hpp" class CResourceXFile { private: LPD3DXMESH m_pMesh; // メッシュ格納場所 DWORD m_materialsCount; // メッシュのマテリアル情報の数(32bit符号なし整数) LPD3DXBUFFER m_pMaterialsBuffer; // マテリアル情報の取得場所 LPDIRECT3DTEXTURE9 *m_pMeshTexture; // テクスチャ格納場所 D3DMATERIAL9 *m_pMeshMaterials; // 個々のマテリアル情報 public: CResourceXFile ( void ); virtual ~CResourceXFile ( void ); public: HRESULT SetMaterials ( void ); // マテリアル設定関数 HRESULT Load ( CONST LPSTR filePath ); // Xファイルロード関数 void Destroy ( void ); // Xファイル情報解放関数 public: //---------------------------------------------------- // マテリアルの情報の数取得 //---------------------------------------------------- CONST DWORD GetMaterialCount( void ) { return m_materialsCount; } //---------------------------------------------------- // 個々のマテリアル情報取得 //---------------------------------------------------- CONST D3DMATERIAL9* GetMeshMaterial ( void ) { return m_pMeshMaterials; } //---------------------------------------------------- // テクスチャ情報取得 //---------------------------------------------------- CONST LPDIRECT3DTEXTURE9* GetMeshTexture ( void ) { return m_pMeshTexture; } //---------------------------------------------------- // メッシュ情報取得 //---------------------------------------------------- CONST LPD3DXMESH GetMesh ( void ) { return m_pMesh; } }; #endif _C_RESOURCE_XFILE_H_<file_sep> #include "CSpaceParticle.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSpaceParticle::CSpaceParticle( void ) { m_pRand = new CRandSystem; m_pSpaceParticle = new CParticle[100]; m_pSpacePatricleFilePath = PARTICLE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pSpacePatricleFilePath ); m_isSpaceParticle = false; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSpaceParticle::~CSpaceParticle( void ) { if( m_pRand != NULL ) { delete m_pRand; m_pRand = NULL; } if( m_pSpaceParticle != NULL ) { delete[] m_pSpaceParticle; m_pSpaceParticle = NULL; } } //---------------------------------------------------- // エミッター //---------------------------------------------------- void CSpaceParticle::Emitter( void ) { if( m_isSpaceParticle == false ) { m_isSpaceParticle = true; m_spaceCnt = 100; int x,y,z; x = m_pRand->GetRand( 150,150,true ); y = m_pRand->GetRand(80,30 ); z = m_pRand->GetRand( 250,350 ); for( int i = 0; i < 100; ++ i ) { m_pSpaceParticle[i].SetLife( 1000 ); m_pSpaceParticle[i].SetPosition( (float)x,(float)y,(float)z ); m_pSpaceParticle[i].SetBillboard( 7.0f,D3DCOLOR_ARGB( 200,180,180,0 ) ); m_pSpaceParticle[i].SetParticle( m_pRand->GetRand(1.0f),m_pRand->GetRand(1.0f),m_pRand->GetRand(1.0f),m_pRand->GetRand(1.0f),m_pRand->GetRand(1.0f),m_pRand->GetRand(1.0f)); } } } //---------------------------------------------------- // 移動 //---------------------------------------------------- void CSpaceParticle::Move( void ) { for( int i = 0; i < 100; ++ i ) { if( m_pSpaceParticle[i].GetLife() > 0 ) { m_pSpaceParticle[i].Move(); m_pSpaceParticle[i].LifeDown( m_pRand->GetRand( 1,5 ) ); m_pSpaceParticle[i].SetDiffuse( m_pSpaceParticle[i].GetAlfa() - 2); if( m_pSpaceParticle[i].GetAlfa() <= 0 ) { m_pSpaceParticle[i].SetLife( 0 ); m_spaceCnt --; } } } if( m_spaceCnt <= 0 ) { m_isSpaceParticle = false; } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSpaceParticle::Draw( CDirectCamera* directCamera ) { for( int i = 0; i < 100; ++ i ) { if( m_pSpaceParticle[i].GetLife() > 0 ) { directCamera->SetBillBoardMtx( m_pSpaceParticle[i].GetMat(), m_pSpaceParticle[i].GetPos() ); CDirectDrawSystem::GetInstance()->DrawParticle( CResourceManager::GetInstance()->GetTexture(m_pSpacePatricleFilePath)->Get(),m_pSpaceParticle[i].GetMat(),m_pSpaceParticle[i].GetVertex() ); } } } <file_sep>//---------------------------------------------------- // CSceneModelView Header // モデルビューワーのシーン // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_MODELVIEW_H_ #define _C_SCENE_MODELVIEW_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputMouse.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Light.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../ObjectSource/GameScene/Particle/CSnowObj.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../ManagerSource/ModelViewScene/CModelViewBackManager.h" #include "../../ManagerSource/ModelViewScene/CModelViewStage.h" #define MODEL_CNT (3) #define CAMERA_DEPTH ( 3.0f ) enum ModelViewState { VIEW_X, VIEW_Y, VIEW_Z, VIEW_NORMAL }; class CSceneModelView : public CSceneBase { private: CDirectCamera* m_pDirectCamera; CDirectLight* m_pDirectLight; private: CObjectBase* m_pViewObj; private: // Manager CModelViewBackManager* m_pModelViewBackManager; CModelViewStage* m_pModelViewStage; CSnowObj* m_pSnowObjManager; private: ModelViewState m_eModelViewState; bool m_isTexture; // テクスチャのフラグ bool m_isMouseHoil; // マウスホイールのフラグ bool m_isMouse; // マウスの動きのフラグ bool m_isCull; // カリングのフラグ bool m_isLight; // ライトのフラグ float m_degree; // カメラの回転角度 public: CSceneModelView ( void ){} CSceneModelView ( CSceneChange* changeScene ); virtual ~CSceneModelView ( void ){} public: void Initialize ( void ) override; void Finalize ( void ) override; void Run ( void ) override; void Draw ( void ) override; bool Load ( void ) override; public: void UpdatePict ( void ); void RotationCamera ( DWORD direction ); // カメラの回転 void DrawModeChange ( void ); // 描画モード変更 void CalcDepthCamera ( void ); // カメラの奥行調整 void CalcCameraPos ( void ); // カメラの位置調整 void RotationModel ( void ); // モデルの回転 }; #endif _C_SCENE_MODELVIEW_H_<file_sep> #include "../../KaiFrameWorkHeader/GameMathHeader/CCollision.h" //---------------------------------------------------- // 球体同士の衝突判定 //---------------------------------------------------- bool CCollision::IsHitCircle ( CONST THITCIRCLE* circle1, CONST THITCIRCLE* circle2 ) { if( pow( circle1->boxCenter.x - circle2->boxCenter.x, 2 ) + pow( circle1->boxCenter.y - circle2->boxCenter.y ,2 ) + pow( circle1->boxCenter.z - circle2->boxCenter.z, 2 ) < pow( circle1->r + circle2->r,2 ) ) { return true; } return false; } //---------------------------------------------------- // OBB構造体に値セット //---------------------------------------------------- THITOBB* CCollision::SetOBB( THITOBB* pOutOBB, CONST D3DXVECTOR3* pInLen, CONST D3DXMATRIX* pInMtx ) { // 位置座標をセット pOutOBB->position.x = pInMtx->_41; pOutOBB->position.y = pInMtx->_42; pOutOBB->position.z = pInMtx->_43; // 方向ベクトルをセット pOutOBB->normalDir[0].x = pInMtx->_11; pOutOBB->normalDir[0].y = pInMtx->_12; pOutOBB->normalDir[0].z = pInMtx->_13; pOutOBB->normalDir[1].x = pInMtx->_21; pOutOBB->normalDir[1].y = pInMtx->_22; pOutOBB->normalDir[1].z = pInMtx->_23; pOutOBB->normalDir[2].x = pInMtx->_31; pOutOBB->normalDir[2].y = pInMtx->_32; pOutOBB->normalDir[2].z = pInMtx->_33; // 軸の長さをセット pOutOBB->normalLength[0] = pInLen->x / 2; pOutOBB->normalLength[1] = pInLen->y / 2; pOutOBB->normalLength[2] = pInLen->z / 2; return pOutOBB; } //---------------------------------------------------- // AABB構造体に値セット //---------------------------------------------------- THITAABB* CCollision::SetAABB( THITAABB* pOutAABB, CONST D3DXVECTOR3* pInPos, CONST D3DXVECTOR3* pInSize ) { // 位置セット pOutAABB->centerPos.x = pInPos->x; pOutAABB->centerPos.y = pInPos->y; pOutAABB->centerPos.z = pInPos->z; // サイズセット pOutAABB->size.x = pInSize->x; pOutAABB->size.y = pInSize->y; pOutAABB->size.z = pInSize->z; // 半分のサイズセット D3DXVECTOR3 halfSize = D3DXVECTOR3( pInSize->x / 2, pInSize->y / 2, pInSize->z / 2 ); pOutAABB->halfSize.x = halfSize.x; pOutAABB->halfSize.y = halfSize.y; pOutAABB->halfSize.z = halfSize.z; return pOutAABB; } //---------------------------------------------------- // メッシュからメッシュデータ抜き出し //---------------------------------------------------- TMESHDATA* CCollision::GetMeshData( TMESHDATA* pOutMeshData, LPD3DXMESH lpMesh ) { HRESULT hr; // 頂点座標データ float* x = nullptr; float* y = nullptr; float* z = nullptr; float* pFloat; BYTE *data; LPDIRECT3DVERTEXBUFFER9 lpVertexBuff = NULL; int numVertex = 0; numVertex = lpMesh->GetNumVertices(); // 頂点数取得 lpMesh->GetVertexBuffer( &lpVertexBuff ); // 頂点バッファオブジェクトへのポインタ取得 // 頂点バッファをロック hr = lpVertexBuff->Lock( 0, 0, (void**)&data, D3DLOCK_READONLY ); if( hr == D3D_OK ) { // 頂点数分の座標格納エリア確保 x = new float[numVertex]; y = new float[numVertex]; z = new float[numVertex]; } pFloat = (float*)data; for( int i = 0; i < numVertex; ++ i ) { // 頂点を取り出す x[i] = *pFloat++; y[i] = *pFloat++; z[i] = *pFloat++; } // maxSizeとminSizeを求める for( int i = 0; i < numVertex; ++ i ) { if( pOutMeshData->minSize.x >= x[i] ) pOutMeshData->minSize.x = x[i]; if( pOutMeshData->minSize.y >= y[i] ) pOutMeshData->minSize.y = y[i]; if( pOutMeshData->minSize.z >= z[i] ) pOutMeshData->minSize.z = z[i]; if( pOutMeshData->maxSize.x <= x[i] ) pOutMeshData->maxSize.x = x[i]; if( pOutMeshData->maxSize.y <= y[i] ) pOutMeshData->maxSize.y = y[i]; if( pOutMeshData->maxSize.z <= z[i] ) pOutMeshData->maxSize.z = z[i]; } // サイズを求める D3DXVECTOR3 workMinSize = pOutMeshData->minSize; D3DXVECTOR3 workMaxSize = pOutMeshData->maxSize; if( pOutMeshData->minSize.x < 0 ) workMinSize.x = pOutMeshData->minSize.x * -1; if( pOutMeshData->minSize.y < 0 ) workMinSize.y = pOutMeshData->minSize.y * -1; if( pOutMeshData->minSize.z < 0 ) workMinSize.z = pOutMeshData->minSize.z * -1; if( pOutMeshData->maxSize.x < 0 ) workMaxSize.x = pOutMeshData->maxSize.x * -1; if( pOutMeshData->maxSize.y < 0 ) workMaxSize.y = pOutMeshData->maxSize.y * -1; if( pOutMeshData->maxSize.z < 0 ) workMaxSize.z = pOutMeshData->maxSize.z * -1; pOutMeshData->size = workMaxSize + workMinSize; // 中心座標を求める pOutMeshData->center.x = ( pOutMeshData->maxSize.x + pOutMeshData->minSize.x ) / 2; pOutMeshData->center.y = ( pOutMeshData->maxSize.y + pOutMeshData->minSize.y ) / 2; pOutMeshData->center.z = ( pOutMeshData->maxSize.z + pOutMeshData->minSize.z ) / 2; // 2点間の距離を求めて半径を求める pOutMeshData->rect = pow( pOutMeshData->maxSize.x - pOutMeshData->center.x, 2 ) + pow( pOutMeshData->maxSize.y - pOutMeshData->center.y, 2 ) + pow( pOutMeshData->maxSize.z - pOutMeshData->center.z, 2 ); pOutMeshData->rect = sqrtf( pOutMeshData->rect ); // 解放処理 delete[] z; delete[] y; delete[] x; // 頂点バッファ解放 lpVertexBuff->Unlock(); lpVertexBuff->Release(); lpVertexBuff = NULL; return pOutMeshData; } //---------------------------------------------------- // OBBによる衝突判定 //---------------------------------------------------- bool CCollision::IsHitOBB( CONST THITOBB* obb1, CONST THITOBB* obb2 ) { //ベクトルの確保(標準化ベクトル) D3DXVECTOR3 NAe1 = obb1->normalDir[0]; D3DXVECTOR3 NAe2 = obb1->normalDir[1]; D3DXVECTOR3 NAe3 = obb1->normalDir[2]; D3DXVECTOR3 NBe1 = obb2->normalDir[0]; D3DXVECTOR3 NBe2 = obb2->normalDir[1]; D3DXVECTOR3 NBe3 = obb2->normalDir[2]; //長さを考慮したベクトル確保 D3DXVECTOR3 Ae1 = NAe1 * obb1->normalLength[0]; D3DXVECTOR3 Ae2 = NAe2 * obb1->normalLength[1]; D3DXVECTOR3 Ae3 = NAe3 * obb1->normalLength[2]; D3DXVECTOR3 Be1 = NBe1 * obb2->normalLength[0]; D3DXVECTOR3 Be2 = NBe2 * obb2->normalLength[1]; D3DXVECTOR3 Be3 = NBe3 * obb2->normalLength[2]; D3DXVECTOR3 vInterval = obb1->position - obb2->position; // 分離軸:Ae1 FLOAT rA = D3DXVec3Length( &Ae1 ); FLOAT rB = this->CalcLenSegOnSeparateAxis( &NAe1,&Be1,&Be2,&Be3); FLOAT L = fabs( D3DXVec3Dot( &vInterval,&NAe1 ) ); if( L > rA + rB ) return FALSE; // 分離軸 : Ae3 rA = D3DXVec3Length( &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &NAe3, &Be1, &Be2, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &NAe3 )); if( L > rA + rB ) return false; // 分離軸 : Be1 rA = this->CalcLenSegOnSeparateAxis( &NBe1, &Ae1, &Ae2, &Ae3 ); rB = D3DXVec3Length( &Be1 ); L = fabs(D3DXVec3Dot( &vInterval, &NBe1 )); if( L > rA + rB ) return false; // 分離軸 : Be2 rA = this->CalcLenSegOnSeparateAxis( &NBe2, &Ae1, &Ae2, &Ae3 ); rB = D3DXVec3Length( &Be2 ); L = fabs(D3DXVec3Dot( &vInterval, &NBe2 )); if( L > rA + rB ) return false; // 分離軸 : Be3 rA = this->CalcLenSegOnSeparateAxis( &NBe3, &Ae1, &Ae2, &Ae3 ); rB = D3DXVec3Length( &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &NBe3 )); if( L > rA + rB ) return false; // 分離軸 : C11 D3DXVECTOR3 Cross; D3DXVec3Cross( &Cross, &NAe1, &NBe1 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae2, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be2, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C12 D3DXVec3Cross( &Cross, &NAe1, &NBe2 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae2, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C13 D3DXVec3Cross( &Cross, &NAe1, &NBe3 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae2, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be2 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C21 D3DXVec3Cross( &Cross, &NAe2, &NBe1 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be2, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C22 D3DXVec3Cross( &Cross, &NAe2, &NBe2 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C23 D3DXVec3Cross( &Cross, &NAe2, &NBe3 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae3 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be2 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C31 D3DXVec3Cross( &Cross, &NAe3, &NBe1 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae2 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be2, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C32 D3DXVec3Cross( &Cross, &NAe3, &NBe2 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae2 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be3 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離軸 : C33 D3DXVec3Cross( &Cross, &NAe3, &NBe3 ); rA = this->CalcLenSegOnSeparateAxis( &Cross, &Ae1, &Ae2 ); rB = this->CalcLenSegOnSeparateAxis( &Cross, &Be1, &Be2 ); L = fabs(D3DXVec3Dot( &vInterval, &Cross )); if( L > rA + rB ) return false; // 分離平面が存在しないので「衝突している」 return true; } //---------------------------------------------------- // AABBによる衝突判定 //---------------------------------------------------- bool CCollision::IsHitAABB( CONST THITAABB* aabb1, CONST THITAABB* aabb2 ) { if( aabb1->centerPos.x + aabb1->halfSize.x > aabb2->centerPos.x - aabb2->halfSize.x && aabb1->centerPos.x - aabb1->halfSize.x < aabb2->centerPos.x + aabb2->halfSize.x && aabb1->centerPos.y + aabb1->halfSize.y > aabb2->centerPos.y - aabb2->halfSize.y && aabb1->centerPos.y - aabb1->halfSize.y < aabb2->centerPos.y + aabb2->halfSize.y && aabb1->centerPos.z + aabb1->halfSize.z > aabb2->centerPos.z - aabb2->halfSize.z && aabb1->centerPos.z - aabb1->halfSize.z < aabb2->centerPos.z + aabb2->halfSize.z ) { // 当たっている return true; } return false; } //---------------------------------------------------- // 分離軸に投影された軸成分から投影線分長を算出 //---------------------------------------------------- float CCollision::CalcLenSegOnSeparateAxis( D3DXVECTOR3 *pSepAxis, D3DXVECTOR3 *e1, D3DXVECTOR3 *e2, D3DXVECTOR3 *e3) { // 3つの内積の絶対値の和で投影線分長を計算 // 分離軸pSepAxisは標準化されていること FLOAT r1 = fabs( D3DXVec3Dot( pSepAxis, e1 ) ); FLOAT r2 = fabs( D3DXVec3Dot( pSepAxis, e2 ) ); FLOAT r3 = e3 ? ( fabs( D3DXVec3Dot( pSepAxis, e3 ) ) ) : 0; return r1 + r2 + r3; } //---------------------------------------------------- // 平面の方程式を算出 //---------------------------------------------------- TPLANE* CCollision::CreatePlaneInfo( TPLANE* pOutPlane, CONST D3DXVECTOR3 *v1, CONST D3DXVECTOR3 *v2, CONST D3DXVECTOR3 *v3 ) { D3DXVECTOR3 v1v2; // v1とv2を結ぶベクトル D3DXVECTOR3 v1v3; // v1とv3を結ぶベクトル D3DXVECTOR3 normal; // 法線ベクトル //ベクトルを算出 D3DXVec3Subtract( &v1v2, v2, v1 ); // v1とv2を結ぶベクトル D3DXVec3Subtract( &v1v3, v3, v1 ); // v1とv3を結ぶベクトル D3DXVec3Cross( &normal, &v1v2, &v1v3 ); // 外積を求める // 平面の方程式決定 pOutPlane->a = normal.x; pOutPlane->b = normal.y; pOutPlane->c = normal.z; // 平面方程式dを計算 pOutPlane->d = -( pOutPlane->a * v1->x + pOutPlane->b * v1->y + pOutPlane->c * v1->z ); return pOutPlane; } //----------------------------------------------------- // 直線と平面の交点を求める //----------------------------------------------------- bool CCollision::LineToPlaneCross( D3DXVECTOR3* pOutCross, CONST TPLANE* plane, CONST D3DXVECTOR3* vTriPos, CONST D3DXVECTOR3* vStartPos, D3DXVECTOR3* vDir ) { D3DXVECTOR3 v1v2; // 3角形の一つの頂点と直線が通る点を結ぶベクトル D3DXVECTOR3 vNormal; // 法線ベクトル FLOAT t; // 平面の方程式から法線ベクトルを抜き取る vNormal.x = plane->a; vNormal.y = plane->b; vNormal.z = plane->c; //3角形の一つの頂点と始点を結ぶベクトルを算出 D3DXVec3Subtract( vDir, vTriPos, vStartPos ); //内積算出 FLOAT dot = D3DXVec3Dot( vDir, &vNormal ); // 内積の結果が0になっているかを判定 if(( 0.0f - FLT_EPSILON < dot ) && ( dot < 0.0f + FLT_EPSILON )) { return FALSE; } t = D3DXVec3Dot( &vNormal, &v1v2 ) / D3DXVec3Dot( vDir,&vNormal ); pOutCross->x = vStartPos->x + vDir->x * t; pOutCross->y = vStartPos->y + vDir->y * t; pOutCross->z = vStartPos->z + vDir->z * t; return TRUE; } //---------------------------------------------------- // 3角形の内部にあるかどうかを判定 //---------------------------------------------------- bool CCollision::CheckInTriangle( CONST D3DXVECTOR3* v1, CONST D3DXVECTOR3* v2, CONST D3DXVECTOR3* v3, CONST D3DXVECTOR3* pos ) { D3DXVECTOR3 v1v2,v2v3,v3v1,v1v3; // 3辺のベクトル D3DXVECTOR3 ap,bp,cp; // 内部の点とのベクトル D3DXVECTOR3 vNormal; // 3角形の法線ベクトル D3DXVECTOR3 n1,n2,n3; // 3辺と内部の点との法線ベクトル D3DXVec3Subtract( &v1v2, v2, v1 ); D3DXVec3Subtract( &v2v3, v3, v2 ); D3DXVec3Subtract( &v3v1, v1, v3 ); D3DXVec3Subtract( &v1v3, v3, v1 ); D3DXVec3Subtract( &ap, pos, v1 ); D3DXVec3Subtract( &bp, pos, v2 ); D3DXVec3Subtract( &cp, pos, v3 ); D3DXVec3Cross( &vNormal, &v1v2, &v1v3 ); D3DXVec3Cross( &n1, &v1v2, &ap ); D3DXVec3Cross( &n2, &v2v3, &bp ); D3DXVec3Cross( &n3, &v3v1, &cp ); if( D3DXVec3Dot( &n1, &vNormal ) < 0.0f ) return FALSE; if( D3DXVec3Dot( &n2, &vNormal ) < 0.0f ) return FALSE; if( D3DXVec3Dot( &n3, &vNormal ) < 0.0f ) return FALSE; return TRUE; } //---------------------------------------------------- // 平面との距離を求める //---------------------------------------------------- float CCollision::LengthPointToPlane( D3DXVECTOR3* pOutCrossPos, CONST D3DXVECTOR3* vStartPos, CONST TPLANE* plane ) { //交点を求める FLOAT cross1 = -( plane->a * vStartPos->x + plane->b * vStartPos->y + plane->c * vStartPos->z + plane->d ); FLOAT cross2 = ( plane->a * plane->a + plane->b*plane->b + plane->c * plane->c ); FLOAT t = cross1 / cross2; pOutCrossPos->x = plane->a * t + vStartPos->x; pOutCrossPos->y = plane->b * t + vStartPos->y; pOutCrossPos->z = plane->c * t + vStartPos->z; //点と平面の距離を求める float p1 = abs( plane->a * vStartPos->x + plane->b * vStartPos->y + plane->c * vStartPos->z + plane->d ); float p2 = sqrtf( plane->a * plane->a + plane->b * plane->b + plane->c * plane->c ); return ( p1 / p2 ); } <file_sep> #include "CModelViewBackManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CModelViewBackManager::CModelViewBackManager( void ) { m_pModelViewBack = new C2DSpriteAlphaBlend(); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CModelViewBackManager::~CModelViewBackManager( void ) { if( m_pModelViewBack != NULL ) { delete m_pModelViewBack; m_pModelViewBack = NULL; } } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CModelViewBackManager::Init( void ) { m_isFade = false; m_pModelViewBack->SetVertexPos( 400.0f,320.0f,800.0f,640.0f ); m_pModelViewBack->SetDiffuse( 255,255,255,0 ); } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CModelViewBackManager::Run( void ) { } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CModelViewBackManager::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( m_pModelViewBack->GetVertex() ); } //---------------------------------------------------- // Fade //---------------------------------------------------- bool CModelViewBackManager::Fade( void ) { if( m_pModelViewBack->FadeOut( 5 ) ) { return true; } return false; } <file_sep>//---------------------------------------------------- // CSceneChangeClass // Sceneを変更するためのクラス // // @date 2013/6/13 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_CHANGE_H_ #define _C_SCENE_CHANGE_H_ typedef enum { eSceneTitle, eSceneModeSelect, // モードセレクト画面 eSceneHighScore, // スコア表示画面 eSceneGame, // ゲーム画面 eSceneResult, // リザルト eSceneConfig, // 設定画面 eSceneModelView, // モデルビューワー eSceneDebug, // デバッグ画面 eScene_None, // 無し }eSceneState; class CSceneChange { public: CSceneChange(){}; virtual ~CSceneChange(){} public: virtual void ChangeScene( eSceneState NextScene ) = 0;//指定シーンに変更する }; #endif _C_SCENE_CHANGE_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/2D/C2DBillBoard.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C2DBillBoard::C2DBillBoard( void ) { m_color.red = 255; m_color.green = 255; m_color.blue = 255; m_color.alpha = 255; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C2DBillBoard::~C2DBillBoard( void ) { } //---------------------------------------------------- // 色のセット //---------------------------------------------------- void C2DBillBoard::SetColor( CONST UINT r = 255, CONST UINT g = 255, CONST UINT b = 255, CONST UINT a = 255 ) { m_color.red = r; m_color.green = g; m_color.blue = b; m_color.alpha = a; // 頂点にも反映させる this->SetVertexColor(); } //---------------------------------------------------- // 頂点色のセット //---------------------------------------------------- void C2DBillBoard::SetVertexColor( void ) { D3DCOLOR color = D3DCOLOR_RGBA( m_color.red, m_color.green, m_color.blue, m_color.alpha ); m_vertex[0].diffuse = color; m_vertex[1].diffuse = color; m_vertex[2].diffuse = color; m_vertex[3].diffuse = color; } //---------------------------------------------------- // 板ポリゴンの行列をワールド行列(ビルボード用)に変換 //---------------------------------------------------- void C2DBillBoard::CalcWorldMtx( CONST D3DXMATRIX* cameraView ) { m_worldMtx._11 = cameraView->_11; m_worldMtx._12 = cameraView->_21; m_worldMtx._13 = cameraView->_31; m_worldMtx._21 = 0.0f; m_worldMtx._22 = 1.0f; m_worldMtx._23 = 0.0f; m_worldMtx._31 = cameraView->_13; m_worldMtx._32 = cameraView->_23; m_worldMtx._33 = cameraView->_33; m_worldMtx._14 = 0.0f; m_worldMtx._24 = 0.0f; m_worldMtx._34 = 0.0f; m_worldMtx._44 = 1.0f; } <file_sep>//---------------------------------------------------- // C2DSpriteRHW // 2Dポリゴンを描画するためのもの // 同次座標計算をしている // // @date 2013/8/10 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_2D_SPRITE_RHW_H_ #define _C_2D_SPRITE_RHW_H_ #include <d3dx9.h> // Sprite(同次座標あり)頂点データ構造体 typedef struct TAGtSPRITERHW { D3DXVECTOR3 pos; // 頂点の座標 float rhw; // スクリーン座標変換 D3DCOLOR diffuse; // 頂点の色 float tu, tv; // テクスチャ座標 }tagTSPRITERHW; class C2DSpriteRHW { private: tagTSPRITERHW m_vertex[4]; // 頂点データ protected: D3DXVECTOR2 m_center; // 中心座標 D3DXVECTOR2 m_halfSize; // 半分のサイズ D3DXVECTOR2 m_size; // サイズ public: C2DSpriteRHW ( void ); virtual ~C2DSpriteRHW ( void ); //---------------------------------------------------- // 頂点座標の取得 //---------------------------------------------------- tagTSPRITERHW* GetVertex ( void ) { return m_vertex; } //---------------------------------------------------- // 中心座標をゲット //---------------------------------------------------- D3DXVECTOR2* GetCenter ( void ) { return &m_center; } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ); public: //---------------------------------------------------- // @name SetVertexPos // @content 頂点座標のセット(中心座標とサイズを指定) // @param centerX 中心X座標 // @param centerY 中心Y座標 // @param width 横幅 // @param height 縦幅 // @return none // @date 2013/8/10 //---------------------------------------------------- void SetVertexPos ( CONST float centerX, CONST float centerY, CONST float width, CONST float height ); //---------------------------------------------------- // @name SetVertexPos // @content 頂点座標のセット(中心座標を指定) // @param centerX 中心X座標 // @param centerY 中心Y座標 // @return none // @date 2013/8/10 //---------------------------------------------------- void SetVertexPos ( CONST float centerX, CONST float centerY ); //---------------------------------------------------- // @name SetVertexPos // @content 頂点座標のセット(中心座標をD3DXVECTOR2型でセット) // @param center 中心座標 // @return none // @date 2013/8/10 //---------------------------------------------------- void SetVertexPos ( CONST D3DXVECTOR2* center ); //---------------------------------------------------- // @name SetUV // @content テクスチャ座標のセット // @param none // @return none // @date 2013/12/13 //---------------------------------------------------- void SetUV ( void ); //---------------------------------------------------- // @name SetUV // @content テクスチャ座標のセット // @param uPatern 横のパターン数 // @param vPatern 縦のパターン数 // @param uNum 横の番号 // @param vNum 縦の番号 // @return none // @date 2013/8/10 //---------------------------------------------------- void SetUV ( CONST UINT uPatern, CONST UINT vPatern, CONST UINT uNum, CONST UINT vNum ); //---------------------------------------------------- // @name SetDiffuse // @content 頂点の色セット // @param r 赤値( 0 〜 255 ) // @param g 緑値( 0 〜 255 ) // @param b 青値( 0 〜 255 ) // @param a α値 ( 0 〜 255 ) // @return none // @date 2013/8/11 // @update 2013/12/13 引数をUINT型に設定 //---------------------------------------------------- void SetDiffuse ( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ); //---------------------------------------------------- // α値の取得 //---------------------------------------------------- int GetAlpha ( void ) { return ( m_vertex[0].diffuse >> 24 ); } }; #endif _C_2D_SPRITE_RHW_H_<file_sep> #include "CSceneGame.h" const int ConstGamePlayTime = 180; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneGame::CSceneGame( void ) { } //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneGame::CSceneGame( CSceneChange* change ) : CSceneBase( change ) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneGame::Load( void ) { m_pDirectCamera = new CDirectCamera; m_pDirectLight = new CDirectLight; // αブレンドのための背景ポリゴン m_pBack = new C2DSpriteAlphaBlend; m_pTimeUP = new C2DSpriteRHW; m_pResTimeUpFilePath = TIMEUP_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResTimeUpFilePath ); m_pPushEnter = new C2DSpriteRHW; m_pResPushEnterFilePath = TIMEUP_PUSHENTER_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPushEnterFilePath ); // Manager m_pGameStageManager = new CGameStageManager; m_pPauseManager = new CPauseManager; m_pTimeManager = new CTimeManager; m_pScoreManager = new CScoreManager; m_pDiceInfoManager = new CDiceInfoManager; m_pSnowObj = new CSnowObj; m_pSpaceParticle = new CSpaceParticle; // タイムアップ m_pTimeUP->SetVertexPos( 400.0f,280.0f,450.0f,180.0f ); // PUSH ENTER m_pPushEnter->SetVertexPos( 600.0f,500.0f,256.0f,64.0f ); CDiceObjManager::GetInstance()->SetDiceInfoManager( m_pDiceInfoManager ); CPlayerManager::GetInstance()->SetDiceInfoManager( m_pDiceInfoManager ); #ifdef _DEBUG CDebugMode::Load(); // デバッグ画面のロード #endif return true; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSceneGame::~CSceneGame( void ) { SAFE_DELETE( m_pDirectCamera ); // カメラの解放 SAFE_DELETE( m_pDirectLight ); // ライトの解放 SAFE_DELETE( m_pBack ); // αブレンドのためのもの SAFE_DELETE( m_pTimeUP ); // タイムアップ SAFE_DELETE( m_pPushEnter ); // PUSH ENTER SAFE_DELETE( m_pGameStageManager ); // 背景のマネージャー SAFE_DELETE( m_pTimeManager ); // タイムのマネージャー SAFE_DELETE( m_pScoreManager ); // スコアのマネージャー SAFE_DELETE( m_pDiceInfoManager ); // ダイスInfoのマネージャー SAFE_DELETE( m_pPauseManager ); // ポーズボタンの解放 SAFE_DELETE( m_pSnowObj ); // 雪 SAFE_DELETE( m_pSpaceParticle ); // 雪のパーティクル } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CSceneGame::Initialize( void ) { m_pDirectCamera->Init( 800, 640); m_pDirectCamera->SetPosition( 18.0f, 24.0f, -27.0f ); m_pDirectCamera->SetAt( -2.0f, 0.0f,0.0f ); m_pDirectLight->Switch( true ); CPlayerManager::GetInstance()->BrightChange( true ); // プレイヤーの色変更 m_pTimeManager->BrightChange( true ); // タイムの色変更 m_pScoreManager->BrightChange( true ); // スコアの色変更 m_pDiceInfoManager->BrightChange( true ); // INFOの色変更 // 乱数の初期化 CDiceRandSystem::GetInstance()->InitSeed(); // 背景ポリゴン m_pBack->SetVertexPos( 400.0f,320.0f,800.0f,640.0f ); m_pBack->SetDiffuse( 255,255,255,0 ); #ifdef _DEBUG CDebugMode::Init(); CDebugMode::Set( m_pTimeManager->GetTime() ); #endif // Manager m_pGameStageManager->Init(); CStageBlockManager::GetInstance()->Init(); CStageBlockManager::GetInstance()->SetBlockPos(); m_pPauseManager->Init(); m_pTimeManager->Init( ConstGamePlayTime ); m_pScoreManager->Init(); m_pDiceInfoManager->Init(); CPlayerManager::GetInstance()->Init(); CPlayerManager::GetInstance()->SetCameraToMtx( m_pDirectCamera->GetView() ); CDiceObjManager::GetInstance()->Init(); // チェインの管理クラスにスコアのポインタをセット CChainManager::GetInstance()->SetScore( m_pScoreManager->GetScore() ); m_eGamePlayStatus = GAMEPLAY_STATUS::GAME_PLAY; } //---------------------------------------------------- // ゲームシーンの終了 //---------------------------------------------------- void CSceneGame::Finalize( void ) { } //---------------------------------------------------- // ゲームシーンの処理 //---------------------------------------------------- void CSceneGame::Run( void ) { // デバイスの更新 CInputKeyboard::GetInstance()->Update(); CJoyStick::GetInstance()->Update(); switch( m_eGamePlayStatus ) { // ゲームプレイ中 case GAMEPLAY_STATUS::GAME_PLAY: CPlayerManager::GetInstance()->Run(); m_pGameStageManager->Run(); CDiceObjManager::GetInstance()->Run(); m_pScoreManager->Run(); m_pTimeManager->Run(); this->ChangePause(); // ポーズ切り替え this->TimeUp(); // タイムアップ break; // ポーズ中 case GAMEPLAY_STATUS::GAME_PAUSE: m_pPauseManager->Run(); this->Pause(); // ポーズ中 this->ChangePause(); // ポーズ切り替え break; // タイムアップ中 case GAMEPLAY_STATUS::TIME_UP: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RETURN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_A ) ) { m_eGamePlayStatus = GAMEPLAY_STATUS::TIME_UP_FADE; } break; // タイムアップのフェード case GAMEPLAY_STATUS::TIME_UP_FADE: this->TimeUpFade(); break; // ポーズのフェード case GAMEPLAY_STATUS::PAUSE_FADE: this->PauseFade(); break; #ifdef _DEBUG // デバッグモード中 case GAMEPLAY_STATUS::DEBUG_MODE: CDebugMode::RunDebugMode(); if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F1 ) || CDebugMode::m_isDebugMode == false ) { m_eGamePlayStatus = GAMEPLAY_STATUS::GAME_PLAY; return; } break; #endif } // デバッグモードに入る #ifdef _DEBUG CDebugMode::Run( m_pDirectCamera ); if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F1 ) && m_eGamePlayStatus != GAMEPLAY_STATUS::DEBUG_MODE ) { CDebugMode::InitDebugMode(); m_eGamePlayStatus = GAMEPLAY_STATUS::DEBUG_MODE; } #endif } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSceneGame::Draw( void ) { m_pGameStageManager->Draw(); // ステージ // ダイス CDiceObjManager::GetInstance()->Draw( m_pDirectCamera->GetView() ); // プレイヤー CPlayerManager::GetInstance()->Draw(); // デバッグ時のみデバッグ画面 #ifdef _DEBUG CDebugMode::Draw(); #endif switch( m_eGamePlayStatus ) { // ゲームプレイ中 case GAMEPLAY_STATUS::GAME_PLAY: break; // ポーズ中 case GAMEPLAY_STATUS::GAME_PAUSE: m_pPauseManager->Draw(); break; // ポーズフェード中 case GAMEPLAY_STATUS::PAUSE_FADE: m_pPauseManager->Draw(); break; // デバッグ中 #ifdef _DEBUG case GAMEPLAY_STATUS::DEBUG_MODE: CDebugMode::DrawDebugMode(); break; #endif // タイムアップ中 case GAMEPLAY_STATUS::TIME_UP: CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTimeUpFilePath )->Get(), m_pTimeUP->GetVertex() ); // CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResPushEnterFilePath )->Get() ,m_pPushEnter->GetVertex() ); break; } m_pDiceInfoManager->Draw(); // Info m_pScoreManager->Draw(); // スコア m_pTimeManager->Draw(); // タイム // 背景描画 CDirectDrawSystem::GetInstance()->DrawSpriteRHW( NULL, m_pBack->GetVertex() ); } //---------------------------------------------------- // ポーズ切り替え //---------------------------------------------------- void CSceneGame::ChangePause( void ) { // ESCAPEキーでポーズ切り替え if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_ESCAPE ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_START ) ) { bool isPause = false; // ポーズのフラグを取得 m_pPauseManager->SetIsPause(); isPause = m_pPauseManager->GetIsPause(); m_pDirectLight->Switch( !isPause ); // ライトのスイッチ変更 CPlayerManager::GetInstance()->BrightChange( !isPause ); // プレイヤーの色変更 m_pTimeManager->BrightChange( !isPause ); // タイムの色変更 m_pScoreManager->BrightChange( !isPause ); // スコアの色変更 m_pDiceInfoManager->BrightChange( !isPause ); // INFOの色変更 if( m_eGamePlayStatus == GAMEPLAY_STATUS::GAME_PLAY ) { m_pPauseManager->InitPause(); m_eGamePlayStatus = GAMEPLAY_STATUS::GAME_PAUSE; } else if( m_eGamePlayStatus == GAMEPLAY_STATUS::GAME_PAUSE ) { m_eGamePlayStatus = GAMEPLAY_STATUS::GAME_PLAY; } } } //---------------------------------------------------- // ポーズ //---------------------------------------------------- void CSceneGame::Pause( void ) { // ポーズ処理 if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RETURN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_A ) ) { if( m_pPauseManager->GetPauseState() == ePauseStatus::RESUME ) { bool isPause = false; m_pPauseManager->SetIsPause(); isPause = m_pPauseManager->GetIsPause(); m_pDirectLight->Switch( !isPause ); // ライトのスイッチ変更 CPlayerManager::GetInstance()->BrightChange( !isPause ); // プレイヤーの色変更 m_pTimeManager->BrightChange( !isPause ); // タイムの色変更 m_pScoreManager->BrightChange( !isPause ); // スコアの色変更 m_pDiceInfoManager->BrightChange( !isPause ); // INFOの色変更 m_eGamePlayStatus = GAMEPLAY_STATUS::GAME_PLAY; } else { // フェード中に設定する m_eGamePlayStatus = GAMEPLAY_STATUS::PAUSE_FADE; } } } //---------------------------------------------------- // ポーズのフェード //---------------------------------------------------- void CSceneGame::PauseFade( void ) { if( m_pBack->FadeOut( 3 ) ) { // フェードした後の遷移 switch( m_pPauseManager->GetPauseState() ) { case RETRY: this->Initialize(); break; case TITLE: mSceneChanger->ChangeScene( eSceneState::eSceneTitle ); break; } } } //---------------------------------------------------- // タイムアップ //---------------------------------------------------- void CSceneGame::TimeUp( void ) { // タイムアップ処理 if( m_pTimeManager->TimeUP() == true ) { m_pDirectLight->Switch( false ); CPlayerManager::GetInstance()->BrightChange( false ); // プレイヤーの色変更 m_pTimeManager->BrightChange( false ); // タイムの色変更 m_pScoreManager->BrightChange( false ); // スコアの色変更 m_pDiceInfoManager->BrightChange( false ); // INFOの色変更 m_eGamePlayStatus = GAMEPLAY_STATUS::TIME_UP; } } //---------------------------------------------------- // タイムアップのフェード //---------------------------------------------------- void CSceneGame::TimeUpFade( void ) { if( m_pBack->FadeOut( 3 ) ) { // ゲームのスコアをユーザデータとして保存 CUserManager::GetInstance()->InitGameScore(); CUserManager::GetInstance()->SetGameScore( m_pScoreManager->GetScore() ); // フェードが終わったらシーン切り替え mSceneChanger->ChangeScene( eSceneState::eSceneResult ); } }<file_sep> #include "CSceneResult.h" // 1〜6のテクスチャ const int pipDigitNum = 4; const float pipPosX = 150.0f; const float pipPosY = 270.0f; const float pipDistanceX = 300.0f; const float pipDistanceY = 70.0f; const float pipSizeX = 50.0f; const float pipSizeY = 50.0f; const float pipDigitDistanceX = 100.0f; // スコア const int scoreDigitNum = 7; const float scoreValueXPos = 180.0f; const float scoreValueYPos = 180.0f; const float scoreValueWidth = 160.0f; const float scoreValueHeight = 70.0f; const float scoreDigitXPos = scoreValueXPos + 180.0f; const float scoreDigitYPos = scoreValueYPos + 5.0f; const float scoreDigitWidth = 50.0f; const float scoreDigitDistanceX = 35.0f; const float scoreDigitHeight = 50.0f; // MaxChain const int maxChainDigitNum = 4; const float maxChainValueXPos = 180.0f; const float maxChainValueYPos = 500.0f; const float maxChainValueWidth = 220.0f; const float maxChainValueHeight = 70.0f; const float maxChainDigitDistanceX = 200.0f; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneResult::CSceneResult( void ) { } //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneResult::CSceneResult( CSceneChange* change ) : CSceneBase( change ) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneResult::Load( void ) { // Result文字 m_pResultValue = new C2DSpriteRHW; m_pResResultValueFilePath = RESULT_RESULTVALUE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResResultValueFilePath ); // 数字 m_pResScoreDigitFilePath = RESULT_SCOREDIGIT_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResScoreDigitFilePath ); // Score m_pScoreValue = new C2DSpriteRHW; m_pResScoreValueFilePath = RESULT_SCOREVALUE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResScoreValueFilePath ); m_pScoreDigit = new C2DSpriteRHW[scoreDigitNum]; // MaxChain m_pMaxChainValue = new C2DSpriteRHW; m_pResMaxChainValueFilePath = RESULT_MAXCHAIN_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResMaxChainValueFilePath ); m_pMaxChainDigit = new C2DSpriteRHW[maxChainDigitNum]; // 1〜6 m_pOnePip = new C2DSpriteRHW; m_pOnePipDigit = new C2DSpriteRHW[pipDigitNum]; m_pTwoPip = new C2DSpriteRHW; m_pTwoPipDigit = new C2DSpriteRHW[pipDigitNum]; m_pThreePip = new C2DSpriteRHW; m_pThreePipDigit = new C2DSpriteRHW[pipDigitNum]; m_pFourPip = new C2DSpriteRHW; m_pFourPipDigit = new C2DSpriteRHW[pipDigitNum]; m_pFivePip = new C2DSpriteRHW; m_pFivePipDigit = new C2DSpriteRHW[pipDigitNum]; m_pSixPip = new C2DSpriteRHW; m_pSixPipDigit = new C2DSpriteRHW[pipDigitNum]; m_pResOneTextureFilePath = RESULT_ONE_PNGPATH; m_pResTwoTextureFilePath = RESULT_TWO_PNGPATH; m_pResThreeTextureFilePath = RESULT_THREE_PNGPATH; m_pResFourTextureFilePath = RESULT_FOUR_PNGPATH; m_pResFiveTextureFilePath = RESULT_FIVE_PNGPATH; m_pResSixTextureFilePath = RESULT_SIX_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResOneTextureFilePath ); CResourceManager::GetInstance()->LoadTexture( m_pResTwoTextureFilePath ); CResourceManager::GetInstance()->LoadTexture( m_pResThreeTextureFilePath ); CResourceManager::GetInstance()->LoadTexture( m_pResFourTextureFilePath ); CResourceManager::GetInstance()->LoadTexture( m_pResFiveTextureFilePath ); CResourceManager::GetInstance()->LoadTexture( m_pResSixTextureFilePath ); m_pPushEnter = new C2DSpriteRHW; m_pResPushEnterFilePath = RESULT_PUSHENTER_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResPushEnterFilePath ); m_pBack = new C2DSpriteAlphaBlend; return true; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSceneResult::~CSceneResult( void ) { SAFE_DELETE( m_pResultValue ); SAFE_DELETE( m_pScoreValue ); SAFE_DELETE_ALLAY( m_pScoreDigit ); SAFE_DELETE( m_pMaxChainValue ); SAFE_DELETE_ALLAY( m_pMaxChainDigit ); SAFE_DELETE( m_pOnePip ); SAFE_DELETE_ALLAY( m_pOnePipDigit ); SAFE_DELETE( m_pTwoPip ); SAFE_DELETE_ALLAY( m_pTwoPipDigit ); SAFE_DELETE( m_pThreePip ); SAFE_DELETE_ALLAY( m_pThreePipDigit ); SAFE_DELETE( m_pFourPip ); SAFE_DELETE_ALLAY( m_pFourPipDigit ); SAFE_DELETE( m_pFivePip ); SAFE_DELETE_ALLAY( m_pFivePipDigit ); SAFE_DELETE( m_pSixPip ); SAFE_DELETE_ALLAY( m_pSixPipDigit ); SAFE_DELETE( m_pPushEnter ); SAFE_DELETE( m_pBack ); } //---------------------------------------------------- // 更新 //---------------------------------------------------- void CSceneResult::Run( void ) { CInputKeyboard::GetInstance()->Update(); CJoyStick::GetInstance()->Update(); if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RETURN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_A )) { m_isFade = true; } if( m_isFade == true ) { if( m_pBack->FadeOut( 3 ) ) { // フェードアウトが終わったらタイトルに戻る mSceneChanger->ChangeScene( eSceneState::eSceneTitle ); } } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSceneResult::Draw( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResResultValueFilePath )->Get(),m_pResultValue->GetVertex() ); // Score CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreValueFilePath )->Get(), m_pScoreValue->GetVertex() ); for( int i = scoreDigitNum - 1; i > scoreDigitNum - 1 - m_scoreDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pScoreDigit[i].GetVertex() ); } // MaxChain CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResMaxChainValueFilePath )->Get(), m_pMaxChainValue->GetVertex() ); for( int i = maxChainDigitNum - 1; i > maxChainDigitNum - 1 - m_maxChainDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pMaxChainDigit[i].GetVertex() ); } // 1〜6 CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResOneTextureFilePath )->Get(), m_pOnePip->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResTwoTextureFilePath )->Get(), m_pTwoPip->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResThreeTextureFilePath )->Get(), m_pThreePip->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResFourTextureFilePath )->Get(), m_pFourPip->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResFiveTextureFilePath )->Get(), m_pFivePip->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResSixTextureFilePath )->Get(), m_pSixPip->GetVertex() ); for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_oneDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pOnePipDigit[i].GetVertex() ); } for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_twoDigitNum; -- i) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pTwoPipDigit[i].GetVertex() ); } for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_threeDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pThreePipDigit[i].GetVertex() ); } for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_fourDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pFourPipDigit[i].GetVertex() ); } for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_fiveDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pFivePipDigit[i].GetVertex() ); } for( int i = pipDigitNum - 1; i > pipDigitNum - 1 - m_sixDigitNum; -- i ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResScoreDigitFilePath )->Get(), m_pSixPipDigit[i].GetVertex() ); } CDirectDrawSystem::GetInstance()->DrawSpriteRHW( NULL,m_pBack->GetVertex() ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CSceneResult::Initialize( void ) { int score = 0; int scoreDigit = 0; m_scoreDigitNum = 0; m_maxChainDigitNum = 0; m_oneDigitNum = 0; m_twoDigitNum = 0; m_threeDigitNum = 0; m_fourDigitNum = 0; m_fiveDigitNum = 0; m_sixDigitNum = 0; // Result文字 m_pResultValue->SetVertexPos( 400.0f,70.0f,250.0f,120.0f ); // Score m_pScoreValue->SetVertexPos( scoreValueXPos, scoreValueYPos, scoreValueWidth, scoreValueHeight ); score = CUserManager::GetInstance()->GetGameScore()->m_record; for( int i = scoreDigitNum - 1; i == scoreDigitNum - 1 || score != 0; -- i ) { m_scoreDigitNum ++; m_pScoreDigit[i].SetVertexPos( scoreDigitXPos + i * scoreDigitDistanceX, scoreDigitYPos, scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pScoreDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } // MaxChain m_pMaxChainValue->SetVertexPos( maxChainValueXPos, maxChainValueYPos, maxChainValueWidth, maxChainValueHeight ); score = CUserManager::GetInstance()->GetGameScore()->m_chainNum; for( int i = maxChainDigitNum - 1; i == maxChainDigitNum - 1 || score != 0; -- i ) { m_maxChainDigitNum ++; m_pMaxChainDigit[i].SetVertexPos( m_pMaxChainValue->GetCenter()->x + maxChainDigitDistanceX + i * scoreDigitDistanceX, m_pMaxChainValue->GetCenter()->y, scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pMaxChainDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } // 1 m_pOnePip->SetVertexPos( pipPosX, pipPosY, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_oneChainNum; for( int i = pipDigitNum - 1; i == pipDigitNum - 1 || score != 0; -- i ) { m_oneDigitNum ++; m_pOnePipDigit[i].SetVertexPos( m_pOnePip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pOnePip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pOnePipDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } // 2 m_pTwoPip->SetVertexPos( pipPosX, pipPosY + pipDistanceY, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_twoChainNum; for( int i = pipDigitNum - 1; i == pipDigitNum - 1 || score != 0; -- i ) { m_twoDigitNum ++; m_pTwoPipDigit[i].SetVertexPos( m_pTwoPip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pTwoPip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pTwoPipDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } m_pThreePip->SetVertexPos( pipPosX, pipPosY + pipDistanceY * 2, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_threeChainNum; for( int i = pipDigitNum - 1; i == pipDigitNum - 1 || score != 0; -- i ) { m_threeDigitNum ++; m_pThreePipDigit[i].SetVertexPos( m_pThreePip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pThreePip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pThreePipDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } m_pFourPip->SetVertexPos( pipPosX + pipDistanceX, pipPosY, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_fourChainNum; for( int i = pipDigitNum - 1; i == pipDigitNum - 1 || score != 0; -- i ) { m_fourDigitNum ++; m_pFourPipDigit[i].SetVertexPos( m_pFourPip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pFourPip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pFourPipDigit[i].SetUV( 10, 1 , scoreDigit + 1, 1 ); } m_pFivePip->SetVertexPos( pipPosX + pipDistanceX, pipPosY + pipDistanceY, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_fiveChainNum; for( int i = pipDigitNum - 1; i == pipDigitNum - 1 || score != 0; -- i ) { m_fiveDigitNum ++; m_pFivePipDigit[i].SetVertexPos( m_pFivePip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pFivePip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pFivePipDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } m_pSixPip->SetVertexPos( pipPosX + pipDistanceX, pipPosY + pipDistanceY * 2, pipSizeX, pipSizeY ); score = CUserManager::GetInstance()->GetGameScore()->m_sixChainNum; for( int i = pipDigitNum - 1;i == pipDigitNum - 1 || score != 0; -- i ) { m_sixDigitNum ++; m_pSixPipDigit[i].SetVertexPos( m_pSixPip->GetCenter()->x + pipDigitDistanceX + i * scoreDigitDistanceX, m_pSixPip->GetCenter()->y , scoreDigitWidth, scoreDigitHeight ); scoreDigit = score % 10; score = score / 10; m_pSixPipDigit[i].SetUV( 10, 1, scoreDigit + 1, 1 ); } m_pPushEnter->SetVertexPos( 600.0f,550.0f,256.0f,64.0f ); m_pBack->SetVertexPos(400.0f,320.0f,800.0f,640.0f ); m_pBack->SetDiffuse( 255,255,255,0 ); m_isFade = false; CUserManager::GetInstance()->UpdateScore(); } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CSceneResult::Finalize( void ) { } <file_sep>/************************************************************* * @file CDebugConsole.h * @brief CDebugConsoleクラスヘッダー * @note メモ * @author <NAME> * @date 2013/04/17 *************************************************************/ #ifndef _Include_CDebugConsole_h_ // インクルードガード #define _Include_CDebugConsole_h_ //------------------------------------------------------------ // インクルード //------------------------------------------------------------ #include<Windows.h> #include<string> //------------------------------------------------------------ // 定数、構造体定義 //------------------------------------------------------------ enum CONSOLECOLOR { L_BLACK = 0, L_BLUE, L_GREEN, L_CYAN, L_RED, L_PURPLE, L_YELLOW, L_WHITE, H_BLACK, H_BLUE, H_GREEN, H_CYAN, H_RED, H_PURPLE, H_YELLOW, H_WHITE }; /*!----------------------------------------------------------- // @class CDebugConsole // @brief デバッグ用のコンソール // @note メモ // @author <NAME> // @date 2013/04/17 ------------------------------------------------------------*/ class CDebugConsole { public: /// コンストラクタ CDebugConsole() { m_pFile = nullptr; SMALL_RECT rc = {0,0,1024,512}; COORD cd = {rc.Right+1,rc.Bottom+1}; ::AllocConsole(); //コンソールの確保 m_hStdOut = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleScreenBufferSize(m_hStdOut, cd); SetConsoleWindowInfo(m_hStdOut,TRUE,&rc); m_backColor = L_BLACK; m_textColor = L_WHITE; this->SetColorF(H_RED); CDebugConsole::Printf("[==================== Start Up Debug Console ====================]\n\n"); this->SetColorF(m_textColor); } /// デストラクタ ~CDebugConsole() { this->Destory(); } /*!----------------------------------------------------------- // @brief 解放処理 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/12/03 ------------------------------------------------------------*/ void Destory() { if( m_hStdOut == nullptr ) return; if( m_pFile != nullptr ) fclose(m_pFile); //コンソールの解放 ::FreeConsole(); m_hStdOut = nullptr; } /*!----------------------------------------------------------- // @brief ファイルポインタオープン // @note 特になし // @param[in] fileName 作成するファイル名 // @return なし // @author <NAME> // @date 2013/08/05 ------------------------------------------------------------*/ void CreateDebugLog(LPCTSTR fileName) { fopen_s(&m_pFile,fileName,"w"); } /*!----------------------------------------------------------- // @brief カーソルの大きさと可視設定 // @note 特になし // @param[in] dwSize カーソルの大きさ // @param[in] isVisible 可視設定 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void SetCursorInfo( DWORD dwSize = 25, BOOL isVisible = TRUE ) { CONSOLE_CURSOR_INFO info = { dwSize, isVisible }; ::SetConsoleCursorInfo( m_hStdOut, &info ); } /*!----------------------------------------------------------- // @brief コンソールカーソルの位置設定 // @note 特になし // @param[in] x X座標 // @return y Y座標 // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void SetCursorPosition( int x, int y ) { COORD coord = { (short)x, (short)y }; ::SetConsoleCursorPosition( m_hStdOut, coord ); } /*!----------------------------------------------------------- // @brief 背景色を変更 // @note 特になし // @param[in] backColor 背景色 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void SetColorB( WORD backColor = L_BLACK ){ this->SetColor( backColor, m_textColor ); } /*!----------------------------------------------------------- // @brief 文字色を変更 // @note 特になし // @param[in] textColor 文字色 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void SetColorF( WORD textColor = L_WHITE ) { this->SetColor( m_backColor, textColor ); } /*!----------------------------------------------------------- // @brief 背景・文字色を変更 // @note 特になし // @param[in] backColor 背景色 // @param[in] textColor 文字色 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void SetColor( WORD backColor = L_BLACK, WORD textColor = L_WHITE ) { m_backColor = backColor; m_textColor = textColor; ::SetConsoleTextAttribute( m_hStdOut, m_textColor|(m_backColor<<4) ); } /*!----------------------------------------------------------- // @brief 文字列の描画 // @note 特になし // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ DWORD Printf( const std::string str, ... ) { DWORD len; va_list args; va_start( args, str ); vsprintf_s( m_strBuf, _countof(m_strBuf), str.c_str(), args ); va_end( args ); ::WriteConsoleA( m_hStdOut, m_strBuf, strlen(m_strBuf), &len, NULL ); return len; } /*!----------------------------------------------------------- // @brief 文字列の描画 // @note ログテキストにも出力する // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/05/20 ------------------------------------------------------------*/ DWORD PrintfLog( const std::string str, ... ) { DWORD len; va_list args; va_start( args, str ); vsprintf_s( m_strBuf, _countof(m_strBuf), str.c_str(), args ); va_end( args ); ::WriteConsoleA( m_hStdOut, m_strBuf, strlen(m_strBuf), &len, NULL ); fprintf_s(m_pFile,"%s",m_strBuf); return len; } /*!----------------------------------------------------------- // @brief 描画画面のクリア // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void Clear( void ) { system( "cls" ); } /*!----------------------------------------------------------- // @brief 閉じるボタンを無効か // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void RemoveClose( void ) { HMENU hMenu = GetSystemMenu( ::GetConsoleWindow(), FALSE ); ::RemoveMenu( hMenu, SC_CLOSE, MF_BYCOMMAND ); } /*!----------------------------------------------------------- // @brief 初期状態に戻す // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ void Reset( void ) { this->SetColor( L_BLACK, L_WHITE ); this->Clear(); this->SetCursorPosition( 0, 0 ); } private: FILE* m_pFile; ///< ファイルポインタ HANDLE m_hStdOut; ///< 出力先ハンドル CHAR m_strBuf[512]; ///< 文字列バッファ WORD m_backColor; ///< 背景色 WORD m_textColor; ///< 文字色 }; #ifdef DEBUG_INSTANCE #define DEBUG_EXTERN #else #define DEBUG_EXTERN extern #endif // !DEBUG_INSTANCE DEBUG_EXTERN CDebugConsole g_DebugConsole; namespace DEBUG { static const int DUMMY_NONE = 0; enum CONSOLECOLOR { L_BLACK = 0, L_BLUE, L_GREEN, L_CYAN, L_RED, L_PURPLE, L_YELLOW, L_WHITE, H_BLACK, H_BLUE, H_GREEN, H_CYAN, H_RED, H_PURPLE, H_YELLOW, H_WHITE }; #if defined(_DEBUG) || defined(_BF_RELEASE_DEBUG) /*!----------------------------------------------------------- // @brief 可変引数に変換 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ inline void OutPutStringArgList(CONST LPSTR str,va_list argList) { char buf[1024]; _vsnprintf_s( buf, _countof(buf), str, argList ); OutputDebugStringA( buf ); g_DebugConsole.Printf( buf ); } /*!----------------------------------------------------------- // @brief 可変引数に変換 // @note ログ出力版 // @param[in] なし // @return なし // @author <NAME> // @date 2013/05/20 ------------------------------------------------------------*/ inline void OutPutStringArgListLog(CONST LPSTR str,va_list argList) { char buf[1024]; _vsnprintf_s( buf, _countof(buf), str, argList ); OutputDebugStringA( buf ); g_DebugConsole.PrintfLog( buf ); } /*!----------------------------------------------------------- // @brief デバッグコンソールの初期化 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ inline void InitDebugConsole(void) { // デバッグコンソールの閉じるボタン無効化 g_DebugConsole.RemoveClose(); } /*!----------------------------------------------------------- // @brief ログ作成初期化 // @note 特になし // @param[in] fileName 書き込むファイル名 // @return なし // @author <NAME> // @date 2013/10/05 ------------------------------------------------------------*/ inline void InitDebugLog(LPCTSTR fileName) { //デバッグログの初期化 g_DebugConsole.CreateDebugLog(fileName); } /*!----------------------------------------------------------- // @brief ×ボタンを無効化 // @note 特になし // @param[in] なし // @return なし // @author <NAME> // @date 2013/12/04 ------------------------------------------------------------*/ inline void RemoveClose() { g_DebugConsole.RemoveClose(); } /*!----------------------------------------------------------- // @brief 文字列の描画 // @note 特になし // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ inline void Printf(CONST LPSTR str,...) { g_DebugConsole.SetColor(); // 文字列を描画 va_list args; va_start( args, str ); OutPutStringArgList(str,args); va_end( args ); } /*!----------------------------------------------------------- // @brief 文字列の描画 // @note ログ出力版 // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/05/20 ------------------------------------------------------------*/ inline void PrintfLog(CONST LPSTR str,...) { g_DebugConsole.SetColor(); // 文字列を描画 va_list args; va_start( args, str ); OutPutStringArgListLog(str,args); va_end( args ); } /*!----------------------------------------------------------- // @brief 指定色で文字列の描画 // @note 特になし // @param[in] textColor 文字色 // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/04/27 ------------------------------------------------------------*/ inline void PrintfColor(WORD textColor,CONST LPSTR str,...) { // 色をセット g_DebugConsole.SetColorF( textColor ); va_list args; va_start( args, str ); OutPutStringArgList(str,args); va_end( args ); } /*!----------------------------------------------------------- // @brief 指定色で文字列の描画 // @note ログ出力版 // @param[in] textColor 文字色 // @param[in] str 文字列 // @param[in] ... 可変引数 // @return なし // @author <NAME> // @date 2013/05/20 ------------------------------------------------------------*/ inline void PrintfColorLog(WORD textColor,CONST LPSTR str,...) { // 色をセット g_DebugConsole.SetColorF( textColor ); va_list args; va_start( args, str ); OutPutStringArgListLog(str,args); va_end( args ); } #else #define InitDebugConsole() DUMMY_NONE #define InitDebugLog(fileName) DUMMY_NONE #define RemoveClose() DUMMY_NONE #define Printf(str, ... ) DUMMY_NONE #define PrintfLog(str,... ) DUMMY_NONE #define PrintfColor(fontColor,str, ... ) DUMMY_NONE #define PrintfColorLog(textColor,str,...) DUMMY_NONE #endif } #endif // _Include_CDebugConsole_h_<file_sep>//---------------------------------------------------- // CResourceTexture // 2Dテクスチャー // // @date 2013/12/5 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_RESOURCE_TEXTURE_H_ #define _C_RESOURCE_TEXTURE_H_ #include <d3dx9.h> #include "../DirectX9Header/CDirectX9FrameWork.h" #include "../UtilityHeader/Macro.hpp" #include "../DebugHeader/CDebugConsole.hpp" class CResourceTexture { private: LPDIRECT3DTEXTURE9 m_pTexture; public: // コンストラクタ CResourceTexture ( void ); // デストラクタ virtual ~CResourceTexture ( void ); public: //---------------------------------------------------- // @name Load // @content テクスチャーのロード // @param filePath ファイルパス // @return bool 成功か失敗 // @date 2013/12/5 //---------------------------------------------------- bool Load ( CONST LPSTR filePath ); //---------------------------------------------------- // テクスチャデータ取得 //---------------------------------------------------- CONST LPDIRECT3DTEXTURE9 Get (void) { return m_pTexture; } }; #endif _C_RESOURCE_TEXTURE_H_<file_sep>//---------------------------------------------------- // CDebugMode // ゲームのデバッグに使うシーン // // @date 2014/1/13 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DEBUG_MODE_H_ #define _C_DEBUG_MODE_H_ #include <Windows.h> #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/3D/C3DObjectShape.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourcePath.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceXFont.h" #define DEBUG_NUM ( 4 ) #define SELECT_DEBUG_NUM ( 6 ) #define DEFAULT_DEBUG_MODE_COLOR D3DXCOLOR( 255, 255, 255, 255 ) #define SELECT_DEBUG_MODE_COLOR D3DXCOLOR( 0, 255, 0, 255 ) #define CHEACK_DEBUG_MODE_COLOR D3DXCOLOR( 255, 0, 0, 255 ) // デバッグのフォント typedef struct tFONTINFO { bool cheack; D3DXCOLOR color; }TFONTINFO; // デバッグのステータス typedef enum DEBUGSTATUS { FPS, COLLISION_BOX, GAME_TIME, EXIT_DEBUG }eDebugStatus; typedef struct tDEBUGDICEBOX { bool isDice; // 生成されているか C3DObjectShape diceBox; // AABBボックス表示用本体 }TDEBUGDICEBOX; class CDebugMode { public: // デバッグモード画面用2Dポリゴン static C2DSpriteRHW m_pDebugMode; static LPSTR m_pDebugModeTexturePath; // デバッグモード終了用フラグ static bool m_isDebugMode; // 当たり判定確認用のボックス static C3DObjectShape m_pPlayerBox; static TDEBUGDICEBOX m_pDiceBox[49]; // デバッグの値 static float* m_pFps; // FPS static int* m_pTime; // ゲームの時間 static TFONTINFO m_font[ SELECT_DEBUG_NUM ]; // デバッグのフォント情報 static int m_fontIndex; // デバッグの選択インデックス番号 static bool m_debugOnOff; // デバッグのOnOFF機能があるもののフラグ // デバッグの項目を管理 static int m_leftRightIndexDir; // 左右の向き static int m_upDownIndexDir; // 上下の向き static int m_debugIndex; // デバッグの項目インデックス番号 static eDebugStatus m_eDebugStatus; // 現在の選択がどのデバッグの項目か private: // 各種フラグ static bool m_isCollisionBox; // 当たり判定チェック用ボックス表示フラグ static bool m_isFps; // FPS表示フラグ private: // コンストラクタ CDebugMode ( void ); CDebugMode ( CONST CDebugMode& debugMode ){} // コピーコンストラクタを防ぐ CDebugMode operator= ( CONST CDebugMode& debugMode ){} // メンバの代入を防ぐ public: // デストラクタ ~CDebugMode ( void ); //---------------------------------------------------- // 初期化 //---------------------------------------------------- static bool Load ( void ); static bool Init ( void ); static void Set ( int* pTime ); static bool InitDebugMode ( void ); //---------------------------------------------------- // 処理 //---------------------------------------------------- static void Run ( CDirectCamera* camera ); static void RunDebugMode ( void ); static void RunRight ( void ); // 右入力 static void RunLeft ( void ); // 左入力 static void RunUp ( void ); // 上入力 static void RunDown ( void ); // 下入力 static void RunEnter ( void ); // Enter入力 //---------------------------------------------------- // 描画 //---------------------------------------------------- static void Draw ( void ); static void DrawDebugMode ( void ); //---------------------------------------------------- // 終了 //---------------------------------------------------- static bool Uninit ( void ); //---------------------------------------------------- // @name DebugONOFF // @content デバッグのON/OFFの処理 // @param isOnOff ON/OFF // @param font* fontデータ1 // @param font2* fontデータ2 // @return none // @date 2014/1/22 //---------------------------------------------------- static void DebugONOFF ( bool isOnOff, TFONTINFO* font, TFONTINFO* font2 ); //---------------------------------------------------- // @name DigitUpDown // @content 値の調整 // @param pOut 調整し終わった値 // @param pDigit 調整したい値 // @param value 調整する量 // @return int* 調整し終わった値 // @date 2014/1/22 //---------------------------------------------------- static int* DigitUpDown ( int* pOut, int* pDigit, int value ); }; #endif _C_DEBUG_MODE_H_<file_sep>//---------------------------------------------------- // Macro // DirectXの自作マクロ関数群 // // @date 2013/9/15 // @author T.Kawashita //---------------------------------------------------- #ifndef _MACRO_H_ #define _MACRO_H_ #include <d3dx9.h> #include <stdio.h> #include <string> #include <stdarg.h> //---------------------------------------------------- // ポインタの解放 //---------------------------------------------------- template<class T> HRESULT SAFE_DELETE( T& t ) { if( t != nullptr ) { delete t; t = nullptr; return S_OK; } return E_FAIL; } //---------------------------------------------------- // ポインタ配列の解放 //---------------------------------------------------- template<class T> HRESULT SAFE_DELETE_ALLAY( T& t ) { if( t != nullptr ) { delete[] t; t = nullptr; return S_OK; } return E_FAIL; } //---------------------------------------------------- // Releseを使ったポインタの解放 //---------------------------------------------------- template<class T> HRESULT SAFE_DELETE_RELESE( T& t ) { if( t != nullptr ) { t->Release(); t = nullptr; return S_OK; } return E_FAIL; } //---------------------------------------------------- // freeを使用してのポインタの解放 //---------------------------------------------------- template<class T> HRESULT SAFE_DELETE_FREE( T& t ) { if( t != nullptr ) { free( t ); t = nullptr; return S_OK; } return E_FAIL; } //---------------------------------------------------- // 行列の内部データをコピー //---------------------------------------------------- inline D3DXMATRIX* CopyMatrix(D3DXMATRIX* pOut,CONST D3DXMATRIX* pIn) { memcpy( pOut,pIn,sizeof(D3DXMATRIX) ); return pOut; } //---------------------------------------------------- // 回転行列のみのコピー //---------------------------------------------------- inline D3DXMATRIX* CopyRotationMatrix(D3DXMATRIX* pOut,CONST D3DXMATRIX* pIn) { memcpy(pOut,pIn,sizeof(float)*12); return pOut; } //---------------------------------------------------- // @name COMBINE_STRING // @content 文字列を結合してSTLのstringに格納し渡す // @param num 文字列数 // @param str 文字列 // @param ... 文字列(可変引数なので何個でも) // @return std::string 結合した文字列 // @date 2013/11/13 //---------------------------------------------------- inline std::string COMBINE_STRING ( int num, const char* str, ... ) { const char* p; std::string comStr; va_list args; // 可変引数を格納しているリスト va_start( args, str ); p = str; for( int i = 0; i < num; ++ i ) { comStr.append( p ); p = va_arg( args, const char*); } va_end( args ); return comStr; } #endif _MACRO_H_<file_sep>//---------------------------------------------------- // CDirectLight Header // DirectXのカメラ // // @date 2013/5/1 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DIRECTX9_LIGHT_H_ #define _C_DIRECTX9_LIGHT_H_ #include <d3dx9.h> #include "CDirectX9FrameWork.h" class CDirectLight { private: D3DLIGHT9 light; public: CDirectLight ( void ); virtual ~CDirectLight ( void ); public: void Init ( void ); //---------------------------------------------------- // ライトのON OFF // @data true false // @return none //---------------------------------------------------- void Switch ( bool isLight ); //---------------------------------------------------- // ライトのセット // @data none // @return none //---------------------------------------------------- void Set ( void ); //---------------------------------------------------- // ライトの位置セット // @data xPos,yPos,zPos // @return none //---------------------------------------------------- void SetPosition ( float xPos,float yPos,float zPos ); //---------------------------------------------------- // ステージ全体のアンビエント光を設定 // @data ambient // @return none //---------------------------------------------------- void SetStageAmbient ( DWORD ambient ); }; #endif _C_DIRECTX9_LIGHT_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/2D/C2DSprite.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C2DSprite::C2DSprite( void ) { m_pos = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); m_size = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); // 頂点座標・色を初期化 for( int i = 0; i < 4; ++ i ){ m_vertex[i].pos.x = 0.0f; m_vertex[i].pos.y = 0.0f; m_vertex[i].pos.z = 0.0f; m_vertex[i].diffuse = D3DCOLOR_RGBA( 255, 255, 255, 255); } // 頂点のテクスチャセット this->SetUV(); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C2DSprite::~C2DSprite( void ) { } //---------------------------------------------------- // スプライトのセット //---------------------------------------------------- bool C2DSprite::SetSprite( CONST D3DXVECTOR3* pos, CONST D3DXVECTOR3* size ) { // スプライトの位置のセット this->SetSpritePos( pos->x, pos->y, pos->z ); // サイズのセット m_size.x = size->x; m_size.y = size->y; m_size.z = size->z; // 当たり判定とかに使用する for( int i = 0; i < 4; ++ i ) { m_vertex[i].diffuse = D3DCOLOR_RGBA( 255,255,255,255 ); } // 頂点座標をセット this->SetVertexPos(); // テクスチャ座標をセット this->SetUV(); return true; } //---------------------------------------------------- // スプライト位置のセット //---------------------------------------------------- void C2DSprite::SetSpritePos( CONST float x, CONST float y, CONST float z ) { m_pos.x = x; m_pos.y = y; m_pos.z = z; // 行列にも設定しておく this->SetWorldPos( &m_pos ); } //---------------------------------------------------- // スプライト位置の移動 //---------------------------------------------------- void C2DSprite::MoveSpritePos( CONST float x, CONST float y, CONST float z ) { m_pos.x = m_pos.x + x; m_pos.y = m_pos.y + y; m_pos.z = m_pos.z + z; this->SetWorldPos( &m_pos ); } //---------------------------------------------------- // スプライト位置の移動( vector指定 ) //---------------------------------------------------- void C2DSprite::MoveSpritePos( CONST D3DXVECTOR3* vec ) { m_pos.x = vec->x; m_pos.y = vec->y; m_pos.z = vec->z; this->SetWorldPos( &m_pos ); } //---------------------------------------------------- // スプライトの大きさをセット //---------------------------------------------------- void C2DSprite::SetSpriteSize( CONST float xSize, CONST float ySize ) { m_size.x = xSize; m_size.y = ySize; SetVertexPos(); } //---------------------------------------------------- // 頂点の座標セット //---------------------------------------------------- void C2DSprite::SetVertexPos( void ) { m_vertex[0].pos.x = -m_size.x / 2; m_vertex[0].pos.y = m_size.y / 2; m_vertex[0].pos.z = 0.0f; m_vertex[1].pos.x = m_size.x / 2; m_vertex[1].pos.y = m_size.y / 2; m_vertex[1].pos.z = 0.0f; m_vertex[2].pos.x = m_size.x / 2; m_vertex[2].pos.y = -m_size.y / 2; m_vertex[2].pos.z = 0.0f; m_vertex[3].pos.x = -m_size.x / 2; m_vertex[3].pos.y = -m_size.y / 2; m_vertex[3].pos.z = 0.0f; } //---------------------------------------------------- // テクスチャ座標セット //---------------------------------------------------- void C2DSprite::SetUV( void ) { m_vertex[0].tu = 0.0f; m_vertex[0].tv = 0.0f; m_vertex[1].tu = 1.0f; m_vertex[1].tv = 0.0f; m_vertex[2].tu = 1.0f; m_vertex[2].tv = 1.0f; m_vertex[3].tu = 0.0f; m_vertex[3].tv = 1.0f; } //---------------------------------------------------- // テクスチャ座標セット(UVパターンを設定) //---------------------------------------------------- void C2DSprite::SetUV( CONST UINT uPatern, CONST UINT vPatern, CONST UINT uNum, CONST UINT vNum ) { m_vertex[0].tu = 1.0f / uPatern * ( uNum - 1 ); m_vertex[0].tv = 1.0f / vPatern * ( vNum - 1 ); m_vertex[1].tu = 1.0f / uPatern * uNum; m_vertex[1].tv = 1.0f / vPatern * ( vNum - 1 ); m_vertex[2].tu = 1.0f / uPatern * uNum; m_vertex[2].tv = 1.0f / vPatern * vNum; m_vertex[3].tu = 1.0f / uPatern * ( uNum - 1 ); m_vertex[3].tv = 1.0f / vPatern * vNum; } //---------------------------------------------------- // 頂点色のセット //---------------------------------------------------- void C2DSprite::SetDiffuse( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ) { for( int i = 0; i < 4; ++ i ) { m_vertex[i].diffuse = D3DCOLOR_RGBA( r, g, b, a ); } } //---------------------------------------------------- // 板ポリゴンの行列をワールド行列に変換 //---------------------------------------------------- void C2DSprite::CalcWorldMtx( void ) { m_worldMtx._11 = 1.0f; m_worldMtx._12 = 0.0f; m_worldMtx._13 = 0.0f; m_worldMtx._21 = 0.0f; m_worldMtx._22 = 1.0f; m_worldMtx._23 = 0.0f; m_worldMtx._31 = 0.0f; m_worldMtx._32 = 0.0f; m_worldMtx._33 = 1.0f; m_worldMtx._14 = 0.0f; m_worldMtx._24 = 0.0f; m_worldMtx._34 = 0.0f; m_worldMtx._44 = 1.0f; }<file_sep>//---------------------------------------------------- // CSceneScore // スコア表示シーン // // @date 2014/2/20 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_SCORE_H_ #define _C_SCENE_SCORE_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourcePath.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../UserSource/CUserManager.h" class CSceneScore : public CSceneBase { private: // Result文字 C2DSpriteRHW *m_pHighScoreValue; LPSTR m_pResHighScoreValueFilePath; // スコア数字 LPSTR m_pResScoreDigitFilePath; // Score C2DSpriteRHW *m_pScoreValue; LPSTR m_pResScoreValueFilePath; C2DSpriteRHW *m_pScoreDigit; // MaxChain C2DSpriteRHW *m_pMaxChainValue; LPSTR m_pResMaxChainValueFilePath; C2DSpriteRHW *m_pMaxChainDigit; // 1〜6用 C2DSpriteRHW *m_pOnePip; LPSTR m_pResOneTextureFilePath; C2DSpriteRHW *m_pOnePipDigit; C2DSpriteRHW *m_pTwoPip; LPSTR m_pResTwoTextureFilePath; C2DSpriteRHW *m_pTwoPipDigit; C2DSpriteRHW *m_pThreePip; LPSTR m_pResThreeTextureFilePath; C2DSpriteRHW *m_pThreePipDigit; C2DSpriteRHW *m_pFourPip; LPSTR m_pResFourTextureFilePath; C2DSpriteRHW *m_pFourPipDigit; C2DSpriteRHW *m_pFivePip; LPSTR m_pResFiveTextureFilePath; C2DSpriteRHW *m_pFivePipDigit; C2DSpriteRHW *m_pSixPip; LPSTR m_pResSixTextureFilePath; C2DSpriteRHW *m_pSixPipDigit; int m_scoreDigitNum; int m_maxChainDigitNum; int m_oneDigitNum; int m_twoDigitNum; int m_threeDigitNum; int m_fourDigitNum; int m_fiveDigitNum; int m_sixDigitNum; public: CSceneScore ( void ); // コンストラクタ CSceneScore ( CSceneChange* sceneChange ); ~CSceneScore ( void ); // デストラクタ void Initialize ( void ) override; void Finalize ( void ) override; void Run ( void ) override; void Draw ( void ) override; bool Load ( void ) override; }; #endif _C_SCENE_SCORE_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/2D/C2DParticle.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C2DParticle::C2DParticle( void ) { m_speed = D3DXVECTOR3( 0.0f,0.0f,0.0f ); m_direct = D3DXVECTOR3( 0.0f,0.0f,0.0f ); m_life = 0; m_isExist = false; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C2DParticle::~C2DParticle( void ) { } //---------------------------------------------------- // パーティクルのセット //---------------------------------------------------- void C2DParticle::SetParticle( CONST D3DXVECTOR3* speed, CONST D3DXVECTOR3* dir, CONST UINT life ) { m_speed.x = speed->x; m_speed.y = speed->y; m_speed.z = speed->z; m_direct.x = dir->x; m_direct.y = dir->y; m_direct.z = dir->z; m_life = life; m_isExist = true; } //---------------------------------------------------- // パーティクルの移動 //---------------------------------------------------- void C2DParticle::Move( void ) { D3DXVECTOR3 workMove; // 移動用work workMove.x = this->GetPos()->x + m_speed.x * m_direct.x; workMove.y = this->GetPos()->y + m_speed.y * m_direct.y; workMove.z = this->GetPos()->z + m_speed.z * m_direct.z; // スプライトの位置を変更してその後ワールド位置も変更する this->MoveSpritePos( &workMove ); } <file_sep>//---------------------------------------------------- // CModeSelectPlayerManager // モードセレクト画面のプレイヤーのマネージャー // // @date 2014/2/7 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MODESELECT_PLAYER_MANAGER_ #define _C_MODESELECT_PLAYER_MANAGER_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSprite.h" //---------------------------------------------------- // モードセレクト用プレイヤー移動ステータス //---------------------------------------------------- typedef enum EMoveSelectMovePlayerStatus { eModeSelectPlayerMoveNone, eModeSelectPlayerMoveRight, eModeSelectPlayerMoveLeft, eModeSelectPlayerMoveUp, eModeSelectPlayerMoveDown, }eModeSelectMovePlayerStatus; class CModeSelectPlayerManager { private: C2DSprite* m_pModeSelectPlayer; LPSTR m_pResModeSelectPlayerPath; eModeSelectMovePlayerStatus m_eMovePlayerStatus; float m_moveValue; // 動いた量 public: CModeSelectPlayerManager ( void ); ~CModeSelectPlayerManager ( void ); public: // プレイヤーのステータスをセット void SetMovePlayerStatus ( CONST eModeSelectMovePlayerStatus playerStatus ) { m_eMovePlayerStatus = playerStatus; } // プレイヤーのステータスを取得 eModeSelectMovePlayerStatus GetMovePlayerStatus ( void ) { return m_eMovePlayerStatus; } public: bool Init ( void ); void Run ( void ); void Draw ( void ); bool Uninit ( void ); public: void MoveRight ( CONST float speed ); void MoveLeft ( CONST float speed ); void MoveUp ( CONST float speed ); void MoveDown ( CONST float speed ); }; #endif _C_MODESELECT_PLAYER_MANAGER_<file_sep>//---------------------------------------------------- // CColision Header // 当たり判定をまとめたヘッダー // // @date 2013/6/15 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_COLISION_H_ #define _C_COLISION_H_ #include <d3dx9.h> #include <math.h> //---------------------------------------------------- // バウンディングスフィア構造体定義 //---------------------------------------------------- typedef struct tagTHITCIRCLE { D3DXVECTOR3 boxCenter; // バウンディングスフィア中心座標 float r; // バウンディングスフィア半径 }THITCIRCLE; //---------------------------------------------------- // メッシュデータ構造体定義 //---------------------------------------------------- typedef struct tagTMESHDATA { D3DXVECTOR3 center; D3DXVECTOR3 size; D3DXVECTOR3 maxSize; D3DXVECTOR3 minSize; float rect; }TMESHDATA; //---------------------------------------------------- // AABB当たり判定用構造体定義 //---------------------------------------------------- typedef struct tagTHITAABB { D3DXVECTOR3 centerPos; // AABBの中心座標 D3DXVECTOR3 size; // AABBのサイズ D3DXVECTOR3 halfSize; // AABBの半分のサイズ }THITAABB; //---------------------------------------------------- // OBB用構造体定義 //---------------------------------------------------- typedef struct tagTHITOBB { D3DXVECTOR3 position; // 位置情報 D3DXVECTOR3 normalDir[3]; // 各方向情報 FLOAT normalLength[3]; // 各軸の長さ }THITOBB; //---------------------------------------------------- // 平面方程式が持つ4つの係数 //---------------------------------------------------- typedef struct tagPLANE { FLOAT a,b,c,d; }TPLANE; class CCollision { private: CCollision ( void ){} // コンストラクタを防ぐ CCollision ( CONST CCollision& colObj ){} // コピーコンストラクタを防ぐ CCollision operator= ( CONST CCollision& colObj ){} // メンバの代入を防ぐ public: // 唯一のインスタンスの取得 static CCollision* GetInstance ( void ) { static CCollision pDirectCollision; return &pDirectCollision; } // デストラクタ ~CCollision (void){} /* //==================================================== // 自身(矩形)と点の当たり判定 //==================================================== bool CDirectGraphics2D::HitPoint2Rect(float x, float y) { if((ver[0].pos.x+objData.centerX < x && ver[1].pos.x+objData.centerX > x) && (ver[0].pos.y+objData.centerY < y && ver[2].pos.y+objData.centerY > y)) return true; return false; } //==================================================== // 自身(円)と点の当たり判定 //==================================================== bool CDirectGraphics2D::HitPoint2Circle(float x, float y, float r) { double workX, workY; workX = pow((x - objData.centerX), 2); workY = pow((y - objData.centerY), 2); if((workX+workY) <= pow(r, 2)) return true; return false; } */ //---------------------------------------------------- // @name IsHitCircle // @content 球体同士の衝突判定 // @param circle1 球体1 // @param circle2 球体2 // @return 球体同士衝突しているかどうか // @date 2013/9/10 //---------------------------------------------------- bool IsHitCircle ( CONST THITCIRCLE* circle1, CONST THITCIRCLE* circle2 ); //---------------------------------------------------- // @name IsHitAABB // @content AABB同士の当たり判定 // @param aabb1 AABB1 // @param aabb2 AABB2 // @return AABB同士衝突しているかどうか // @date 2014/1/15 //---------------------------------------------------- bool IsHitAABB ( CONST THITAABB* aabb1, CONST THITAABB* aabb2 ); //---------------------------------------------------- // @name IsHitOBB // @content OBBによる衝突判定 // @param obb1 OBB1 // @param obb2 OBB2 // @return OBB同士衝突しているかどうか // @date 2013/9/10 //---------------------------------------------------- bool IsHitOBB ( CONST THITOBB* obb1,CONST THITOBB* obb2 ); public: //---------------------------------------------------- // @name SetOBB // @content OBB構造体にセット // @param pOutOBB* セットするOBB構造体のポインタ // @param pInLen 各軸の長さ // @param PInMtx モデル行列 // @return THITOBB 当たり判定に使うOBB構造体 // @date 2013/9/10 //---------------------------------------------------- THITOBB* SetOBB ( THITOBB* pOutOBB, CONST D3DXVECTOR3* pInLen, CONST D3DXMATRIX* pInMtx ); //---------------------------------------------------- // @name SetAABB // @content AABB構造体にセット // @param pOutAABB* セットしたいAABB構造体ポインタ // @param pInPos セットしたい中心座標 // @param pInSize セットしたいAABBのサイズ // @return THITAABB* セットしたAABB構造体ポインタ // @date 2014/1/15 //---------------------------------------------------- THITAABB* SetAABB ( THITAABB* pOutAABB, CONST D3DXVECTOR3* pInPos, CONST D3DXVECTOR3* pInSize ); //---------------------------------------------------- // @name GetMeshData // @content メッシュからメッシュデータを抜き出し // @param pOutMeshData 抜き出したいメッシュデータ構造体ポインタ // @param mesh 抜き出したいメッシュ // @return TMESHDATA* 抜き出したメッシュデータ // @date 2014/1/15 //---------------------------------------------------- TMESHDATA* GetMeshData ( TMESHDATA* pOutMeshData, LPD3DXMESH lpMesh ); //---------------------------------------------------- // @name CalcLenSegOnSeparateAxis // @content 分離軸に投影された軸成分から投影線分長を算出 // @param pSepAis 分離軸 // @param e1 軸成分1 // @param e2 軸成分2 // @param e3 軸成分3 // @return 投影された線分の長さ // @date 2013/9/10 //----------------------------------------------------- float CalcLenSegOnSeparateAxis( D3DXVECTOR3 *pSepAxis, D3DXVECTOR3 *e1, D3DXVECTOR3 *e2, D3DXVECTOR3 *e3 = nullptr ); //---------------------------------------------------- // @name CreatePlaneInfo // @content 平面方程式を求める // @param pOutPlane 求めた平面方程式 // @param v1 3角形の頂点座標 // @param v2 3角形の頂点座標 // @param v3 3角形の頂点座標 // @return 求めた平面方程式 // @date 2013/9/10 //---------------------------------------------------- TPLANE* CreatePlaneInfo( TPLANE* pOutPlane, CONST D3DXVECTOR3* v1, CONST D3DXVECTOR3* v2, CONST D3DXVECTOR3* v3 ); //---------------------------------------------------- // @name LineToPlaneCross // @content 直線と平面の交点を求める // @param pOutCross 求めた交点座標 // @param plane 平面方程式 // @param vTriPos 3角形のどれか一つの頂点座標 // @param vStartPos 直線が通る点(座標) // @param vDir 直線と平行なベクトル // @return 交点を求めることが出来たか // @date 2013/9/10 //---------------------------------------------------- bool LineToPlaneCross( D3DXVECTOR3* pOutCross, CONST TPLANE* plane, CONST D3DXVECTOR3* vTriPos, CONST D3DXVECTOR3* vStartPos, D3DXVECTOR3* vDir ); //---------------------------------------------------- // name CheckInTriangle // @content 3角形の内部にあるかどうかを判定 // @param v1 頂点座標1 // @param v2 頂点座標2 // @param v3 頂点座標3 // @param pos 判定したい座標 // @return 3角形の内部にあるかどうか // @date 2013/9/10 //---------------------------------------------------- bool CheckInTriangle( CONST D3DXVECTOR3* v1, CONST D3DXVECTOR3* v2, CONST D3DXVECTOR3* v3, CONST D3DXVECTOR3* pos ); //---------------------------------------------------- // @name LengthPontToPlane // @content 平面との距離を求める // @param pOutCrossPos 出力する交点座標 // @param vStartPos 視点となる座標 // @param plane 平面方程式 // @return 平面と始点の距離 // @date 2013/9/10 //---------------------------------------------------- float LengthPointToPlane( D3DXVECTOR3* pOutCrossPos, CONST D3DXVECTOR3* vStartPos, CONST TPLANE* plane ); }; #endif _C_COLISION_H_<file_sep> #include "CChainManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CChainManager::CChainManager( void ) { // チェイン管理配列を初期化 for( int i = 0; i < 50; ++ i ) { m_chain[i].isChain = false; m_chain[i].chainNo = 0; m_chain[i].chainNum = 0; m_chain[i].chainPip = 0; } this->Init(); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CChainManager::~CChainManager( void ) { } //---------------------------------------------------- // 初期化(毎回) //---------------------------------------------------- bool CChainManager::Init( void ) { m_connectDiceNum = 0; // 繋がったダイスの数を初期化 m_connectDiceList.clear(); // 繋がったダイスの格納用リスト初期化 // 全て判定していない状態にする for( int i = 0; i < BLOCK_DEFAULT_MAX_NUM; ++ i ) { m_decisionBlock[i] = false; } this->SetSize(); return true; } //---------------------------------------------------- // ブロック上のダイスのステータスを設定 //---------------------------------------------------- void CChainManager::SetStageBlockDiceStatus( UINT index ) { CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->SetStatus( e_statusStartDelete ); } //---------------------------------------------------- // Chain処理 //---------------------------------------------------- void CChainManager::Chain( CONST UINT index ) { // 初期化 this->Init(); // 現在のメインダイスの上面を取得 m_mainPip = CStageBlockManager::GetInstance()->GetStageBlock(index)->GetDice()->GetPip(); // 1の場合は特別な処理 if( m_mainPip == 1 ) { if( this->CheckChain( index ) == true ) { int oneNum = 0; this->CheckOne( index ); // ステージ上の1の目を判定 for( auto iterator = m_connectDiceList.begin(); iterator != m_connectDiceList.end(); ++ iterator ) { (*iterator)->SetStatus( DICE_STATUS::e_statusStartDelete ); // 消えるアニメーションにする oneNum ++; } // スコア m_pScore->m_record += m_chain[ CStageBlockManager::GetInstance()->GetStageBlock(index)->GetDice()->GetChainNo() ].chainNum * oneNum; // 1を消した数を更新 m_pScore->PipScoreAdd( m_mainPip, oneNum ); } } // 周りの面がチェインしていて上面が同じだったらこのダイスもチェイン中にする else if( this->CheckChain( index, m_mainPip ) == true ) { int chainNo = CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->GetChainNo(); // 自分自身のブロックは判定済みにしておく m_decisionBlock[ index ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice() ); // 周りのダイス(チェインしていない部分)判定 this->CheckAround( index ); // チェイン管理用配列の更新 m_chain[ chainNo ].chainNum ++; m_chain[ chainNo ].chainDiceNum += m_connectDiceNum; // 消えるアニメーションに遷移させる for( auto iterator = m_connectDiceList.begin(); iterator != m_connectDiceList.end(); ++ iterator ) { (*iterator)->SetChainNo( chainNo ); // チェイン番号をセット (*iterator)->SetIsChain( true ); // チェイン中に設定 (*iterator)->SetStatus( DICE_STATUS::e_statusStartDelete ); // プレイヤーの状態遷移 CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceDeleteStart ); } // スコアの設定 // スコア( 目 * ダイスの数 * チェイン数 + 1 ) m_pScore->m_record += m_mainPip * m_chain[ chainNo ].chainDiceNum * m_chain[ chainNo ].chainNum; // 消した数更新 m_pScore->PipScoreAdd( m_mainPip, 1 ); // マックスチェイン数更新 if( m_pScore->m_chainNum <= m_chain[chainNo].chainNum ) { m_pScore->m_chainNum = m_chain[chainNo].chainNum; } } // 1以外の場合は繋がったダイスの数によって判定 else { // 自分自身のブロックは判定済みにしておく m_decisionBlock[ index ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice() ); // 周りのダイス判定 this->CheckAround( index ); // 繋がったダイスがメインダイスの上面より多い場合は消える if( m_mainPip <= m_connectDiceNum ) { // チェイン管理配列にセット int chainNo; for( chainNo = 0; chainNo < 50; ++ chainNo ) { if( m_chain[chainNo].isChain == false ) break; } m_chain[chainNo].isChain = true; m_chain[chainNo].chainNo = chainNo; m_chain[chainNo].chainPip = m_mainPip; m_chain[chainNo].chainDiceNum = m_connectDiceNum; m_chain[chainNo].chainNum = 1; // 消えるアニメーションに遷移させる for( auto iterator = m_connectDiceList.begin(); iterator != m_connectDiceList.end(); ++ iterator ) { (*iterator)->SetChainNo( chainNo ); // チェイン番号をセット (*iterator)->SetIsChain( true ); // チェイン中に設定 (*iterator)->SetStatus( DICE_STATUS::e_statusStartDelete ); // メインのダイスが消えるアニメーションに遷移したらプレイヤーの状態を変える if( (*iterator)->GetIndexNo() == CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->GetIndexNo() ) { CPlayerManager::GetInstance()->SetPlayerStatus( ePlayerStatus::eOnDiceDeleteStart ); } } // スコアの処理 // スコア( 目 * ダイスの数 * チェイン数 + 1 ) m_pScore->m_record += m_mainPip * m_chain[chainNo].chainDiceNum * m_chain[chainNo].chainNum; // 消した数更新 m_pScore->PipScoreAdd( m_mainPip, m_chain[chainNo].chainDiceNum ); // マックスチェイン数更新 if( m_pScore->m_chainNum <= m_chain[chainNo].chainNum ) { m_pScore->m_chainNum = m_chain[chainNo].chainNum; } } } } //---------------------------------------------------- // 4方向とのダイスの判定(再帰関数) //---------------------------------------------------- int CChainManager::CheckAround( CONST UINT index ) { // 右判定 if( this->CheckRight( index ) ) { this->CheckAround( index + 1 ); } // 左のダイスとの判定 if( this->CheckLeft( index ) ) { this->CheckAround( index - 1 ); } // 前のダイスとの判定 if( this->CheckFront( index ) ) { this->CheckAround( index - m_zNum ); } // 後のダイスとの判定 if( this->CheckDown( index ) ) { this->CheckAround( index + m_zNum ); } return true; } //---------------------------------------------------- // 右方向の判定 //---------------------------------------------------- bool CChainManager::CheckRight( UINT index ) { // 添え字が一番右ではないか,右にダイスがあるか,まだ判定していないブロックか,まだチェインしていないダイスかどうか判定 if( index % m_xNum != m_xNum - 1 && CStageBlockManager::GetInstance()->GetIsOnDice( index + 1 ) == true && m_decisionBlock[ index + 1 ] == false && CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetIsChain() == false ) { if( m_mainPip == CStageBlockManager::GetInstance()->GetStageBlock(index + 1)->GetDice()->GetPip() && CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetStatus() == e_statusNormal ) { // 見つかった場合は判定済みにしカウントしてリストに追加 m_decisionBlock[ index + 1 ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice() ); return true; } } return false; } //---------------------------------------------------- // 左方向の判定 //---------------------------------------------------- bool CChainManager::CheckLeft( UINT index ) { // 添え字が一番左ではないか,左にダイスがあるか,まだ判定していないブロックか,まだチェインしていないかどうか判定 if( index % m_xNum != 0 && CStageBlockManager::GetInstance()->GetIsOnDice( index - 1 ) == true && m_decisionBlock[ index -1 ] == false && CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetIsChain() == false ) { // メインのダイスの上面と左のダイスの上面が同じかどうか,横のダイスが通常状態か判定 if( m_mainPip == CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetPip() && CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetStatus() == e_statusNormal ) { // 見つかった場合は判定済みにしカウントしてリストに追加 m_decisionBlock[ index - 1 ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice() ); return true; } } return false; } //---------------------------------------------------- // 前方向の判定 //---------------------------------------------------- bool CChainManager::CheckFront( UINT index ) { int workIndex = index; // メインダイスが一番前ではないか,前にダイスがあるか,まだ判定していないブロックか,まだチェインしていないかどうか判定 if( workIndex - m_zNum >= -1 && CStageBlockManager::GetInstance()->GetIsOnDice( index - m_zNum ) == true && m_decisionBlock[ index - m_zNum ] == false && CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetIsChain() == false ) { if( m_mainPip == CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetPip() && CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetStatus() == e_statusNormal ) { // 見つかった場合は判定済みにしカウントしてリストに追加 m_decisionBlock[ index - m_zNum ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice() ); return true; } } return false; } //---------------------------------------------------- // 後方向の判定 //---------------------------------------------------- bool CChainManager::CheckDown( UINT index ) { // メインダイスが一番後ではないか,後にダイスがあるか,まだ判定していないブロックか,まだチェインしていないか判定 if( index + m_zNum < CStageBlockManager::GetInstance()->GetDiceNum() && CStageBlockManager::GetInstance()->GetIsOnDice( index + m_zNum ) == true && m_decisionBlock[ index + m_zNum ] == false && CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetIsChain() == false ) { if( m_mainPip == CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetPip() && CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetStatus() == e_statusNormal ) { // 見つかった場合は判定済みにしカウントしてリストに追加 m_decisionBlock[ index + m_zNum ] = true; m_connectDiceNum ++; m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice() ); return true; } } return false; } //---------------------------------------------------- // 1の目かどうかを判定 //---------------------------------------------------- void CChainManager::CheckOne( CONST UINT index ) { // ステージに置かれているダイスが1かどうか判定してリストに入れる for( int i = 0; i < MAX_DICE_NUM; ++ i ) { // 自分の添え字は判定しない if( index == i ) continue; if( CStageBlockManager::GetInstance()->GetIsOnDice( i ) == true && CStageBlockManager::GetInstance()->GetStageBlock( i )->GetDice()->GetIsDice() == true && CStageBlockManager::GetInstance()->GetStageBlock( i )->GetDice()->GetPip() == 1 ) { m_connectDiceList.push_back( CStageBlockManager::GetInstance()->GetStageBlock( i )->GetDice() ); } } } //---------------------------------------------------- // 周りの面がチェインしているかどうか判定 //---------------------------------------------------- bool CChainManager::CheckChain( CONST UINT index ) { // 右判定 if( index % m_xNum != m_xNum - 1 && CStageBlockManager::GetInstance()->GetIsOnDice( index + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetIsChain() == true ) { return true; } // 左のダイスとの判定 if( index % m_xNum != 0 && CStageBlockManager::GetInstance()->GetIsOnDice( index -1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetIsChain() == true ) { return true; } // 前のダイスとの判定 if( index - m_zNum >= -1 && CStageBlockManager::GetInstance()->GetIsOnDice( index - m_zNum ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetIsChain() == true ) { return true; } // 後のダイスとの判定 if( index + m_zNum < CStageBlockManager::GetInstance()->GetDiceNum() == true && CStageBlockManager::GetInstance()->GetIsOnDice( index + m_zNum ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetIsChain() == true ) { return true; } return false; } //---------------------------------------------------- // 周り面が上面番号でチェインしているかどうか判定 //---------------------------------------------------- bool CChainManager::CheckChain( CONST UINT index, CONST UINT pip ) { // 右判定 if( index % m_xNum != m_xNum - 1 && CStageBlockManager::GetInstance()->GetIsOnDice( index + 1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetIsChain() == true && CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetPip() == pip && m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetChainNo()].chainDiceNum + 1 >= pip ) { CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->SetChainNo( m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index + 1 )->GetDice()->GetChainNo()].chainNo ); return true; } // 左のダイスとの判定 if( index % m_xNum != 0 && CStageBlockManager::GetInstance()->GetIsOnDice( index -1 ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetIsChain() == true && CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetPip() == pip && m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetChainNo()].chainDiceNum + 1 >= pip ) { CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->SetChainNo( m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index - 1 )->GetDice()->GetChainNo()].chainNo ); return true; } // 前のダイスとの判定 // −判定するためにキャスト if( (int)(index - m_zNum) >= -1 && CStageBlockManager::GetInstance()->GetIsOnDice( index - m_zNum ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetIsChain() == true && CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetPip() == pip && m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetChainNo()].chainDiceNum + 1 >= pip ) { CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->SetChainNo( m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index - m_zNum )->GetDice()->GetChainNo()].chainNo ); return true; } // 後のダイスとの判定 if( index + m_zNum < CStageBlockManager::GetInstance()->GetDiceNum() == true && CStageBlockManager::GetInstance()->GetIsOnDice( index + m_zNum ) == true && CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetIsChain() == true && CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetPip() == pip && m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetChainNo()].chainDiceNum + 1 >= pip ) { CStageBlockManager::GetInstance()->GetStageBlock( index )->GetDice()->SetChainNo( m_chain[CStageBlockManager::GetInstance()->GetStageBlock( index + m_zNum )->GetDice()->GetChainNo()].chainNo ); return true; } return false; }<file_sep> #include "CSceneTitle.h" //---------------------------------------------------- // タイトルシーンのコンストラクタ //---------------------------------------------------- CSceneTitle::CSceneTitle( CSceneChange* change) : CSceneBase(change) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneTitle::Load( void ) { m_pDirectCamera = new CDirectCamera(); m_pDirectCamera->Init(800,640); m_pDirectLight = new CDirectLight(); // Managerクラス m_pTitleBackManager = new CTitleBackManager(); // userのセット CUserManager::GetInstance()->Login(); DEBUG::PrintfColor(DEBUG::H_RED,"ユーザログイン\n"); return true; } //---------------------------------------------------- // タイトルシーンのデストラクタ //---------------------------------------------------- CSceneTitle::~CSceneTitle( void ) { SAFE_DELETE( m_pDirectCamera ); // カメラの解放 SAFE_DELETE( m_pDirectLight ); // ライトの解放 SAFE_DELETE( m_pTitleBackManager ); // 背景のマネージャークラス解放 } //---------------------------------------------------- // タイトル画面の初期化 //---------------------------------------------------- void CSceneTitle::Initialize( void ) { // Manager m_pTitleBackManager->Init(); } //---------------------------------------------------- // タイトルシーンの処理 //---------------------------------------------------- void CSceneTitle::Run( void ) { CInputKeyboard::GetInstance()->Update(); CJoyStick::GetInstance()->Update(); m_pTitleBackManager->Run(); // 背景処理 this->Draw(); // 描画 // スタートボタンが押されたらゲームスタート if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_SPACE ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_START ) ) { m_pTitleBackManager->SetIsFade( true ); } if( m_pTitleBackManager->GetIsFade() ) { if( m_pTitleBackManager->Fade() ) { mSceneChanger->ChangeScene( eSceneState::eSceneModeSelect ); } } // デバッグの時のみF1キーを押したらデバッグ画面に戻る #ifdef _DEBUG if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F1 ) ) { mSceneChanger->ChangeScene( eSceneState::eSceneDebug ); } #endif } //---------------------------------------------------- // タイトル画面の描画 //---------------------------------------------------- void CSceneTitle::Draw( void ) { m_pTitleBackManager->Draw(); // 背景描画 } //---------------------------------------------------- // タイトルシーンの終了 //---------------------------------------------------- void CSceneTitle::Finalize() { } <file_sep>//---------------------------------------------------- // CChainManager // ブロックがつながった時の処理 // // @date 2013/12/2 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_CHAIN_MANAGER_H_ #define _C_CHAIN_MANAGER_H_ #include <list> #include <vector> #include "../../ObjectSource/GameScene/CDiceObj.h" #include "CStageBlockManager.h" #include "../../PlayerSource/CPlayerManager.h" #include "../../ObjectSource/CScore.hpp" typedef struct TagChain { bool isChain; // チェイン中かどうか UINT chainNo; // チェイン番号 UINT chainPip; // チェインしている上面 UINT chainNum; // チェインしている数 UINT chainDiceNum; // チェインしているダイスの数 }tagChain; class CChainManager { private: std::list< CDiceObj* > m_connectDiceList; // 繋がったダイス格納用リスト tagChain m_chain[50]; // チェイン管理構造体配列 int m_connectDiceNum; // つながっている数 int m_mainPip; // メインダイスの上面保存用 int m_xNum; int m_yNum; int m_zNum; bool m_decisionBlock[BLOCK_DEFAULT_MAX_NUM]; // 判定したかどうかの配列 CScore* m_pScore; // スコア管理クラスから受け取るスコアのポインタ // コンストラクタ CChainManager ( void ); CChainManager ( CONST CChainManager& chainManager ){} // コピーコンストラクタを防ぐ CChainManager operator= ( CONST CChainManager& chainManager ){} // メンバの代入を防ぐ public: // 唯一のインスタンスの取得場所 static CChainManager* GetInstance ( void ) { static CChainManager chainManager; return &chainManager; } // デストラクタ ~CChainManager ( void ); //---------------------------------------------------- // ステージサイズをセット //---------------------------------------------------- void SetSize ( void ) { m_xNum = CStageBlockManager::GetInstance()->GetXNum(); m_yNum = CStageBlockManager::GetInstance()->GetYNum(); m_zNum = CStageBlockManager::GetInstance()->GetZNum(); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ); //---------------------------------------------------- // スコアのポインタをセット //---------------------------------------------------- void SetScore ( CScore* score ) { m_pScore = score; } //---------------------------------------------------- // @name SetStageBlockDiceStatus // @content ブロック上のダイスのステータスを設定 // @param index 変更したいダイスのインデックス番号 // @return none // @date 2013/12/9 //---------------------------------------------------- void SetStageBlockDiceStatus ( CONST UINT index ); //---------------------------------------------------- // @name Chain // @content つながったときの処理 // @param index メインブロックのインデックス番号 // @return none // @date 2013/12/2 // @update 2013/12/3 //---------------------------------------------------- void Chain ( CONST UINT index ); public: //---------------------------------------------------- // @name CheckAround // @content 周りのダイスとの判定(再帰関数) // @param index ブロックのインデックス番号 // @return none // @date 2013/12/3 //---------------------------------------------------- int CheckAround ( CONST UINT index ); bool CheckRight ( CONST UINT index ); // 右方向判定 bool CheckLeft ( CONST UINT index ); // 左方向判定 bool CheckFront ( CONST UINT index ); // 前方向判定 bool CheckDown ( CONST UINT index ); // 後方向判定 //---------------------------------------------------- // @name CheckOne // @content 1の目かどうかを判定 // @param index 自分自身のインデックス番号 // @return none // @date 2014/2/4 // @update 引数を追加(自分自身は消してはいけない) //---------------------------------------------------- void CheckOne ( CONST UINT index ); //---------------------------------------------------- // @name CheckChain // @content 周りの面が消えているかどうかチェック // @param index 調べたいインデックス番号 // @return bool チェインしている // @date 2014/2/5 //---------------------------------------------------- bool CheckChain ( CONST UINT index ); //---------------------------------------------------- // @name CheckChain // @content 周りの面が調べたい上面で消えているかどうかチェック // @param index 調べたいインデックス番号 // @param pip 調べたい上面番号 // @return bool 調べたい上面番号でチェインしている // @date 2014/2/10 //---------------------------------------------------- bool CheckChain ( CONST UINT index, CONST UINT pip ); //---------------------------------------------------- // チェイン管理配列を取得 //---------------------------------------------------- tagChain* GetChain ( CONST UINT chainNo ) { return &m_chain[ chainNo ]; } }; #endif _C_CHAIN_MANAGER_H_<file_sep>//---------------------------------------------------- // CScore // スコア // // @date 2014/2/9 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_SCORE_H_ #define _C_SCORE_H_ #include <Windows.h> class CScore { public: UINT m_oneChainNum; // ダイス1を消した回数 UINT m_twoChainNum; // ダイス2を消した回数 UINT m_threeChainNum; // ダイス3を消した回数 UINT m_fourChainNum; // ダイス4を消した回数 UINT m_fiveChainNum; // ダイス5を消した回数 UINT m_sixChainNum; // ダイス6を消した回数 UINT m_chainNum; // コンボ回数 UINT m_maxLinkNum; // 最大リンク回数 UINT m_record; // スコア public: //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CScore ( void ) { m_oneChainNum = 0; m_twoChainNum = 0; m_threeChainNum = 0; m_fourChainNum = 0; m_fiveChainNum = 0; m_sixChainNum = 0; m_chainNum = 0; m_maxLinkNum = 0; m_record = 0; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- ~CScore ( void ) { } public: //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ) { m_oneChainNum = 0; m_twoChainNum = 0; m_threeChainNum = 0; m_fourChainNum = 0; m_fiveChainNum = 0; m_sixChainNum = 0; m_chainNum = 0; m_maxLinkNum = 0; m_record = 0; return true; } //---------------------------------------------------- // @name PipScoreAdd // @content 上面によってスコア集計 // @param pip 消した上面 // @param diceNum 消した数 // @return none // @date 2014/2/12 //---------------------------------------------------- void PipScoreAdd ( CONST UINT pip, CONST UINT diceNum ) { switch( pip ) { case 1: m_oneChainNum += diceNum; break; case 2: m_twoChainNum += diceNum; break; case 3: m_threeChainNum += diceNum; break; case 4: m_fourChainNum += diceNum; break; case 5: m_fiveChainNum += diceNum; break; case 6: m_sixChainNum += diceNum; break; } } }; #endif _C_SCORE_H_<file_sep> #include "CSceneDebug.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneDebug::CSceneDebug( CSceneChange* change ) : CSceneBase( change ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSceneDebug::~CSceneDebug( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CSceneDebug::Initialize( void ) { CResourceManager::GetInstance()->CreateXFont( 0,15,30 ); CResourceManager::GetInstance()->CreateXFont( 99, 13, 20 ); m_fontIndex = 0; for( int i = 0; i < FONT_NUM; ++ i ) { m_fontColor[i] = DEFAULT_SCENE_COLOR; m_fontPos[i].x = 130.0f; m_fontPos[i].y = 150.0f + 40 * i; } m_fontColor[0] = SELECT_SCENE_COLOR; m_fontPos[0].x = 100.0f; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CSceneDebug::Run( void ) { CInputKeyboard::GetInstance()->Update(); CJoyStick::GetInstance()->Update(); if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetTriggerButton(0,XINPUT_GAMEPAD_DPAD_DOWN )) { m_fontColor[ m_fontIndex ] = DEFAULT_SCENE_COLOR; m_fontPos[ m_fontIndex ].x = 130.0f; m_fontIndex ++; if( m_fontIndex == FONT_NUM ) { m_fontIndex = 0; } m_fontColor[ m_fontIndex ] = SELECT_SCENE_COLOR; m_fontPos[ m_fontIndex ].x = 100.0f; } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) || CJoyStick::GetInstance()->GetTriggerButton(0,XINPUT_GAMEPAD_DPAD_UP )) { m_fontColor[ m_fontIndex ] = DEFAULT_SCENE_COLOR; m_fontPos[ m_fontIndex ].x = 130.0f; m_fontIndex --; if( m_fontIndex == -1 ) { m_fontIndex = FONT_NUM - 1; } m_fontColor[ m_fontIndex ] = SELECT_SCENE_COLOR; m_fontPos [m_fontIndex].x = 100.0f; } if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RETURN ) || CJoyStick::GetInstance()->GetReleaseButton( 0,XINPUT_GAMEPAD_A )) { switch( m_fontIndex ) { case 0: mSceneChanger->ChangeScene( eSceneState::eSceneTitle ); break; case 1: mSceneChanger->ChangeScene( eSceneState::eSceneModeSelect ); break; case 2: mSceneChanger->ChangeScene( eSceneState::eSceneGame ); break; case 3: mSceneChanger->ChangeScene( eSceneState::eSceneResult ); break; case 4: mSceneChanger->ChangeScene( eSceneState::eSceneModelView ); break; case 5: SendMessage( CWindowSystem::GethWnd(),WM_CLOSE,0,0 ); break; } } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSceneDebug::Draw( void ) { CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[0].x, (ULONG)m_fontPos[0].y, m_fontColor[0], "Title" ); CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[1].x, (ULONG)m_fontPos[1].y, m_fontColor[1], "ModeSelect"); CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[2].x, (ULONG)m_fontPos[2].y, m_fontColor[2], "GamePlay"); CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[3].x, (ULONG)m_fontPos[3].y, m_fontColor[3], "Result"); CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[4].x, (ULONG)m_fontPos[4].y, m_fontColor[4], "ModelView"); CResourceManager::GetInstance()->GetXFont(0)->DrawColor( (ULONG)m_fontPos[5].x, (ULONG)m_fontPos[5].y, m_fontColor[5], "Exit" ); } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CSceneDebug::Finalize( void ) { } //---------------------------------------------------- // Load //---------------------------------------------------- bool CSceneDebug::Load( void ) { return true; }<file_sep> #include "CDebugMode.h" C2DSpriteRHW CDebugMode::m_pDebugMode; LPSTR CDebugMode::m_pDebugModeTexturePath; bool CDebugMode::m_isDebugMode; float* CDebugMode::m_pFps = nullptr; int* CDebugMode::m_pTime = nullptr; C3DObjectShape CDebugMode::m_pPlayerBox; TDEBUGDICEBOX CDebugMode::m_pDiceBox[49]; bool CDebugMode::m_isCollisionBox; bool CDebugMode::m_isFps; TFONTINFO CDebugMode::m_font[ SELECT_DEBUG_NUM ]; int CDebugMode::m_fontIndex; bool CDebugMode::m_debugOnOff; int CDebugMode::m_leftRightIndexDir; int CDebugMode::m_upDownIndexDir; eDebugStatus CDebugMode::m_eDebugStatus; int CDebugMode::m_debugIndex; // ステータス管理用配列 const eDebugStatus debugStatus[ DEBUG_NUM ] = { eDebugStatus::FPS, eDebugStatus::COLLISION_BOX, eDebugStatus::GAME_TIME, eDebugStatus::EXIT_DEBUG }; const D3DXCOLOR defaultColor = DEFAULT_DEBUG_MODE_COLOR; //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CDebugMode::CDebugMode( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CDebugMode::~CDebugMode( void ) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CDebugMode::Load( void ) { // 画像ロード m_pDebugModeTexturePath = DEBUGMODE_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pDebugModeTexturePath ); m_pDebugMode.Init(); m_pDebugMode.SetVertexPos( 400.0f,320.0f,800.0f,640.0f ); m_pDebugMode.SetDiffuse( 0 , 255, 255, 200 ); // デバッグ用文字作成 CResourceManager::GetInstance()->CreateXFont( 1, 12, 20 ); return true; } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CDebugMode::Init( void ) { // デバッグ各種の状態 m_isCollisionBox = false; m_isFps = true; // 色の設定 for( int i = 0; i < SELECT_DEBUG_NUM; ++ i ) { m_font[i].cheack = false; m_font[i].color = DEFAULT_DEBUG_MODE_COLOR; } // 当たり判定用AABB表示フラグOFF for( int i = 0; i < 49; ++ i ) { m_pDiceBox[i].isDice = false; } // 最初の色の設定 m_font[0].cheack = true; m_font[3].cheack = true; return true; } //---------------------------------------------------- // デバッグ用値のセット //---------------------------------------------------- void CDebugMode::Set( int* pTime ) { m_pTime = pTime; // 時間のアドレスをセット } //---------------------------------------------------- // デバッグモードの初期化( 入るたびに毎回 ) //---------------------------------------------------- bool CDebugMode::InitDebugMode( void ) { // デバッグモードフラグON m_isDebugMode = true; // ステータス管理用変数 m_debugIndex = 0; m_debugOnOff = true; // ON m_eDebugStatus = eDebugStatus::FPS; m_leftRightIndexDir = 1; m_upDownIndexDir = 1; m_fontIndex = 0; for( int i = 0; i < SELECT_DEBUG_NUM; ++ i ) { if( m_font[i].cheack == true ) { m_font[i].color = SELECT_DEBUG_MODE_COLOR; } else { m_font[i].color = DEFAULT_DEBUG_MODE_COLOR; } } m_font[0].color = CHEACK_DEBUG_MODE_COLOR; return true; } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CDebugMode::Uninit( void ) { return true; } //---------------------------------------------------- // 動作 //---------------------------------------------------- void CDebugMode::Run( CDirectCamera* camera ) { float workDegree = 0.0f; // デバッグのためのカメラ回転 if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_F10 ) ) { workDegree = 1.0f; camera->LocalRotationQuaterY( workDegree ); } if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_F9 ) ) { workDegree = -1.0f; camera->LocalRotationQuaterY( workDegree ); } if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_F8 ) ) { workDegree = -1.0f; camera->LocalRotationQuaterX( workDegree ); } if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_F7 ) ) { workDegree = 1.0f; camera->LocalRotationQuaterX( workDegree ); } } //---------------------------------------------------- // デバッグモードの動作 //---------------------------------------------------- void CDebugMode::RunDebugMode( void ) { RunRight(); // 右入力 RunLeft(); // 左入力 RunUp(); // 上入力 RunDown(); // 下入力 RunEnter(); // Enter入力 } //---------------------------------------------------- // 右入力 //---------------------------------------------------- void CDebugMode::RunRight( void ) { if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_RIGHT )) { switch( m_eDebugStatus ) { case eDebugStatus::EXIT_DEBUG: return; case eDebugStatus::GAME_TIME: DigitUpDown( m_pTime, m_pTime, 60 ); break; default: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RIGHT ) ) { // 動かす前の色変更 if( m_font[ m_fontIndex ].cheack == true ) { m_font[ m_fontIndex ].color = SELECT_DEBUG_MODE_COLOR; } else { m_font[ m_fontIndex ].color = DEFAULT_DEBUG_MODE_COLOR; } // 動かした後の色変更 if( m_debugOnOff == true ) { m_fontIndex += 1; } else if( m_debugOnOff == false ) { m_fontIndex -= 1; } m_font[ m_fontIndex ].color = CHEACK_DEBUG_MODE_COLOR; m_debugOnOff ^= true; break; } } } } //---------------------------------------------------- // 左入力 //---------------------------------------------------- void CDebugMode::RunLeft( void ) { if( CInputKeyboard::GetInstance()->GetPressKeyState( VK_LEFT )) { switch( m_eDebugStatus ) { case eDebugStatus::EXIT_DEBUG: return; case eDebugStatus::GAME_TIME: DigitUpDown( m_pTime, m_pTime, -60 ); break; default: if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_LEFT ) ) { // 動かす前の色変更 if( m_font[ m_fontIndex ].cheack == true ) { m_font[ m_fontIndex ].color = SELECT_DEBUG_MODE_COLOR; } else { m_font[ m_fontIndex ].color = DEFAULT_DEBUG_MODE_COLOR; } // 動かした後の色変更 if( m_debugOnOff == true ) { m_fontIndex += 1; } else if( m_debugOnOff == false ) { m_fontIndex -= 1; } m_font[ m_fontIndex ].color = CHEACK_DEBUG_MODE_COLOR; m_debugOnOff ^= true; break; } } } } //---------------------------------------------------- // 上入力 //---------------------------------------------------- void CDebugMode::RunUp( void ) { if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) ) { if( m_font[ m_fontIndex ].cheack == true ) { m_font[ m_fontIndex ].color = SELECT_DEBUG_MODE_COLOR; } else { m_font[ m_fontIndex ].color = DEFAULT_DEBUG_MODE_COLOR; } // もし一番↑の場合 if( m_fontIndex <= 1 ) { m_fontIndex = SELECT_DEBUG_NUM - 1; m_debugIndex = DEBUG_NUM - 1; } else { if( m_eDebugStatus == eDebugStatus::EXIT_DEBUG ) { m_fontIndex -= 1; } else if( m_eDebugStatus == eDebugStatus::GAME_TIME ) { m_fontIndex -= 2; m_debugOnOff = true; } else { m_fontIndex -= 2; } m_debugIndex -= 1; } m_eDebugStatus = debugStatus[ m_debugIndex ]; m_font[ m_fontIndex ].color = CHEACK_DEBUG_MODE_COLOR; } } //---------------------------------------------------- // 下入力 //---------------------------------------------------- void CDebugMode::RunDown( void ) { if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN )) { if( m_font[ m_fontIndex ].cheack == true ) { m_font[ m_fontIndex ].color = SELECT_DEBUG_MODE_COLOR; } else if( m_font[ m_fontIndex ].cheack == false ) { m_font[ m_fontIndex ].color = DEFAULT_DEBUG_MODE_COLOR; } // ↓キー入力したときに一番下のExitが選択されていたら if( m_fontIndex == SELECT_DEBUG_NUM - 1 ) { m_fontIndex = 0; m_debugIndex = 0; m_leftRightIndexDir = 1; m_debugOnOff = true; m_eDebugStatus = debugStatus[ m_debugIndex ]; } // ↓キー通常選択状態 else { m_debugIndex += 1; m_eDebugStatus = debugStatus[ m_debugIndex ]; if( ( m_eDebugStatus == eDebugStatus::GAME_TIME && m_debugOnOff == false ) || m_eDebugStatus == eDebugStatus::EXIT_DEBUG ) { m_fontIndex += 1; } else { m_fontIndex += 2; } } m_font[ m_fontIndex ].color = CHEACK_DEBUG_MODE_COLOR; } } //---------------------------------------------------- // Enter入力 //---------------------------------------------------- void CDebugMode::RunEnter( void ) { // 確定ボタン(ENTER) if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RETURN ) ) { switch( m_eDebugStatus ) { // FPS表示 case eDebugStatus::FPS: m_isFps = m_debugOnOff; DebugONOFF( m_isFps, &m_font[0], &m_font[1] ); break; // 当たり判定用ボックス case eDebugStatus::COLLISION_BOX: m_isCollisionBox = m_debugOnOff; DebugONOFF( m_isCollisionBox, &m_font[2], &m_font[3] ); break; // ゲームの時間 case eDebugStatus::GAME_TIME: break; // Exit case eDebugStatus::EXIT_DEBUG: m_isDebugMode = false; break; } } } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CDebugMode::Draw( void ) { // FPS表示 if( m_isFps == true ) { CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 0, 0, D3DXCOLOR( 255,255,255,255 ), "FPS:%4.2f", *m_pFps ); } // 当たり判定用ボックス if( m_isCollisionBox == true ) { // プレイヤー用AABB CDirectDrawSystem::GetInstance()->DrawShape( m_pPlayerBox.GetWorldMtx(), m_pPlayerBox.GetMaterial(), m_pPlayerBox.GetMesh() ); // ダイス用AABB for( int i= 0; i< 49; ++ i ) { if( m_pDiceBox[i].isDice == true ) { CDirectDrawSystem::GetInstance()->DrawShape( m_pDiceBox[i].diceBox.GetWorldMtx(), m_pDiceBox[i].diceBox.GetMaterial(), m_pDiceBox[i].diceBox.GetMesh() ); } } } } //---------------------------------------------------- // デバッグモード画面の描画 //---------------------------------------------------- void CDebugMode::DrawDebugMode( void ) { // 背景 CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pDebugModeTexturePath )->Get(),m_pDebugMode.GetVertex() ); // タイトル CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 340, 110, D3DXCOLOR(255,255,0,255), "Debug Mode" ); // FPS CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 100, 150, defaultColor, "FPS" ); CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 400, 150, m_font[0].color, "ON" ); CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 500, 150, m_font[1].color, "OFF" ); // 当たり判定用AABBBOXの表示 CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 100, 180, defaultColor, "HitCheack AABBBOX" ); CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 400, 180, m_font[2].color, "ON" ); CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 500, 180, m_font[3].color, "OFF" ); // Time CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 100, 210, defaultColor, "Time Change" ); CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 400, 210, m_font[4].color, "%d", *m_pTime ); // Exit CResourceManager::GetInstance()->GetXFont( 1 )->DrawColor( 380, 500, m_font[ SELECT_DEBUG_NUM - 1 ].color, "Exit" ); } //---------------------------------------------------- // デバッグのON/OFFの切り替え //---------------------------------------------------- void CDebugMode::DebugONOFF( bool isOnOff, TFONTINFO* font, TFONTINFO* font2 ) { if( isOnOff == true ) { font->cheack = true; font2->cheack = false; font2->color = DEFAULT_DEBUG_MODE_COLOR; } else if( isOnOff == false ) { font->cheack = false; font->color = DEFAULT_DEBUG_MODE_COLOR; font2->cheack = true; } } //---------------------------------------------------- // 値の調整 //---------------------------------------------------- int* CDebugMode::DigitUpDown( int* pOut, int* pDigit, int value ) { *pOut = *pDigit + value; return pOut; }<file_sep>//---------------------------------------------------- // CModeSelectBackManager // モードセレクト画面の背景マネージャー // // @date 2014/2/4 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MODESELECT_BACK_MANAGER_ #define _C_MODESELECT_BACK_MANAGER_ #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourcePath.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/CObjectBase.hpp" #include "../../ObjectSource/ModeSelect/CMessageBar.h" typedef enum { eMessageBarNone, eMessageBarAnimation, eMessageBarNormal }eMessageBarStatus; class CModeSelectBackManager { private: CObjectBase* m_pModeSelectStage; LPSTR m_pResModeSelectStageFilePath; // αブレンド用 C2DSpriteAlphaBlend* m_pAlphaBlend; // メニューの文字 C2DSpriteAlphaBlend* m_pMenuValue; LPSTR m_pResMenuValueFilePath; // モードセレクト画面のメッセージバー CMessageBar* m_pMessageBar; LPSTR m_pResMessageBar[6]; int m_resIndexNo; eMessageBarStatus m_eMessageBarStatus; bool m_isBarAnimation; bool m_isAlphaBlend; public: CModeSelectBackManager ( void ); // コンストラクタ ~CModeSelectBackManager ( void ); // デストラクタ public: // メッセージバーのステータス取得 eMessageBarStatus GetMessageBarStatus ( void ) { return m_eMessageBarStatus; } // メッセージバーのステータスセット void SetMessageBarStatus ( CONST eMessageBarStatus messageBarStatus ) { m_eMessageBarStatus = messageBarStatus; } public: bool Init ( void ); // 初期化 void Run ( void ); // 処理 void Draw ( void ); // 描画 void DrawAlpha ( void ); // αブレンド用画像の描画 bool Uninit ( void ); // 終了 public: void RunKey ( CONST UINT index ); // キー入力 void RunKeyEnter ( void ); // エンターキー押されたら呼ぶ関数 bool MessageBarAnimation ( void ); // メッセージバーのアニメーション bool Fade ( void ); // フェードアウト }; #endif _C_MODESELECT_BACK_MANAGER_<file_sep>//---------------------------------------------------- // CResourcePath // リソースのファイルパスのみを定義したもの // // @date 2014/1/14 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_RESOURCE_PATH_H_ #define _C_RESOURCE_PATH_H_ // オブジェクト用ファイルパス CONST LPSTR PLAYER_PNGPATH = "resource/2D/player/player.png"; // プレイヤーのファイルパス CONST LPSTR DICE_XFILEPATH = "resource/xFile/dice.x"; // サイコロのファイルパス CONST LPSTR PARTICLE_PNGPATH = "resource/2D/particle.png"; // 雪 // タイトル用ファイルパス CONST LPSTR TITLE_BACK_PNGPATH = "resource/2D/title/titleBack.png"; CONST LPSTR TITLELOG_PNGPATH = "resource/2D/title/title.png"; CONST LPSTR TITLE_REMAKE_PNGPATH = "resource/2D/title/remake.png"; CONST LPSTR PUSHSTART_PNGPATH = "resource/2D/title/pushStartPlay.png"; CONST LPSTR VIEWMODE_PNGPATH = "resource/2D/title/modelViewMode.png"; CONST LPSTR EXIT_PNGPATH = "resource/2D/title/exit.png"; CONST LPSTR TITLEEFFECT_PNGPATH = "resource/2D/title/titleEffect.png"; // モードセレクト用ファイルパス CONST LPSTR MODE_STAGE_XFILEPATH = "resource/xFile/modeSelectStage.x"; CONST LPSTR MODE_MENU_PNGPATH = "resource/2D/modeselect/menu.png"; CONST LPSTR MODE_TITLEMESSAGE_PNGPATH = "resource/2D/modeselect/title.png"; CONST LPSTR MODE_EXITMESSAGE_PNGPATH = "resource/2D/modeselect/exit.png"; CONST LPSTR MODE_GAMEPLAYMESSAGE_PNGPATH = "resource/2D/modeselect/gameplay.png"; CONST LPSTR MODE_RANKINGMESSAGE_PNGPATH = "resource/2D/modeselect/ranking.png"; CONST LPSTR MODE_RECORDMESSAGE_PNGPATH = "resource/2D/modeselect/record.png"; CONST LPSTR MODE_OPTIONMESSAGE_PNGPATH = "resource/2D/modeselect/option.png"; // ゲーム用ファイルパス CONST LPSTR GAME_STAGE_XFILEPATH = "resource/xFile/stage.x"; CONST LPSTR GAME_DICEINFO_PNGPATH = "resource/2D/game/info.png"; CONST LPSTR GAME_SCOREVALUE_PNGPATH = "resource/2D/game/score.png"; CONST LPSTR GAME_SCOREDIGIT_PNGPATH = "resource/2D/game/scoreDigit.png"; // タイム用ファイルパス CONST LPSTR TIME_PNGPATH = "resource/2D/game/time.png"; CONST LPSTR TIMEDIGIT_PNGPATH = "resource/2D/game/timeDigit.png"; CONST LPSTR TIMEUP_PNGPATH = "resource/2D/game/timeup.png"; CONST LPSTR TIMEUP_PUSHENTER_PNGPATH = "resource/2D/game/pushEnter.png"; // ポーズ用ファイルパス CONST LPSTR PAUSE_BACK_PNGPATH = "resource/2D/pause/back.png"; CONST LPSTR PAUSE_PNGPATH = "resource/2D/pause/pause.png"; CONST LPSTR RETRY_PNGPATH = "resource/2D/pause/retry.png"; CONST LPSTR RESUME_PNGPATH = "resource/2D/pause/resume.png"; CONST LPSTR BACKTITLE_PNGPATH = "resource/2D/pause/backTitle.png"; CONST LPSTR CURSOL_PNGPATH = "resource/2D/pause/cursol.png"; CONST LPSTR PAUSEEFFECT_PNGPATH = "resource/2D/pause/pauseEffect.png"; // デバッグ用ファイルパス CONST LPSTR DEBUGMODE_PNGPATH = "resource/2D/debug/debugBack.png"; // リザルト用ファイルパス CONST LPSTR RESULT_RESULTVALUE_PNGPATH = "resource/2D/result/resultValue.png"; CONST LPSTR RESULT_SCOREDIGIT_PNGPATH = "resource/2D/result/scoreDigit.png"; CONST LPSTR RESULT_SCOREVALUE_PNGPATH = "resource/2D/result/scoreValue.png"; CONST LPSTR RESULT_MAXCHAIN_PNGPATH = "resource/2D/result/maxChain.png"; CONST LPSTR RESULT_ONE_PNGPATH = "resource/2D/result/one.png"; CONST LPSTR RESULT_TWO_PNGPATH = "resource/2D/result/two.png"; CONST LPSTR RESULT_THREE_PNGPATH = "resource/2D/result/three.png"; CONST LPSTR RESULT_FOUR_PNGPATH = "resource/2D/result/four.png"; CONST LPSTR RESULT_FIVE_PNGPATH = "resource/2D/result/five.png"; CONST LPSTR RESULT_SIX_PNGPATH = "resource/2D/result/six.png"; CONST LPSTR RESULT_PUSHENTER_PNGPATH = "resource/2D/result/pushEnter.png"; // ハイスコア用ファイルパス CONST LPSTR SCORE_HIGHSCORE_VALUE_PNGPATH = "resource/2D/highScore/highScore.png"; // モデルビュー用ファイルパス CONST LPSTR modelViewPath = "resource/ModelView/goldskybill.x"; #endif _C_RESOURCE_PATH_H_<file_sep>//---------------------------------------------------- // CSnowObj Class // 雪のオブジェクラス // // @author T.Kawashita //---------------------------------------------------- #pragma once #include <Windows.h> #include <d3dx9.h> #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DParticle.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CRandSystem.hpp" // 定数 #define SNOW_CNT ( 100 ) class CSnowObj { private: CRandSystem *m_rand; // 乱数 C2DParticle *m_snow; // パーティクルの粒子 LPSTR m_pResSnowFilePath; // 雪画像のファイルパス public: CSnowObj(); ~CSnowObj(); public: void Emitter ( void ); void Move ( void ); void Draw ( CDirectCamera* directCamera ); public: /* //---------------------------------------------------- // 雪画像取得 //---------------------------------------------------- const CDirectResource2D* GetTexture (void) { return m_resSnow; } */ // ビルボード用の行列の取得 CONST D3DXMATRIX* GetMat( int snowNo ) { return m_snow[snowNo].GetWorldMtx(); } // ビルボード用の頂点情報の取得 tagTSPRITE* GetVertex( int snowNo ) { return m_snow[snowNo].GetVertex(); } };<file_sep>//---------------------------------------------------- // CDebugStage // デバッグステージ // // @date 2013/9/8 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DEBUG_STAGE_H_ #define _C_DEBUG_STAGE_H_ #include <d3dx9.h> #include "../UtilityHeader/Macro.hpp" // デバッグ用の頂点構造体 typedef struct TAGtDEBUGVERTEX { D3DXVECTOR3 pos; D3DCOLOR color; }tagTDEBUGVERTEX; class CDebugStage { private: tagTDEBUGVERTEX* m_pLineStage; UINT m_lineNum; public: CDebugStage ( void ); CDebugStage ( CONST UINT lineNum ); ~CDebugStage ( void ); public: //---------------------------------------------------- // @name Init // @content 原点から正方形のステージを作成するための初期化 // @param lineLen 線の長さ // @return none // @date 2013/9/8 //---------------------------------------------------- void Init ( CONST FLOAT lineLen ); // 終了処理 void Uninit ( void ); public: //---------------------------------------------------- // @name GetLineNum // @content ライン数の取得 // @param none // @return UINT ライン数 // @date 2013/9/8 //---------------------------------------------------- CONST UINT GetLineNum ( void ) { return m_lineNum; } //---------------------------------------------------- // @name GetVertex // @content 頂点情報の取得 // @param none // @return tagTDEBUGVERTEX* 頂点情報 // @date 2013/9/8 //---------------------------------------------------- tagTDEBUGVERTEX* GetVertex ( void ) { return m_pLineStage; } }; #endif _C_DEBUG_STAGE_H_<file_sep>//---------------------------------------------------- // CSceneBase Class // Sceneの基底クラス // 各種シーンに派生させる // // @date 2013/6/10 // @auter T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_BASE_H_ #define _C_SCENE_BASE_H_ #include "CSceneChange.hpp" #include "../DirectX9Header/CDirectX9DrawSystem.h" #include "../DirectX9Header/CDirectX9Camera.h" class CSceneBase { protected: CSceneChange* mSceneChanger; // クラス所有元にシーン切り替えを伝えるインターフェイス public: // コンストラクタ CSceneBase( CSceneChange* changer ) { mSceneChanger = changer; } CSceneBase(){} virtual ~CSceneBase(){} public: virtual void Initialize(){} // 初期化処理 virtual void Finalize(){} // 終了処理 virtual void Run() {} // 更新処理 virtual void Draw(){} // 描画処理 virtual bool Load(){return true;} // ロード処理 }; #endif _C_SCENE_BASE_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/Billboard/CBillBoard.h" //---------------------------------------------------- // 中心を原点とした頂点座標をセットする関数(3D空間) //---------------------------------------------------- void CBillBoard::SetVertex() { m_vertex[0].pos.x = -m_size.x / 2; m_vertex[0].pos.y = m_size.y / 2; m_vertex[0].pos.z = 0.0f; m_vertex[0].color = m_color; m_vertex[0].tu = 0.0f; m_vertex[0].tv = 0.0f; m_vertex[1].pos.x = m_size.x / 2; m_vertex[1].pos.y = m_size.y / 2; m_vertex[1].pos.z = 0.0f; m_vertex[1].color = m_color; m_vertex[1].tu = 1.0f; m_vertex[1].tv = 0.0f; m_vertex[2].pos.x = m_size.x / 2; m_vertex[2].pos.y = -m_size.y / 2; m_vertex[2].pos.z = 0.0f; m_vertex[2].color = m_color; m_vertex[2].tu = 1.0f; m_vertex[2].tv = 1.0f; m_vertex[3].pos.x = -m_size.x / 2; m_vertex[3].pos.y = -m_size.y / 2; m_vertex[3].pos.z = 0.0f; m_vertex[3].color = m_color; m_vertex[3].tu = 0.0f; m_vertex[3].tv = 1.0f; } //---------------------------------------------------- // 左上を原点をした頂点座標をセットする関数(2D空間) //---------------------------------------------------- void CBillBoard::SetVertex( int windowX, int windowY ) { m_vertex[0].pos.x = -m_size.x / 2 - windowX / 2; m_vertex[0].pos.y = m_size.y / 2 + windowY / 2; m_vertex[0].pos.z = 0.0f; m_vertex[0].color = m_color; m_vertex[0].tu = 0.0f; m_vertex[0].tv = 0.0f; m_vertex[1].pos.x = m_size.x / 2 + windowX / 2; m_vertex[1].pos.y = m_size.y / 2 + windowY / 2; m_vertex[1].pos.z = 0.0f; m_vertex[1].color = m_color; m_vertex[1].tu = 1.0f; m_vertex[1].tv = 0.0f; m_vertex[2].pos.x = m_size.x / 2 + windowX / 2; m_vertex[2].pos.y = -m_size.y / 2 - windowY / 2; m_vertex[2].pos.z = 0.0f; m_vertex[2].color = m_color; m_vertex[2].tu = 1.0f; m_vertex[2].tv = 1.0f; m_vertex[3].pos.x = -m_size.x / 2 - windowX / 2; m_vertex[3].pos.y = -m_size.y / 2 - windowY / 2; m_vertex[3].pos.z = 0.0f; m_vertex[3].color = m_color; m_vertex[3].tu = 0.0f; m_vertex[3].tv = 1.0f; } //---------------------------------------------------- // 位置をセット //---------------------------------------------------- void CBillBoard::SetPosition(float x,float y,float z) { m_pos.x = x; m_pos.y = y; m_pos.z = z; } //---------------------------------------------------- // ビルボードのセット //---------------------------------------------------- void CBillBoard::SetBillboard( float xSize,float ySize,D3DCOLOR color ) { m_size.x = xSize; m_size.y = ySize; m_color = color; this->SetMaxAlfa( this->GetAlfa() ); D3DXMatrixIdentity( &m_mtx ); this->SetVertex(); } //---------------------------------------------------- // ビルボードのセット // XとY両方同じ大きさ //---------------------------------------------------- void CBillBoard::SetBillboard( float size,D3DCOLOR color ) { m_size.x = size; m_size.y = size; m_color = color; this->SetMaxAlfa( this->GetAlfa() ); D3DXMatrixIdentity( &m_mtx ); this->SetVertex(); } //---------------------------------------------------- // 更新したα値のセット //---------------------------------------------------- void CBillBoard::SetAlfa( int alfa ) { m_color = D3DCOLOR_ARGB( alfa,255,255,255 ); m_vertex[0].color = m_color; m_vertex[1].color = m_color; m_vertex[2].color = m_color; m_vertex[3].color = m_color; } //---------------------------------------------------- // 更新したα値のセット //---------------------------------------------------- void CBillBoard::SetDiffuse( int alfa ) { int r,g,b; r = m_color >> 16; g = m_color >> 8; b = m_color >> 0; m_color = D3DCOLOR_ARGB( alfa,r,g,b ); m_vertex[0].color = m_color; m_vertex[1].color = m_color; m_vertex[2].color = m_color; m_vertex[3].color = m_color; } //---------------------------------------------------- // マックスα値のセット //---------------------------------------------------- void CBillBoard::SetMaxAlfa( int maxAlfa ) { m_maxAlfa = maxAlfa; }<file_sep>//---------------------------------------------------- // CPlayerManager // プレイヤーの管理クラス // // @date 2013/12/12 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_PLAYER_MANAGER_H_ #define _C_PLAYER_MANAGER_H_ #include <d3dx9.h> #include "CPlayer.h" #include "../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../SceneSource/DebugScene/CDebugMode.h" #include "../ManagerSource/GameScene/CDiceObjManager.h" #include "../ManagerSource/GameScene/CStageBlockManager.h" #include "../ManagerSource/GameScene/CDiceInfoManager.h" class CPlayerManager { private: CPlayer* m_pPlayer; LPSTR m_pPlayerFilePath; // プレイヤーの画像ファイルパス CDiceInfoManager* m_pDiceInfoManager; // コンストラクタ CPlayerManager ( void ); CPlayerManager ( CONST CPlayerManager& playerManager ){} // コピーコンストラクタ禁止 CPlayerManager operator= ( CONST CPlayerManager& playerManager ){} // オペレータオーバロード禁止 public: // インスタンス取得場所 static CPlayerManager* GetInstance( void ) { static CPlayerManager playerManager; return &playerManager; } public: // デストラクタ ~CPlayerManager ( void ); //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ); //---------------------------------------------------- // 終了 //---------------------------------------------------- bool Uninit ( void ); //---------------------------------------------------- // 描画 //---------------------------------------------------- void Draw ( void ); //---------------------------------------------------- // プレイヤーの処理 //---------------------------------------------------- void Run ( void ); //---------------------------------------------------- // @name Move // @content プレイヤーの移動 // @param none // @return none // @date 2013/12/13 //---------------------------------------------------- void Move ( void ); //---------------------------------------------------- // 各方向へ移動 //---------------------------------------------------- void MoveRight ( void ); void MoveLeft ( void ); void MoveFront ( void ); void MoveBack ( void ); //---------------------------------------------------- // @name IsHitPlayerToDiceX,Z // @content プレイヤーとダイスの当たり判定 // @param distance 調整用値 // @return bool 当たっていない状態になったらtrue // @date 2014/1/30 //---------------------------------------------------- bool IsHitPlayerToDiceX ( CONST float distance, CDiceObj* dice ); bool IsHitPlayerToDiceZ ( CONST float distance, CDiceObj* dice ); //---------------------------------------------------- // @name Down // @content プレイヤーの落下処理 // @param none // @return none // @date 2014/1/27 //---------------------------------------------------- void Down ( void ); //---------------------------------------------------- // @name Up // @content プレイヤーの上昇処理 // @param speed 速度 // @return none // @date 2014/1/31 //---------------------------------------------------- void Up ( CONST float speed ); //---------------------------------------------------- // @name SetCameraToMtx // @content カメラの行列をプレイヤーの行列にセット // @param view カメラ行列 // @return none // @date 2013/12/20 // @update 2014/1/15 引数を一つに設定し直し // @update 2014/1/28 引数をなしに設定 //---------------------------------------------------- void SetCameraToMtx ( CONST D3DXMATRIX* view ); //---------------------------------------------------- // @name SetPlayerStatus // @content プレイヤーのステータス変更 // @param playerStatus 変更したいステータス // @return none // @date 2014/1/31 //---------------------------------------------------- void SetPlayerStatus ( CONST ePlayerStatus playerStatus ) { m_pPlayer->SetPlayerStatus( playerStatus ); } //---------------------------------------------------- // @name SetPlayerPos // @content プレイヤーの位置変更 // @param xPos X座標 // @param yPos Y座標 // @param zPos Z座標 // @return none // @date 2014/1/31 //---------------------------------------------------- void SetPlayerPos ( CONST float xPos, CONST float yPos, CONST float zPos ) { m_pPlayer->SetSpritePos( xPos, yPos, zPos ); } //---------------------------------------------------- // プレイヤーのステータス取得 //---------------------------------------------------- CONST ePlayerStatus GetPlayerStatus( void ) { return m_pPlayer->GetPlayerStatus(); } //---------------------------------------------------- // プレイヤーの位置取得 //---------------------------------------------------- CONST D3DXVECTOR3* GetPlayerPos( void ) { return m_pPlayer->GetPos(); } //---------------------------------------------------- // プレイヤーの色変更 //---------------------------------------------------- void BrightChange( bool isBright ) { if( isBright == false ) { m_pPlayer->SetDiffuse( 50, 50, 50, 255 ); } else { m_pPlayer->SetDiffuse( 255, 255, 255, 255 ); } } //---------------------------------------------------- // INFO用マネージャーのセット //---------------------------------------------------- void SetDiceInfoManager ( CDiceInfoManager* diceInfoManager ) { m_pDiceInfoManager = diceInfoManager; } }; #endif _C_PLAYER_MANAGER_H_<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/3D/C3DObjectAlphaBlend.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C3DObjectAlphaBlend::C3DObjectAlphaBlend( void ) { this->SetColor( 255,255,255,255 ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C3DObjectAlphaBlend::~C3DObjectAlphaBlend( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool C3DObjectAlphaBlend::Init( void ) { CObjectBase::Init(); this->SetColor( 255,255,255,255 ); return true; } //---------------------------------------------------- // 色の設定 //---------------------------------------------------- void C3DObjectAlphaBlend::SetColor( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ) { m_color.r = ( float )( r / 255.0f ); m_color.g = ( float )( g / 255.0f ); m_color.b = ( float )( b / 255.0f ); m_color.a = ( float )( a / 255.0f ); } //---------------------------------------------------- // 色の取得 //---------------------------------------------------- D3DXCOLOR* C3DObjectAlphaBlend::GetColor( void ) { return &m_color; }<file_sep>//---------------------------------------------------- // CDiceObj // 3Dのサイコロオブジェクト // // @date 2013/11/20 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DICE_OBJ_H_ #define _C_DICE_OBJ_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/3D/C3DObjectAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CCollision.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" #define ROLL_RIGTH_PIP ( 1 ) #define ROLL_LEFT_PIP ( 2 ) #define ROLL_FRONT_PIP ( 3 ) #define ROLL_BACK_PIP ( 4 ) #define ROLL_HALFH_PIP ( 5 ) // 左右180°回転 #define ROLL_HALFV_PIP ( 6 ) // 上下180°回転 //---------------------------------------------------- // ステータス情報 //---------------------------------------------------- typedef enum DICE_STATUS { e_statusNone = 0, // 出現していない e_statusStartAppear, // 出現中(出現し始め:薄い) e_statusAppear, // 出現中(出現中:薄くない) e_statusNormal, // 通常状態 e_statusStartDelete, // 消去中(消え始め:薄くない) e_statusDelete // 消去中(消えている:薄い) }; class CDiceObj : public C3DObjectAlphaBlend { private: int m_no; // 識別番号 int m_indexNo; // 添え字番号 int m_chainNo; // チェイン番号 D3DXVECTOR3 m_size; // ダイスのサイズ D3DXVECTOR3 m_logPos; // 保存行列 D3DXMATRIX m_rotTemp; // 保存回転行列 short m_dicePipAllay[7]; // ダイスの目が保存された配列( 添え字の0番は入れ替え用のワーク ) int m_animeCnt; // アニメーション用 DICE_STATUS m_status; // ステータス DICE_STATUS m_beforStatus; // 前回のステータス THITAABB* m_pAABB; // 当たり判定用AABB bool m_isDice; // 生成されているかどうか bool m_isChain; // チェイン中かどうか public: // 識別番号をセット void SetNo ( CONST short no ) { m_no = no; } // 識別番号を取得 CONST short GetNo ( void ) { return m_no; } // チェインしているかどうかをセット void SetIsChain ( CONST bool isChain ) { m_isChain = isChain; } // チェインしているかどうかを取得 CONST bool GetIsChain ( void ) { return m_isChain; } // チェイン番号のセット void SetChainNo ( CONST UINT chainNo ) { m_chainNo = chainNo; } // チェイン番号の取得 CONST UINT GetChainNo ( void ) { return m_chainNo; } // 添え字番号をセット void SetIndexNo ( CONST short indexNo ) { m_indexNo = indexNo; } // 添え字番号を取得 CONST short GetIndexNo ( void ) { return m_indexNo; } // 生成されているかどうかをセット void SetIsDice ( CONST bool isDice ) { m_isDice = isDice; } // 生成されているかどうかを取得 bool GetIsDice ( void ) { return m_isDice; } // ステータスをセット void SetStatus ( CONST DICE_STATUS status ) { m_status = status; } // ステータスを取得 CONST DICE_STATUS GetStatus ( void ) { return m_status; } // 前回のステータスをセット void SetBeforStatus ( CONST DICE_STATUS status ) { m_beforStatus = status; } // 前回のステータスを取得 CONST DICE_STATUS GetBeforStatus ( void ) { return m_beforStatus; } // サイズをセット void SetSize ( CONST D3DXVECTOR3* size ) { m_size.x = size->x; m_size.y = size->y; m_size.z = size->z; } // サイズを取得 CONST D3DXVECTOR3* GetSize ( void ) { return &m_size; } // 当たり判定用AABBをセット void SetAABB ( void ) { D3DXVECTOR3 aabbPos = D3DXVECTOR3( this->GetXPos(), this->GetYPos(), this->GetZPos() ); m_pAABB = CCollision::GetInstance()->SetAABB( m_pAABB, &aabbPos, &m_size ); } // 当たり判定用AABBを取得 CONST THITAABB* GetAABB ( void ) { return m_pAABB; } public: CDiceObj ( void ); // コンストラクタ virtual ~CDiceObj ( void ); // デストラクタ void Init ( void ); // 初期化 void Uninit ( void ); // 終了処理 // 回転のみのためのメソッド public: //---------------------------------------------------- // @name InitRoll // @content 回転する時の初期化 // @param none // @return bool 成功か失敗 // @date 2014/2/3 //---------------------------------------------------- bool InitRoll ( void ); //---------------------------------------------------- // @name RollX,Y,Z // @content 回転 // @param degree 回転量 // @return none // @date 2013/11/25 //---------------------------------------------------- void RollX ( float degree ); // X軸回転 void RollY ( float degree ); // Y軸回転 void RollZ ( float degree ); // Z軸回転 public: //---------------------------------------------------- // @name MoveX,Z // @content 移動+回転 // @param x 軸を移動させるためのx量 // @param y 軸を移動させるためのy量 // @param z 軸を移動させるためのz量 // @param rotDir 回転させる方向ベクトル( 1.0, -1.0f ) // @param speed スピード量 // @return none // @date 2013/11/26 //---------------------------------------------------- void MoveX ( float x, float y, float z, float rotDir, float speed ); // X回転 void MoveZ ( float x, float y, float z, float rotDir, float speed ); // Z回転 // 面制御用のメソッド public: //---------------------------------------------------- // @name InitPip // @content 面判定用配列の初期化 // @param none // @return bool 成功か失敗 // @date 2014/2/3 //---------------------------------------------------- bool InitPip ( void ); //---------------------------------------------------- // @name GetPip // @content サイコロの上面の番号取得 // ※サイコロの面配列の添え字1が上面としている // @param none // @return short 上面番号 // @date 2013/11/27 //---------------------------------------------------- CONST short GetPip ( void ) { return m_dicePipAllay[1]; } //---------------------------------------------------- // @name RollChangePip // @content 回転させた時に回転させた方向によって // ダイスの目を内部的に変える // @param rollState 回転ステータス // @return none // @date 2013/11/27 //---------------------------------------------------- void RollChangePip ( CONST USHORT rollState ); //---------------------------------------------------- // @name RollYChangePip // @content Y回転のみの場合回転させた方向によって // ダイスの目を内部的に変える // @param rollState 回転ステータス // @return none // @date 2013/11/27 // @update //---------------------------------------------------- void RollYChangePip ( void ); //---------------------------------------------------- // @name SetUpperFacePip // @content 上面をセット // @param upperFace セットしたい上面の番号(1〜6) // @return none // @date 2013/11/26 //---------------------------------------------------- void SetUpperPip ( CONST UINT upperFace ); //---------------------------------------------------- // @name SetAroundFace // @content 周りの面をセット // @param rollNum 回転させる回数(0〜3) // @return none // @date 2013/11/27 //---------------------------------------------------- void SetAroundPip ( CONST UINT rollNum ); //---------------------------------------------------- // @name SetPip // @content 上面と周りの面を同時にセット // @param upperFace セットしたい上面の番号(1〜6) // @param rollNum 回転させる回数(0〜3) // @return none // @date 2013/11/27 //---------------------------------------------------- void SetPip ( CONST UINT upperFace, CONST UINT rollNum ); //---------------------------------------------------- // @name DownAnimation // @content 消えていく処理 // @param downSpeed 落ちる速度 // @return bool 落ち切ったor一定距離落ちたかどうか // @date 2013/12/4 // @update 2013/12/4 引数と戻り値追加 //---------------------------------------------------- bool DownAnimation ( CONST float downSpeed ); //---------------------------------------------------- // @name UpAnimatiion // @content 出てくる処理 // @param upSpeed 出てくる速度 // @return bool 出てきたor一定距離出てきたかどうか // @date 2013/12/4 //---------------------------------------------------- bool UpAnimation ( CONST float upSpeed ); }; #endif _C_DICE_OBJ_H_<file_sep> #define _WINMAIN_MODULE_ #include "WinMain.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // メモリリークが起こっていないかを確認するためのテスト #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif MSG msg; CWindowSystem* pWnd = new CWindowSystem( 800, 640 ); // ウィンドウの作成 CFpsControl* pFpsControl = new CFpsControl(); // FPSをコントロールするクラスのインスタンス化 CDirectX9FrameWork* pDirectxFw = new CDirectX9FrameWork; // DirectX9のクラスをインスタンス化 // DirectX9の初期化 pDirectxFw->Init(); CMySQLManager::GetInstance()->ConnectDatabase(); // ゲームの起動シーン CSceneManager* sceneManager = new CSceneManager( GAME_STATUS ); #ifdef _DEBUG CDebugMode::m_pFps = pFpsControl->GetFPS(); #endif while( 1 ) { if( !pWnd->PeekEventMessage() ) { break; } else { if( pFpsControl->TuneFps() ) { sceneManager->Run(); if( CDirectDrawSystem::GetInstance()->BeginScene() ) { sceneManager->Draw(); CDirectDrawSystem::GetInstance()->EndScene(); } CDirectDrawSystem::GetInstance()->Present(); } pFpsControl->CalcFPS(); } } SAFE_DELETE( pDirectxFw ); SAFE_DELETE( pFpsControl ); SAFE_DELETE( sceneManager ); msg.wParam = pWnd->GetMessageWParam(); SAFE_DELETE( pWnd ); return msg.wParam; } <file_sep> #include "../../KaiFrameWorkHeader/SceneHeader/CSceneManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneManager::CSceneManager( eSceneState state ) { // m_pPthread = new CPthread(); m_pScene = nullptr; m_nowScene = eScene_None; m_nextScene = state; this->Update(); } //---------------------------------------------------- // 引数なしコンストラクタ //---------------------------------------------------- CSceneManager::CSceneManager( void ) { // m_pPthread = new CPthread(); m_pScene = nullptr; m_nextScene = eScene_None; } //---------------------------------------------------- // デストラクタ  // 現在のシーンのデストラクタを起動させる //---------------------------------------------------- CSceneManager::~CSceneManager() { if( m_pScene != NULL ) { m_pScene->Finalize(); delete m_pScene; m_pScene = NULL; } // スレッドが終了されていなかったら待機 // m_pPthread->Wait(); // SAFE_DELETE( m_pPthread ); } //---------------------------------------------------- // スレッドのロード //---------------------------------------------------- void* CSceneManager::ThreadLoad( void* func ) { CSceneManager* sceneManager = (CSceneManager*)func;; sceneManager->Load(); return 0; } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneManager::Load( void ) { m_pScene->Load(); m_pScene->Initialize(); m_isLoad = true; return true; } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CSceneManager::Initialize( void ) { m_pScene->Initialize(); } //---------------------------------------------------- // 終了処理 //---------------------------------------------------- void CSceneManager::Finalize() { m_pScene->Finalize(); } //---------------------------------------------------- // シーン切り替え処理 //---------------------------------------------------- void CSceneManager::Run( void ) { if( m_nextScene != m_nowScene ) { //次のシーンがセットされていたら if( m_pScene != NULL ) { m_pScene->Finalize(); //現在のシーンの終了処理を実行 m_isLoad = false; delete m_pScene; } this->Update(); // シーンをインスタンス化 } if( m_isLoad == true ) { m_pScene->Run(); //シーンの更新 } else if( m_isLoad == false ) { } } //---------------------------------------------------- // シーンをインスタンス化 //---------------------------------------------------- void CSceneManager::Update( void ) { //シーンによって処理を分岐 switch( m_nextScene ) { case eSceneState::eSceneGame: m_pScene = ( CSceneBase* ) new CSceneGame( this ); break; case eSceneState::eSceneTitle: m_pScene = ( CSceneBase* ) new CSceneTitle( this ); break; case eSceneState::eSceneModeSelect: m_pScene = ( CSceneBase* ) new CSceneModeSelect( this ); break; case eSceneState::eSceneHighScore: m_pScene = ( CSceneBase* ) new CSceneScore( this ); break; case eSceneState::eSceneModelView: m_pScene = ( CSceneBase* ) new CSceneModelView( this ); break; case eSceneState::eSceneResult: m_pScene = ( CSceneBase* ) new CSceneResult( this ); break; case eSceneState::eSceneDebug: m_pScene = ( CSceneBase* ) new CSceneDebug( this ); break; } m_nextScene = eScene_None; //次のシーン情報をクリア this->Load(); // m_isLoad = false; // m_pPthread->Create( this->ThreadLoad, this ); } //---------------------------------------------------- // シーンごとに描画 //---------------------------------------------------- void CSceneManager::Draw( void ) { if( m_isLoad == true ) { m_pScene->Draw(); //シーンの描画 } else if( m_isLoad == false ) { // NowLoadingの描画 DrawLoading(); } } //---------------------------------------------------- // 次のシーンをセット //---------------------------------------------------- void CSceneManager::ChangeScene( eSceneState nextScene ) { m_nextScene = nextScene; //次のシーンをセットする } //---------------------------------------------------- // NowLoading.... //---------------------------------------------------- void CSceneManager::DrawLoading( void ) { }<file_sep>//---------------------------------------------------- // CMySQLBase // MySQLにつなぎ、基本的なSQL文を実行するためのもの // // @author T.Kawashita // @date 2013/11/11 //---------------------------------------------------- #ifndef _C_MYSQL_MANAGER_H_ #define _C_MYSQL_MANAGER_H_ #include <Windows.h> #include <mysql.h> #include <string> // データベース情報 #define HOST_NAME ( NULL ) #define USER_NAME ( "Kaikai" ) #define PASS_WORD ( "<PASSWORD>" ) #define DATA_BASE ( "XI_Remakedb" ) #define PORT_NUM ( 0 ) class CMySQLManager { private: MYSQL* m_pMySql; MYSQL_RES* m_pResult; // コンストラクタ CMySQLManager ( void ) { m_pMySql = mysql_init( NULL ); // MySQLの初期化の成功か否か if( m_pMySql == NULL ) { MessageBox( NULL,"MySQL初期化失敗","InitError",MB_OK ); } } CMySQLManager ( CONST CMySQLManager& mysqlManager ); // コピーコンストラクタ禁止 CMySQLManager operator= ( CONST CMySQLManager& mysqlManager ); // メンバの代入を防ぐ public: // デストラクタ ~CMySQLManager ( void ) { mysql_server_end(); // MySQLを終了 } //---------------------------------------------------- // インスタンスの唯一の取得場所 //---------------------------------------------------- static CMySQLManager* GetInstance ( void ) { static CMySQLManager mysqlManager; return &mysqlManager; } //---------------------------------------------------- // @name ConnectDatabase // @content データベースへの接続(引数なし) // @param none // @return bool 成功か失敗 // @date 2013/11/11 //---------------------------------------------------- bool ConnectDatabase ( void ) { m_pMySql = mysql_init( NULL ); if( mysql_real_connect( m_pMySql, HOST_NAME, USER_NAME, PASS_WORD, DATA_BASE, PORT_NUM,NULL, 0 ) == NULL ) { // MessageBox( NULL, mysql_error( m_pMySql ), "MySQL接続エラー", MB_OK ); return false; } return true; } //---------------------------------------------------- // @name ConnectDatabase // @content データベースへの接続(引数あり) // @param dataBase 接続したいデータベース名 // @return bool 成功か失敗 // @date 2013/11/11 //---------------------------------------------------- bool ConnectDatabase ( CONST std::string dataBase ) { m_pMySql = mysql_init( NULL ); if( mysql_real_connect( m_pMySql, HOST_NAME, USER_NAME, PASS_WORD, dataBase.c_str(), PORT_NUM,NULL, 0 ) == NULL ) { MessageBox( NULL, mysql_error( m_pMySql ), "MySQL接続エラー", MB_OK ); return false; // 失敗 } return true; // 成功 } //---------------------------------------------------- // @name Search(テーブル名のみの指定) // @content 検索処理 // @param searchResultFd 検索結果を保存するフィールド // @param table テーブル名 // @return MYSQL_FIELD* 検索結果 // @date 2013/11/11 //---------------------------------------------------- CONST MYSQL_FIELD* Search ( MYSQL_FIELD* searchResultFd, CONST std::string table ) { std::string sql = "SELECT * FROM " + table; if( this->Query( sql ) == true ) { m_pResult = mysql_store_result( m_pMySql ); // 検索結果を保存 if( m_pResult == NULL || mysql_errno( m_pMySql ) != 0 ) { return NULL; } // 見つかった場合は列の情報をMYSQL_FIELD型の変数にセット searchResultFd = mysql_fetch_field( m_pResult ); return searchResultFd; } } //---------------------------------------------------- // @name Search(テーブル名・列名・条件式) // @content 検索処理 // @param searchResultFd 検索結果を保存するフィールド // @param table テーブル名 // @param column 列名 // @param condition 条件式 // @return MYSQL_FIELD* 検索結果 // @date 2014/2/19 //---------------------------------------------------- CONST MYSQL_ROW Search ( MYSQL_ROW searchResultFd, CONST std::string* table, CONST std::string* column, CONST std::string* condition ) { std::string sql = "SELECT " + *column + " FROM " + *table + " WHERE " + *condition; // クエリ発行 if( this->Query( sql ) == true ) { m_pResult = mysql_store_result( m_pMySql ); // 検索結果を保存 if( m_pResult == NULL || mysql_errno( m_pMySql ) != 0 ) { // 検索エラー return false; } // 見つかった場合は列の情報をMYSQL_FIELD型の変数にセット searchResultFd = mysql_fetch_row( m_pResult ); return searchResultFd; } return searchResultFd; } //---------------------------------------------------- // @name Search(テーブル名と列名を指定) // @content 検索処理 // @param fd 検索結果を保存するフィールド // @param table テーブル名 // @param column 列名 // @return bool あるかどうか // @date 2013/11/11 //---------------------------------------------------- bool Search ( CONST std::string table, CONST std::string condition ) { std::string sql = "SELECT * FROM " + table + " WHERE " + condition + ";"; if( this->Query( sql ) == true ) { m_pResult = mysql_store_result( m_pMySql ); if( m_pResult == NULL || mysql_errno( m_pMySql ) != 0 || m_pResult->row_count == 0 ) { return false; } // 結果の破棄 mysql_free_result( m_pResult ); return true; } return false; } //---------------------------------------------------- // @name CreateTable // @content テーブルの作成 // @param table テーブル名 // @return bool 成功か失敗 // @date 2013/11/11 // @comment 実装していません。 //---------------------------------------------------- bool CreateTable ( CONST std::string table, CONST std::string ) { } //---------------------------------------------------- // @name Insert // @content 列の追加 // @param table 追加したいテーブル名 // @param condition 条件 // @return bool 成功か失敗 // @date 2013/11/11 //---------------------------------------------------- bool Insert ( CONST std::string table, std::string condision ) { std::string sql = " INSERT INTO " + table + " VALUES ( " + condision + " ); " ; if( this->Query( sql ) == true ) { // 追加成功 return true; } // 追加失敗 return false; } //---------------------------------------------------- // @name Update // @content 指定列の更新 // @param table テーブル名 // @param column 指定列名 // @param condition 条件 // @return bool 更新できたか出来なかったか // @date 2013/11/11 //---------------------------------------------------- bool Update ( CONST std::string* table, CONST std::string* column, CONST std::string* condition ) { std::string sql = " UPDATE " + *table + " SET " + *column + " WHERE " + *condition; if( this->Query( sql ) == true ) { // 更新 return true; } // 更新できない return false; } //---------------------------------------------------- // @name Query // @content SQL文の実行 // @param sql sql文 // @return bool 成功か失敗か // @date 2013/10/10 //---------------------------------------------------- bool Query ( CONST std::string sql ) { mysql_query( m_pMySql, sql.c_str() ); // SQL文の実行 if( mysql_errno( m_pMySql ) != NULL ) { MessageBox( NULL, mysql_error( m_pMySql ), "クエリの発行失敗", MB_OK ); return false; } return true; // クエリ発行成功 } //---------------------------------------------------- // @name UnConnectionDatabase // @content データベースからの切断 // @param none // @return 切断できたか出来なかったか // @date 2013/11/11 //---------------------------------------------------- bool UnConnectionDatabase ( void ) { if( m_pMySql != NULL ) { mysql_close( m_pMySql ); } return true; } //---------------------------------------------------- // @name DestroyResult // @content リザルト情報の破棄 // @param none // @return bool 破棄できたかどうか // @date 2014/2/20 // @update none //---------------------------------------------------- bool DestroyResult ( void ) { mysql_free_result( m_pResult ); } }; #endif _C_MYSQL_BASE_H_<file_sep>//---------------------------------------------------- // CFpsControl // Fps計算・格納・調整などを行う // // @date 2013/5/8 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_FPSCONTROL_H_ #define _C_FPSCONTROL_H_ #include<Windows.h> class CFpsControl { private: DWORD m_execLastTime; // 最後にゲーム処理した時間 DWORD m_fpsLastTime; // 最後にFPSを計測した時間 DWORD m_currentTime; // 最新時間 int m_countFrame; // 描画回数(FPS計測用) float m_countFps; // FPS値表示用 public: // コンストラクタ CFpsControl (void) { m_execLastTime = 0; m_fpsLastTime = 0; m_currentTime = 0; m_countFrame = 0; m_countFps = 0; // FPS計算に必要な時間を取得 m_execLastTime = m_fpsLastTime = timeGetTime(); } // デストラクタ virtual ~CFpsControl (void){} public: //---------------------------------------------------- // @name GetFps // @content Fps値の取得 // @param none // @return float FPS値 // @date 2013/5/8 // @update 2013/11/6 //---------------------------------------------------- float* GetFPS ( void ) { return &m_countFps; } //---------------------------------------------------- // @name GetFrameCount // @content フレーム数の取得 // @param none // @return int フレーム数 // @date 2013/5/8 // @update 2013/11/6 //---------------------------------------------------- int GetFrameCount ( void ) { return m_countFrame; } public: //---------------------------------------------------- // @name TuneFps // @content FPSの調整 // @param none // @return bool 16msたったらtrue // @date 2013/5/8 // @update 2013/11/6 //---------------------------------------------------- bool TuneFps ( void ) { while( 1 ) { m_currentTime = timeGetTime(); if( m_currentTime - m_execLastTime >= 1000 / 60 ) break; } m_execLastTime = m_currentTime; return true; } //---------------------------------------------------- // @name CalcFps // @content FPSの計算 // @param none // @return bool 60FPSの計算 // @date 2013/5/8 // @update 2013/11/6 //---------------------------------------------------- bool CalcFPS ( void ) { if( m_countFrame >= 60 ) { m_countFps = ( m_countFrame * 1000 )/( (float)m_currentTime - m_fpsLastTime ); m_fpsLastTime = timeGetTime(); m_countFrame = 0; } m_countFrame ++; return true; } }; #endif<file_sep>//---------------------------------------------------- // CDirectX9FrameWork Header // DirectX9のフレームワーク // // @date 2013/4/27 // @authro T.Kawashita //---------------------------------------------------- #ifndef _C_DIRECTX9_FRAMEWORK_H_ #define _C_DIRECTX9_FRAMEWORK_H_ // 内部インポート #include <windows.h> #include <mmsystem.h> #include <d3dx9.h> // 外部インポート #include "../../KaiFrameWorkHeader/WindowsHeader/CWindowSystem.h" #include "../UtilityHeader/Macro.hpp" #include "../DebugHeader/CDebugConsole.hpp" // DXライブラリ読み込み #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "winmm.lib") class CDirectX9FrameWork { public: CDirectX9FrameWork (void); ~CDirectX9FrameWork (void); public: // シングルトンでグローバル制御 static LPDIRECT3D9& Getpd3d ( void ) { static LPDIRECT3D9 m_pd3d; return m_pd3d; } // シングルトンでデバイスポインタをグローバル制御 static LPDIRECT3DDEVICE9& Getpd3dDevice ( void ) { static LPDIRECT3DDEVICE9 m_pd3dDevice; return m_pd3dDevice; } public: //---------------------------------------------------- // @name Init // @content DirectX9の初期化 // @param none // @return HRESULT 成功か失敗 // @date 2013/5/20 //---------------------------------------------------- HRESULT Init (void); }; #endif _C_DIRECTX9_FRAMEWORK_H_ <file_sep>/************************************************************* * @file xorShift.h * @brief xorShift.クラスヘッダー * @note 特になし * @author <NAME> * @date 2013/05/19 *************************************************************/ #ifndef _Include_CXorShift_h_ // インクルードガード #define _Include_CXorShift_h_ /*!----------------------------------------------------------- // @class CXorShift // @brief Xorshifを使用した乱数クラス // @note 特になし // @author <NAME> // @date 2013/05/19 ------------------------------------------------------------*/ class CXorShift { public: /// デストラクタ ~CXorShift(){} /*!----------------------------------------------------------- // @brief 乱数のシード値設定 // @note 特になし // @param[in] setSeed 設定するシード値 // @return なし // @author <NAME> // @date 2013/05/19 ------------------------------------------------------------*/ void InitSeed( _int64 setSeed ) { m_seed = setSeed; m_z ^= m_seed; m_z ^= m_z >> 21; m_z ^= m_z << 35; m_z ^= m_z >> 4; m_w ^= m_z << 2; m_w *= 8943207074934384298LL; m_z *= 2685821657736338717LL; } /*!----------------------------------------------------------- // @brief 乱数の取得 // @note 特になし // @param[in] なし // @return 取得する乱数 // @author <NAME> // @date 2013/05/19 ------------------------------------------------------------*/ _int64 GetRandom() { _int64 t=(m_x^(m_x<<11)); m_x=m_y; m_y=m_z; m_z=m_w; return ( m_w=(m_w^(m_w>>19))^(t^(t>>8)) ); } /*!----------------------------------------------------------- // @brief 範囲乱数の取得 // @note 特になし // @param[in] min 最小値(範囲に含まれる) // @param[in] max 最大値(範$囲に含まれる) // @return 取得する乱数 // @author <NAME> // @date 2013/05/19 ------------------------------------------------------------*/ _int64 GetRandom(int min,int max) { _int64 rn = this->GetRandom(); return (this->GetRandom()%(max+1-min) + min); } /*!----------------------------------------------------------- // @brief インスタンス取得 // @note 特になし // @param[in] なし // @return 自身の参照 // @author <NAME> // @date 2013/05/19 ------------------------------------------------------------*/ static CXorShift* GetInstance() { static CXorShift singleton; return &singleton; } private: _int64 m_x; _int64 m_y; _int64 m_z; _int64 m_w; _int64 m_seed; private: /// コンストラクタ CXorShift() { m_x = 123456789; m_y = 362436069; m_z = 521288629; m_w = 88675123; m_seed = 1; }; }; //シングルトン定義 inline CXorShift* sXorShift() { return CXorShift::GetInstance(); } #endif // _Include_CXorShift_h_<file_sep> #include "CSceneModeSelect.h" //---------------------------------------------------- // 引数なしコンストラクタ //---------------------------------------------------- CSceneModeSelect::CSceneModeSelect( void ) { } //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CSceneModeSelect::CSceneModeSelect( CSceneChange* change ) : CSceneBase( change ) { } //---------------------------------------------------- // ロード //---------------------------------------------------- bool CSceneModeSelect::Load( void ) { // カメラ・ライトをインスタンス化 m_pDirectCamera = new CDirectCamera; m_pDirectLight = new CDirectLight; // 背景のマネージャクラス生成 m_pModeSelectBackManager = new CModeSelectBackManager; // プレイヤのマネージャクラス生成 m_pModeSelectPlayerManager = new CModeSelectPlayerManager; return true; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CSceneModeSelect::~CSceneModeSelect( void ) { SAFE_DELETE( m_pDirectCamera ); SAFE_DELETE( m_pDirectLight ); SAFE_DELETE( m_pModeSelectBackManager ); SAFE_DELETE( m_pModeSelectPlayerManager ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- void CSceneModeSelect::Initialize( void ) { m_pDirectCamera->Init( 800,600 ); m_pDirectCamera->SetPosition( 5.0f, 20.0f, -10.0f ); m_pDirectLight->Init(); m_pModeSelectBackManager->Init(); m_pModeSelectPlayerManager->Init(); m_modeIndexNo = 1; m_eMode = modeAllay[ m_modeIndexNo ]; m_isFade = false; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CSceneModeSelect::Run( void ) { CInputKeyboard::GetInstance()->Update(); CJoyStick::GetInstance()->Update(); // 右キー入力 if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_RIGHT ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_RIGHT ) ) && m_modeIndexNo < 3 && m_pModeSelectBackManager->GetMessageBarStatus() == eMessageBarStatus::eMessageBarNormal ) { m_modeIndexNo ++; m_eMode = modeAllay[ m_modeIndexNo ]; m_pModeSelectBackManager->RunKey( m_modeIndexNo ); m_pModeSelectBackManager->SetMessageBarStatus( eMessageBarStatus::eMessageBarAnimation ); m_pModeSelectPlayerManager->SetMovePlayerStatus( eModeSelectMovePlayerStatus::eModeSelectPlayerMoveRight ); } // 左キー入力 if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_LEFT ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_LEFT ) ) && m_modeIndexNo > 0 && m_modeIndexNo < 4 && m_pModeSelectBackManager->GetMessageBarStatus() == eMessageBarStatus::eMessageBarNormal) { m_modeIndexNo --; m_eMode = modeAllay[ m_modeIndexNo ]; m_pModeSelectBackManager->RunKey( m_modeIndexNo ); m_pModeSelectBackManager->SetMessageBarStatus( eMessageBarStatus::eMessageBarAnimation ); m_pModeSelectPlayerManager->SetMovePlayerStatus( eModeSelectMovePlayerStatus::eModeSelectPlayerMoveLeft ); } // 上キー入力 if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_UP ) || CJoyStick::GetInstance()->GetTriggerButton( 0 ,XINPUT_GAMEPAD_DPAD_UP ) ) && ( m_modeIndexNo == 1 || m_modeIndexNo == 5 ) && m_pModeSelectBackManager->GetMessageBarStatus() == eMessageBarStatus::eMessageBarNormal) { if( m_modeIndexNo == 1 ) { m_modeIndexNo = 4; } if( m_modeIndexNo == 5 ) { m_modeIndexNo = 1; } m_eMode = modeAllay[ m_modeIndexNo ]; m_pModeSelectBackManager->RunKey( m_modeIndexNo ); m_pModeSelectBackManager->SetMessageBarStatus( eMessageBarStatus::eMessageBarAnimation ); m_pModeSelectPlayerManager->SetMovePlayerStatus( eModeSelectMovePlayerStatus::eModeSelectPlayerMoveUp ); } // 下キー入力 if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_DOWN ) || CJoyStick::GetInstance()->GetTriggerButton( 0, XINPUT_GAMEPAD_DPAD_DOWN ) ) && ( m_modeIndexNo == 1 || m_modeIndexNo == 4 ) && m_pModeSelectBackManager->GetMessageBarStatus() == eMessageBarStatus::eMessageBarNormal) { if( m_modeIndexNo == 1 ) { m_modeIndexNo = 5; } if( m_modeIndexNo == 4 ) { m_modeIndexNo = 1; } m_eMode = modeAllay[ m_modeIndexNo ]; m_pModeSelectBackManager->RunKey( m_modeIndexNo ); m_pModeSelectBackManager->SetMessageBarStatus( eMessageBarStatus::eMessageBarAnimation ); m_pModeSelectPlayerManager->SetMovePlayerStatus( eModeSelectMovePlayerStatus::eModeSelectPlayerMoveDown ); } // シーンの切り替え if( ( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_SPACE ) || CJoyStick::GetInstance()->GetTriggerButton( 0,XINPUT_GAMEPAD_A ) ) && ( m_eMode == eModeSelectState::eModeGamePlay || m_eMode == eModeSelectState::eModeTitle || m_eMode == eModeSelectState::eModeExit || m_eMode == eModeSelectState::eModeRecord) ) { m_isFade = true; } if( m_isFade == true ) { // フェードアウトが終わったらシーンを切り替える if( m_pModeSelectBackManager->Fade() ) { switch( m_eMode ) { // ゲームプレイ case eModeSelectState::eModeGamePlay: mSceneChanger->ChangeScene( eSceneState::eSceneGame ); // 現在はゲームのシーンに遷移 break; // タイトル case eModeSelectState::eModeTitle: mSceneChanger->ChangeScene( eSceneState::eSceneTitle ); break; // スコア case eModeRecord: mSceneChanger->ChangeScene( eSceneState::eSceneHighScore ); break; // 終了 case eModeSelectState::eModeExit: SendMessage( CWindowSystem::GethWnd(),WM_CLOSE,0,0 ); break; default: break; } } } // 背景用マネージャー m_pModeSelectBackManager->Run(); // プレイヤー用マネージャー m_pModeSelectPlayerManager->Run(); #ifdef _DEBUG // F1キーでデバッグシーンに戻る if( CInputKeyboard::GetInstance()->GetTriggerKeyState( VK_F1 ) ) { mSceneChanger->ChangeScene( eSceneState::eSceneDebug ); } #endif } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CSceneModeSelect::Draw( void ) { m_pModeSelectBackManager->Draw(); m_pModeSelectPlayerManager->Draw(); m_pModeSelectBackManager->DrawAlpha(); } //---------------------------------------------------- // 終了 //---------------------------------------------------- void CSceneModeSelect::Finalize( void ) { m_pModeSelectBackManager->Uninit(); m_pModeSelectPlayerManager->Uninit(); } <file_sep>//---------------------------------------------------- // CWindowSystem // ウィンドウを作成 制御するクラス // // @date 2013/4/25 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_WINDOW_SYSTEM_H_ #define _C_WINDOW_SYSTEM_H_ #include <windows.h> #include "../../../GameInfo.h" #include "../DebugHeader/CDebugConsole.hpp" #pragma comment(lib,"winmm.lib") #define WINDOW_MAX_X ( GetSystemMetrics(SM_CXSCREEN) ) // ウィンドウX最大幅 #define WINDOW_MAX_Y ( GetSystemMetrics(SM_CYSCREEN) ) // ウィンドウY最大幅 #define DEFAULT_WINDOW_X 640 // ウィンドウXサイズ初期値 #define DEFAULT_WINDOW_Y 480 // ウィンドウYサイズ初期値 #define WINDOW_CLASS_NAME "DirectX" class CWindowSystem { private: WNDCLASSEX wc; MSG msg; LPSTR wndName; // ウィンドウの名前 short screenWidth; // スクリーンXサイズ short screenHeight; // スクリーンYサイズ POINT clientSize; // クライアントのサイズ public: // コンストラクタ CWindowSystem ( void ); // ウィンドウの大きさを指定しないウィンドウ作成 CWindowSystem ( CONST UINT screenWidth, CONST UINT screenHeight ); // ウィンドウの大きさを指定してウィンドウ作成 CWindowSystem ( CONST bool isFullScr ); // フルスクリーンモード用のウィンドウ作成 // デストラクタ virtual ~CWindowSystem ( void ) { timeEndPeriod(1); } private: static LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ); HRESULT CreateWnd ( void ); HRESULT SetWindowClass ( void ); void SetClientSize ( void ); // クライアントサイズの設定 public: HRESULT SetShowWindow ( void ); BOOL GetEventMessage ( void ); BOOL PeekEventMessage ( void ); public: // メッセージを取得 INT GetMessageWParam ( void ) { return (int)msg.wParam; } // シングルトンでウィンドウのハンドルをグローバル制御 static HWND& GethWnd ( void ) { static HWND hWnd; return hWnd; } }; #endif _C_WINDOW_SYSTEM_H_ <file_sep>//---------------------------------------------------- // CSceneTitle Class // Titleの画面シーンクラス // // @auter T.Kawashita //---------------------------------------------------- #ifndef _C_SCENE_TITLE_H_ #define _C_SCENE_TITLE_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneBase.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/SceneHeader/CSceneChange.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Camera.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9Light.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CJoyStick.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/WindowsHeader/CInputKeyboard.hpp" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" // Manager #include "../../ManagerSource/TitleScene/CTitleBackManager.h" #include "../../ManagerSource/TitleScene/CTitleSoundManager.h" #include "../../UserSource/CUserManager.h" class CSceneTitle : public CSceneBase { private: CDirectCamera *m_pDirectCamera; CDirectLight *m_pDirectLight; // Managerクラス private: CTitleBackManager *m_pTitleBackManager; CTitleSoundManager *m_pTitleSoundManager; public: CSceneTitle ( void ){} CSceneTitle ( CSceneChange* change ); virtual ~CSceneTitle ( void ); public: void Initialize ( void ) override; void Finalize ( void ) override; void Run ( void ) override; void Draw ( void ) override; bool Load ( void ) override; }; #endif _C_SCENE_TITLE_H_<file_sep>#include "CMySQLUserManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CMySQLUserManager::CMySQLUserManager( void ) { m_id = ""; m_userID = ""; m_pass = ""; m_userName = ""; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CMySQLUserManager::~CMySQLUserManager( void ) { } //---------------------------------------------------- // Userのログイン // ログイン失敗時はfalseが返る //---------------------------------------------------- bool CMySQLUserManager::Login( CONST std::string* loginID, CONST std::string* loginPass ) { std::string sqlString; // Login確認用のSQL文作成 sqlString = COMBINE_STRING( 5, "id = '", loginID->c_str(), " ' AND pass = '", loginPass->c_str(), "'" ); // MySQLとの接続 if( CMySQLManager::GetInstance()->ConnectDatabase() == true ) { // 接続成功 if( CMySQLManager::GetInstance()->Search( USER_TABLE, sqlString )) { // ログイン成功時にパスワードとIDを保存 m_id = *loginID; m_pass = *loginPass; // USERIDとパスワードも取得 std::string columnSql = COMBINE_STRING( 1, "userID, name" ); std::string conditionSql = COMBINE_STRING( 3, "id = '", loginID->c_str(), "'" ); MYSQL_ROW field = nullptr; field = CMySQLManager::GetInstance()->Search( field, &(std::string)USER_TABLE, &columnSql, &conditionSql ); m_userID = field[0]; m_userName = field[1]; // SQLの切断 CMySQLManager::GetInstance()->UnConnectionDatabase(); return true; } CMySQLManager::GetInstance()->UnConnectionDatabase(); // 切断 return false; } // MySQL接続失敗 return false; } //---------------------------------------------------- // Userの新規登録 // すでに登録されているUserIDの場合はfalseが返る //---------------------------------------------------- bool CMySQLUserManager::SignUp( CONST std::string* userID, CONST std::string* userPass ) { // DBに接続 if( CMySQLManager::GetInstance()->ConnectDatabase() ) { // 既に登録されているかどうか確認( User IDで確認 ) std::string sqlString = COMBINE_STRING( 3, "userID = '", userID->c_str(), "'" ); if( !CMySQLManager::GetInstance()->Search( USER_TABLE, sqlString ) ) { // 登録処理 // 新規登録するためのSQLを作成 sqlString = COMBINE_STRING( 9, "'", "00004", "' ,'", "aiueo", "', '", userID->c_str(), "', '", userPass->c_str(), "'" ); if( CMySQLManager::GetInstance()->Insert( USER_TABLE, sqlString ) ) { // 登録成功 return true; } // 登録失敗 CMySQLManager::GetInstance()->UnConnectionDatabase(); return false; } // すでに登録されている CMySQLManager::GetInstance()->UnConnectionDatabase(); // 何かメッセージを出す return false; } // MySQL接続失敗 return false; } <file_sep> #include "CStageBlockObj.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CStageBlockObj::CStageBlockObj( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CStageBlockObj::~CStageBlockObj( void ) { } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CStageBlockObj::Init( void ) { m_no = 50; m_pos.x = 0.0f; m_pos.y = 0.0f; m_pos.z = 0.0f; m_pDice = nullptr; m_isOnDice = false; m_isOnPlayer = false; return true; } //---------------------------------------------------- // ダイスがあるかどうか取得する //---------------------------------------------------- bool CStageBlockObj::CheckOnDice( void ) { return m_isOnDice; } //---------------------------------------------------- // プレイヤーが乗っているかどうかを取得する //---------------------------------------------------- bool CStageBlockObj::CheckOnPlayer( void ) { return m_isOnPlayer; } //---------------------------------------------------- // 位置情報のセット //---------------------------------------------------- void CStageBlockObj::SetPosition( float x, float y, float z ) { m_pos.x = x; m_pos.y = y; m_pos.z = z; } //---------------------------------------------------- // 番号のセット //---------------------------------------------------- void CStageBlockObj::SetNo( CONST UINT no ) { m_no = no; } //---------------------------------------------------- // ダイスをセット //---------------------------------------------------- void CStageBlockObj::SetDice( CDiceObj* dice ) { m_pDice = dice; } //---------------------------------------------------- // ダイスが乗っているかどうかのフラグをセット //---------------------------------------------------- void CStageBlockObj::SetIsOnDice( CONST bool isDice ) { m_isOnDice = isDice; } //---------------------------------------------------- // プレイヤーが乗っているかどうかのフラグをセット //---------------------------------------------------- void CStageBlockObj::SetIsOnPlayer( CONST bool isPlayer ) { m_isOnPlayer = isPlayer; }<file_sep>//---------------------------------------------------- // CTitleSoundManager Header // タイトルのサウンド管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_TITLE_SOUND_MANAGER_H_ #define _C_TITLE_SOUND_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CXAudio2.h" #define TITLE_BGM ( 0 ) #define TITLE_BUTTON ( 1 ) class CTitleSoundManager { private: CXAudio2 *m_pSound; public: CTitleSoundManager ( void ); ~CTitleSoundManager ( void ); public: void Init ( void ); void Play ( const int soundNo,bool isLoop ); void Stop ( const int soundNo ); void FadeOut ( void ); }; #endif _C_TITLE_SOUND_MANAGER_H_<file_sep>//---------------------------------------------------- // CPthread // PThreadでのマルチスレッド // // @date 2013/11/5 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_PTHREAD_H_ #define _C_PTHREAD_H_ #include <windows.h> /* #include <pthread.h> #pragma comment( lib, "pthreadVC2.lib" ) class CPthread { private: pthread_t m_pThread; // スレッド public: //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CPthread ( void ){} //---------------------------------------------------- // デストラクタ //---------------------------------------------------- ~CPthread ( void ){} //---------------------------------------------------- // @name Create // @content スレッドの作成 // @param startThread スタートさせたい関数ポインタ // @param arg スレッドに渡す引数 // @return bool 作成できたら // @date 2014/1/24 //---------------------------------------------------- bool Create ( void* startThread(void * _info), void* arg ) { pthread_create( &m_pThread, NULL, startThread, arg ); return true; } //---------------------------------------------------- // @name Wait // @content スレッド待機 // @param none // @return bool スレッド待機して終わったら // @date 2014/1/24 //---------------------------------------------------- bool Wait ( void ) { pthread_join( m_pThread, NULL ); return true; } }; */ #endif _C_PTHREAD_H_<file_sep>//---------------------------------------------------- // CPlayer // プレイヤーのクラス // // @date 2013/12/4 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_PLAYER_H_ #define _C_PLAYER_H_ #include <d3dx9.h> #include "../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DBillBoard.h" #include "../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../KaiFrameWork/KaiFrameWorkHeader/GameMathHeader/CCollision.h" #include "../SceneSource/DebugScene/CDebugMode.h" // プレイヤーのステータス typedef enum ePlayerStatus { eOnStage, // ステージの上にいる状態 eOnDiceAppear, // ダイスが出現している上にいる状態 eOnDiceAppearStart, // ダイスが出現している上にいる状態 eOnDiceDelete, // ダイスが消えている上にいる状態 eOnDiceDeleteStart, // ダイスの消え始めの上にいる状態 eOnDice, // ダイスの上にいる状態 }; // プレイヤーの移動のステータス typedef enum ePlayerMoveStatus { eMoveDice, eMoveRight, eMoveLeft, eMoveFront, eMoveBack, eMoveNone }; class CPlayer : public C2DSprite { private: THITAABB* m_pAABB; // 当たり判定用AABB ePlayerStatus m_status; // プレイヤーのステータス ePlayerMoveStatus m_moveStatus; // プレイヤーの移動ステータス public: // 当たり判定用AABBをセット void SetAABB ( void ) { m_pAABB->centerPos.x = this->GetXPos(); m_pAABB->centerPos.y = this->GetYPos(); m_pAABB->centerPos.z = this->GetZPos(); } // 当たり判定用AABBを取得 THITAABB* GetAABB ( void ) { return m_pAABB; } // プレイヤーのステータスをセット void SetPlayerStatus ( ePlayerStatus status = ePlayerStatus::eOnDice ) { m_status = status; } // プレイヤーのステータスを取得 ePlayerStatus GetPlayerStatus ( void ) { return m_status; } // プレイヤーの移動ステータスをセット void SetMoveStatus ( ePlayerMoveStatus status = ePlayerMoveStatus::eMoveNone ) { m_moveStatus = status; } // プレイヤーの移動ステータスを取得 ePlayerMoveStatus GetMoveStatus ( void ) { return m_moveStatus; } public: // コンストラクタ CPlayer ( void ); // デストラクタ virtual ~CPlayer ( void ); // 初期化 bool Init ( void ); bool Uninit ( void ); //---------------------------------------------------- // 移動 //---------------------------------------------------- void MoveFront ( CONST float speed ); // 前移動 void MoveBack ( CONST float speed ); // 後移動 void MoveRight ( CONST float speed ); // 右移動 void MoveLeft ( CONST float speed ); // 左移動 void MoveDown ( CONST float speed ); // ダウン処理 void MoveUp ( CONST float speed ); // アップ処理 }; #endif _C_PLAYER_H_<file_sep># XI-Remake- ## 実行環境 Windows 7, 8, 10 動作確認済 Microsoft DirectX SDK (June 2010) ## 操作 |画面|操作|Xbox Controller|KeyBoard| |:---:|:---:|:---:|:---:| |タイトル|決定|STARTボタン|SPACE| |モードセレクト|選択 |Aボタン|SPACE| |ハイスコア|戻る|Bボタン|SPACE| |ゲーム|移動|十字ボタン|ARROW| |ゲーム|ポーズ|STARTボタン|ESCAPE| |リザルト|進む|Aボタン|ENTER| ## 未実装 - オプション画面 ------------------- ## スクリーンショット ![menu](https://user-images.githubusercontent.com/9031790/98631406-b5459180-2360-11eb-93f0-fc8f82cdd60f.png) ![game](https://user-images.githubusercontent.com/9031790/98631404-b4146480-2360-11eb-929d-98bb6814df36.png) <file_sep>//---------------------------------------------------- // CParticle // パーティクルする物体のBaseとなるクラス // // @date 2013/8/25 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_PARTICLE_H_ #define _C_PARTICLE_H_ #include <Windows.h> #include <d3dx9.h> #include "CBillBoard.h" class CParticle:public CBillBoard { private: D3DXVECTOR3 m_speed; // パーティクルの進む速度 D3DXVECTOR3 m_direct; // パーティクルの進む方向 int m_life; // 生存値 float m_rate; // 倍率 public: // コンストラクタ CParticle() { m_speed.x = 0.0f; m_speed.y = 0.0f; m_speed.z = 0.0f; m_direct.x = 0.0f; m_direct.y = 0.0f; m_direct.z = 0.0f; m_life = 0; m_rate = (float)(this->GetAlfa() / 255); } CParticle(float xSpeed,float ySpeed,float zSpeed,float xDirect,float yDirect,float zDirect,int life,int alfa) { m_speed.x = xSpeed; m_speed.y = ySpeed; m_speed.z = zSpeed; m_direct.x = xDirect; m_direct.y = yDirect; m_direct.z = zDirect; m_life = life; m_rate = (float)(this->GetAlfa() / life); } ~CParticle(){} public: // ライフを減らす void LifeDown ( int dist ) { m_life = m_life - dist; } // ライフを取得 const int GetLife () { return m_life; } //---------------------------------------------------- // ライフのセット //---------------------------------------------------- void SetLife ( int life ) { m_life = life; } //---------------------------------------------------- // α値の計算(ライフで考えている) // 倍率を求める //---------------------------------------------------- void CalcAlfa ( void ) { int alfa; m_rate = (float)this->GetMaxAlfa() / (float)m_life; alfa =(int)(m_rate * this->GetLife()); this->SetAlfa( alfa ); } //---------------------------------------------------- // パーティクル移動 //---------------------------------------------------- void Move ( void ) { D3DXVECTOR3 move; // 移動用work move.x = this->GetPos()->x + m_speed.x * m_direct.x; move.y = this->GetPos()->y + m_speed.y * m_direct.y; move.z = this->GetPos()->z + m_speed.z * m_direct.z; this->SetPosition( move.x,move.y,move.z ); } //---------------------------------------------------- // パーティクルのセット //---------------------------------------------------- void SetParticle ( float xSpeed,float ySpeed,float zSpeed,float xDirect,float yDirect,float zDirect ) { m_speed.x = xSpeed; m_speed.y = ySpeed; m_speed.z = zSpeed; m_direct.x = xDirect; m_direct.y = yDirect; m_direct.z = zDirect; } }; #endif _C_PARTICLE_H_<file_sep> #include "../../KaiFrameWorkHeader/ResourceHeader/COriginalMesh.h" /* //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- COriginalMesh::COriginalMesh() { m_cloneData.connect = NULL; m_cloneData.vertex = NULL; m_cloneData.numVertex = 0; m_cloneData.numFaces = 0; } //---------------------------------------------------- // メッシュからバウンディングスフィア用の構造体データ取得 //---------------------------------------------------- void CMeshClone::Init( LPD3DXMESH lpMesh, COLISION_DATA* colData) { // シングルトンでデバイスへのポインタを取得 const LPDIRECT3DDEVICE9 pd3dDevice = CDirectBase::Getpd3dDevice(); HRESULT hr; // 頂点座標データ float* x; float* y; float* z; float* pFloat; BYTE *data; cloneConnect = NULL; cloneVertex = NULL; pTriangle = NULL; // 当たり判定用データ作成のためにクローンメッシュ作成 hr = lpMesh->CloneMeshFVF( D3DXMESH_MANAGED,(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ),pd3dDevice,&cloneMesh); if( FAILED(hr) ) { // 作成できなかった場合エラーを表示 処理は続行 MessageBox(0,"Colon Not Create...","error",MB_OK); } else { numVertex = cloneMesh->GetNumVertices(); // 頂点数取得 cloneMesh->GetVertexBuffer( &lpVertexBuff ); // 頂点バッファオブジェクトへのポインタ取得 // 頂点バッファをロック hr = lpVertexBuff->Lock(0,0,(void**)&data,D3DLOCK_READONLY); if( hr == D3D_OK ) { // 頂点数分の座標格納エリア確保 x = new float[numVertex]; y = new float[numVertex]; z = new float[numVertex]; } pFloat = (float *)data; for( int i = 0; i < numVertex; ++ i ) { // 頂点を取り出す x[i] = *pFloat++; y[i] = *pFloat++; z[i] = *pFloat++; } // maxとminを求める for( int i = 0; i < numVertex; ++ i ) { if( colData->minX >= x[i] ) colData->minX = x[i]; if( colData->minY >= y[i] ) colData->minY = y[i]; if( colData->minZ >= z[i] ) colData->minZ = z[i]; if( colData->maxX <= x[i] ) colData->maxX = x[i]; if( colData->maxY <= y[i] ) colData->maxY = y[i]; if( colData->maxZ <= z[i] ) colData->maxZ = z[i]; } // 球の中心座標を求める colData->cenX = ( colData->maxX + colData->minX ) / 2; colData->cenY = ( colData->maxY + colData->minY ) / 2; colData->cenZ = ( colData->maxZ + colData->minZ ) / 2; // 2点間の距離を求めて半径を求める colData->r = pow( colData->maxX - colData->cenX,2 ) + pow( colData->maxY - colData->cenY,2 ) + pow( colData->maxZ - colData->cenZ,2 ); colData->r = sqrtf( colData->r ); // ---- データ取得終了 ---- // delete[] z; delete[] y; delete[] x; // 頂点バッファ解放 lpVertexBuff->Unlock(); // 解放 cloneMesh->Release(); cloneMesh = NULL; } } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- COriginalMesh::~COriginalMesh(void) { SAFE_DELETE_ALLAY( m_cloneData.connect ); // 結線情報削除 SAFE_DELETE_ALLAY( m_cloneData.vertex ); // 頂点情報削除 SAFE_DELETE_ALLAY( pTriangle ); // 三角形情報削除する } /* void COriginalMesh::TraiangleTransform(D3DXMATRIX mat) { TCLONETRIANGLEVERTEX* TransformWork; // ワールド座標系に変換するためのワーク D3DXVECTOR3 temp; int idx0,idx1,idx2; D3DXVECTOR3 normal; D3DXVECTOR3 p0p1; D3DXVECTOR3 p0p2; // 生成された三角形情報があれば削除する if( pTriangle != NULL ) { delete[] pTriangle; pTriangle = NULL; } // 座標変換用ワークを頂点数分生成する TransformWork = new TCLONETRIANGLEVERTEX[numVertex]; // 頂点をすべて取り出しワールド座標変換用ワークにセット for( UINT i = 0; i < numVertex; i ++ ) { // ローカル座標を座標変換用ワークにセット TransformWork[i] = cloneVertex[i]; temp.x = cloneVertex[i].pos.x; temp.y = cloneVertex[i].pos.y; temp.z = cloneVertex[i].pos.z; // 座標変換 D3DXVec3TransformCoord(&temp,&temp,&mat); // 座標値のみワールド座標で書き換え TransformWork[i].pos.x = temp.x; TransformWork[i].pos.y = temp.y; TransformWork[i].pos.z = temp.z; } pTriangle = new MyTriangle[numFaces]; // 三角形の面数分オブジェクト生成 // 三角形ポリゴン数分ループ for( UINT i = 0; i < numFaces; i ++ ) { idx0 = cloneConnect[i].idx[0]; idx1 = cloneConnect[i].idx[1]; idx2 = cloneConnect[i].idx[2]; pTriangle[i].vertex[0] = TransformWork[idx0]; pTriangle[i].vertex[1] = TransformWork[idx1]; pTriangle[i].vertex[2] = TransformWork[idx2]; pTriangle[i].vertex[0].diffuse = D3DCOLOR_ARGB(255,255,255,255); pTriangle[i].vertex[1].diffuse = D3DCOLOR_ARGB(255,255,255,255); pTriangle[i].vertex[2].diffuse = D3DCOLOR_ARGB(255,255,255,255); p0p1.x = pTriangle[i].vertex[1].pos.x - pTriangle[i].vertex[0].pos.x; p0p1.y = pTriangle[i].vertex[1].pos.y - pTriangle[i].vertex[0].pos.y; p0p1.z = pTriangle[i].vertex[1].pos.z - pTriangle[i].vertex[0].pos.z; p0p2.x = pTriangle[i].vertex[2].pos.x - pTriangle[i].vertex[0].pos.x; p0p2.y = pTriangle[i].vertex[2].pos.y - pTriangle[i].vertex[0].pos.y; p0p2.z = pTriangle[i].vertex[2].pos.z - pTriangle[i].vertex[0].pos.z; // 法線情報計算 D3DXVec3Cross( &normal,&p0p1,&p0p2 ); D3DXVec3Normalize( &normal,&normal ); pTriangle[i].normal.x = normal.x; pTriangle[i].normal.y = normal.y; pTriangle[i].normal.z = normal.z; // 重心計算 pTriangle[i].center.x = (pTriangle[i].vertex[0].pos.x + pTriangle[i].vertex[1].pos.x + pTriangle[i].vertex[2].pos.x)/3; pTriangle[i].center.y = (pTriangle[i].vertex[0].pos.y + pTriangle[i].vertex[1].pos.y + pTriangle[i].vertex[2].pos.y)/3; pTriangle[i].center.z = (pTriangle[i].vertex[0].pos.z + pTriangle[i].vertex[1].pos.z + pTriangle[i].vertex[2].pos.z)/3; // 現在の重心座標を保存しておく pTriangle[i].m_vLogPos.x = pTriangle[i].center.x; pTriangle[i].m_vLogPos.y = pTriangle[i].center.y; pTriangle[i].m_vLogPos.z = pTriangle[i].center.z; // 頂点座標を原点を基準とした座標に変換する for( int j = 0; j < VERTEX_NUM; j ++ ) { pTriangle[i].vertex[j].pos.x -= pTriangle[i].center.x; pTriangle[i].vertex[j].pos.y -= pTriangle[i].center.y; pTriangle[i].vertex[j].pos.z -= pTriangle[i].center.z; } D3DXMatrixIdentity(&pTriangle[i].mat); pTriangle[i].m_vLife = 255; pTriangle[i].isExist = true; } delete[] TransformWork; TransformWork = NULL; return; } */ /* void COriginalMesh::LocalToWorld( D3DXMATRIX mat ) { TCLONETRIANGLEVERTEX* TransformWork; // ワールド座標系に変換するためのワーク D3DXVECTOR3 temp; int idx0,idx1,idx2; // 生成された三角形情報があれば削除する if( pTriangle != NULL ) { delete[] pTriangle; pTriangle = NULL; } // 座標変換用ワークを頂点数分生成する TransformWork = new TCLONETRIANGLEVERTEX[numVertex]; // 頂点をすべて取り出しワールド座標変換用ワークにセット for( UINT i = 0; i < numVertex; i ++ ) { // ローカル座標を座標変換用ワークにセット TransformWork[i] = cloneVertex[i]; temp.x = cloneVertex[i].pos.x; temp.y = cloneVertex[i].pos.y; temp.z = cloneVertex[i].pos.z; // 座標変換 D3DXVec3TransformCoord(&temp,&temp,&mat); // 座標値のみワールド座標で書き換え TransformWork[i].pos.x = temp.x; TransformWork[i].pos.y = temp.y; TransformWork[i].pos.z = temp.z; } pTriangle = new MyTriangle[numFaces]; // 三角形の面数分オブジェクト生成 // 三角形ポリゴン数分ループ for( UINT i = 0; i < numFaces; i ++ ) { idx0 = cloneConnect[i].idx[0]; idx1 = cloneConnect[i].idx[1]; idx2 = cloneConnect[i].idx[2]; pTriangle[i].vertex[0] = TransformWork[idx0]; pTriangle[i].vertex[1] = TransformWork[idx1]; pTriangle[i].vertex[2] = TransformWork[idx2]; } delete[] TransformWork; TransformWork = NULL; } */ /* //---------------------------------------------------- // オリジナルメッシュの作成 //---------------------------------------------------- tagTORIGINALMESH* COriginalMesh::CreateOriginalMesh ( tagTORIGINALMESH* cloneData, CONST LPSTR filePath ) { CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); HRESULT hr; LPD3DXMESH pMesh; LPD3DXMESH pCloneMesh; LPD3DXBUFFER pMaterialsBuffer; LPDIRECT3DVERTEXBUFFER9 pVertexBuff; // 頂点バッファ LPDIRECT3DINDEXBUFFER9 pIndexBuff; DWORD materialsCount; //Xファイル読み込み hr = D3DXLoadMeshFromX( filePath, D3DXMESH_MANAGED, pd3dDevice, nullptr, &pMaterialsBuffer, nullptr, &materialsCount, &pMesh); if( FAILED( hr ) ) { // 読み込み失敗時 return nullptr; } //クローンメッシュ hr = pMesh->CloneMeshFVF( D3DXMESH_MANAGED, CLONE_FVF, pd3dDevice, &pCloneMesh ); if( FAILED( hr ) ) { // 生成失敗 MessageBox( 0,"Colon Not Create...","error",MB_OK ); return nullptr; } // 頂点数を取得 cloneData->numVertex = pCloneMesh->GetNumVertices(); pCloneMesh->GetVertexBuffer( &pVertexBuff ); // 面数を取得 cloneData->numFaces = pCloneMesh->GetNumFaces(); pCloneMesh->GetIndexBuffer( &pIndexBuff ); BYTE* pVertexData; // 頂点バッファをロック hr = pVertexBuff->Lock( 0,sizeof( tagTORIGINALMESHVERTEX ),( void** )&pVertexData,D3DLOCK_READONLY ); if( FAILED( hr ) ) { // 頂点バッファロック失敗 MessageBox( 0,"VertexBuff Not Lock...","error",MB_OK ); return nullptr; } cloneData->vertex = new tagTORIGINALMESHVERTEX[cloneData->numVertex]; // 頂点数分確保 memcpy( cloneData->vertex,pVertexData,sizeof( tagTORIGINALMESHVERTEX )*( cloneData->numVertex )); // 頂点情報をコピー // 頂点バッファ解放 pVertexBuff->Unlock(); // インデックスバッファをロック hr = pIndexBuff->Lock(0, sizeof( tagTORIGINALMESHVERTEX ),(void**)&pIndexBuff,D3DLOCK_READONLY); if( FAILED( hr ) ) { // インデックスバッファロック失敗 MessageBox( 0,"IndexBuff Not Lock...","error",MB_OK ); return FALSE; } cloneData->connect = new MyConnect[cloneData->numFaces]; // 面数分の結線情報を取得 WORD* pIndex = nullptr; // インデックスバッファ // 3角形ポリゴン数分ループ for( UINT i = 0; i < cloneData->numFaces; ++ i ) { cloneData->connect[i].idx[0] = *pIndex ++; cloneData->connect[i].idx[1] = *pIndex ++; cloneData->connect[i].idx[2] = *pIndex ++; } // インデックスバッファ解放 pIndexBuff->Unlock(); return cloneData; } /* //==================================================== // 色変更 //==================================================== bool COriginalMesh::ColorClone3D(void) { for( UINT i = 0; i < m_cloneData.numFaces; i ++ ) { pTriangle[i].m_vLife -- ; if( pTriangle[i].m_vLife <= 0 ) { return true; pTriangle[i].isExist = false; } } return false; } //==================================================== // クローン3Dモデルを法線方向に移動 //==================================================== void COriginalMesh::MoveClone3D( void ) { for( UINT i = 0; i < m_cloneData.numFaces; i ++ ) { // pTriangle[i].normal.x -= 0.1f; // pTriangle[i].normal.y -= 0.1f; pTriangle[i].normal.z -= 0.05f; pTriangle[i].mat._41 = pTriangle[i].m_vLogPos.x + pTriangle[i].normal.x * 0.12f; pTriangle[i].mat._42 = pTriangle[i].m_vLogPos.y + pTriangle[i].normal.y * 0.08f; pTriangle[i].mat._43 = pTriangle[i].m_vLogPos.z + pTriangle[i].normal.z * 0.08f; pTriangle[i].m_vLogPos.x = pTriangle[i].mat._41; pTriangle[i].m_vLogPos.y = pTriangle[i].mat._42; pTriangle[i].m_vLogPos.z = pTriangle[i].mat._43; } } //==================================================== // クローン3Dモデルを回転 //==================================================== void COriginalMesh::RotationClone3D(void) { static D3DXMATRIX rotX,rotY,rotZ; D3DXMatrixIdentity(&rotX); D3DXMatrixIdentity(&rotY); D3DXMatrixIdentity(&rotZ); for( UINT i = 0; i < m_cloneData.numFaces; i ++ ) { D3DXMatrixRotationX(&rotX,0.2f); D3DXMatrixRotationY(&rotY,0.2f); D3DXMatrixRotationZ(&rotZ,0.2f); pTriangle[i].mat = rotX * rotY * rotZ * pTriangle[i].mat; } } */<file_sep> #include "../../../KaiFrameWorkHeader/GameObjectHeader/3D/C3DObjectShape.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- C3DObjectShape::C3DObjectShape( void ) { ::ZeroMemory( &m_pMesh, sizeof( LPD3DXMESH ) ); ::ZeroMemory( &m_materials, sizeof( D3DMATERIAL9 ) ); } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- C3DObjectShape::~C3DObjectShape( void ) { } //---------------------------------------------------- // スフィアの生成 //---------------------------------------------------- bool C3DObjectShape::CreateSphere( CONST float radius ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // スフィアの生成 if( D3DXCreateSphere( pd3dDevice, radius, 20, 20, &m_pMesh, NULL ) ) { // 作成できなかった場合 return false; } // Diffuseの色のセット this->SetDiffuse( 255,255,255,255 ); // Ambient色のセット this->SetAmbient( 255,255,255,255 ); return true; } //---------------------------------------------------- // ボックスの生成 //---------------------------------------------------- bool C3DObjectShape::CreateBox( CONST D3DXVECTOR3* size ) { // デバイスのポインタを取得 CONST LPDIRECT3DDEVICE9 pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); // スフィアの生成 if( D3DXCreateBox( pd3dDevice, size->x, size->y ,size->z, &m_pMesh, NULL ) ) { // 作成できなかった場合 return false; } // Diffuseの色のセット this->SetDiffuse( 255,255,255,255 ); // Ambient色のセット this->SetAmbient( 255,255,255,255 ); return true; } //---------------------------------------------------- // Diffuse色セット //---------------------------------------------------- void C3DObjectShape::SetDiffuse( CONST UINT r, CONST UINT b, CONST UINT g, CONST UINT a ) { m_materials.Diffuse.r = ( float )( r / 255.0f ); m_materials.Diffuse.g = ( float )( g / 255.0f ); m_materials.Diffuse.b = ( float )( b / 255.0f ); m_materials.Diffuse.a = ( float )( a / 255.0f ); } //---------------------------------------------------- // Ambient色セット //---------------------------------------------------- void C3DObjectShape::SetAmbient( CONST UINT r, CONST UINT g, CONST UINT b, CONST UINT a ) { m_materials.Ambient.r = ( float )( r / 255.0f ); m_materials.Ambient.g = ( float )( g / 255.0f ); m_materials.Ambient.b = ( float )( b / 255.0f ); m_materials.Ambient.a = ( float )( a / 255.0f ); } <file_sep>//---------------------------------------------------- // CRandSystem Header // 乱数の生成用ヘッダー // // @date 2013/8/10 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_RAND_SYSTEM_H_ #define _C_RAND_SYSTEM_H_ #include <stdlib.h> #include <time.h> class CRandSystem { public: CRandSystem (void) { this->ChangeSeed(); // シードの変更 } ~CRandSystem (void) { } public: //---------------------------------------------------- // @name ChangeSeed // @content シードの変更(タイムで変更) // @param none // @return none // @date 2013/8/10 //---------------------------------------------------- void ChangeSeed ( void ) { srand( (unsigned)time( NULL ) ); } //---------------------------------------------------- // @name GetRand // @content ある範囲の乱数を取得 // @param start 範囲の最初 // @param end 範囲の最後 // @return const int 乱数 // @date 2013/8/11 //---------------------------------------------------- const int GetRand ( unsigned int start,unsigned int end ) { return ( rand() % end - start + 1 ) + start; } //---------------------------------------------------- // @name GetRand // @content 最大値のみ指定した乱数を取得 // @param max 乱数で取得できる最大数 // @return const int 乱数 // @date 2013/8/11 //---------------------------------------------------- const int GetRand ( int max ) { return ( rand() % max ); } //---------------------------------------------------- // @name GetRand // @content −の値を含めた乱数を取得 // @param max 範囲の最大値 // @param minus 範囲の最小値 // @param isMinus −を含めるかどうか // @return const int 乱数 // @date 2013/8/11 //---------------------------------------------------- const int GetRand ( int max, int minus,bool isMinus ) { return ( ( rand() % max ) - (rand() % minus) ); } //---------------------------------------------------- // @name GetRand // @content −の値を含めた乱数を取得(float型) // @param max 範囲の最大値 // @return float 乱数 // @date 2013/8/11 //---------------------------------------------------- const float GetRand ( float max ) { int value = (int)max * 10; value = value + 1; float value2 = (float)(rand() % value ) / 10.0f; float value3 = (float)(rand() % value ) / 10.0f; return value2 - value3; } }; #endif _C_RAND_SYSTEM_H_<file_sep> #include "CModeSelectBackManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CModeSelectBackManager::CModeSelectBackManager( void ) { // モードセレクトのステージ m_pModeSelectStage = new CObjectBase; m_pResModeSelectStageFilePath = MODE_STAGE_XFILEPATH; CResourceManager::GetInstance()->LoadXFile( m_pResModeSelectStageFilePath ); // αブレンド用画像 m_pAlphaBlend = new C2DSpriteAlphaBlend; // メニューの画像 m_pMenuValue = new C2DSpriteAlphaBlend; m_pResMenuValueFilePath = MODE_MENU_PNGPATH; CResourceManager::GetInstance()->LoadTexture( m_pResMenuValueFilePath ); // メッセージバー m_pMessageBar = new CMessageBar; m_resIndexNo = 1; m_isBarAnimation = false; m_pResMessageBar[0] = MODE_TITLEMESSAGE_PNGPATH; m_pResMessageBar[1] = MODE_GAMEPLAYMESSAGE_PNGPATH; m_pResMessageBar[2] = MODE_OPTIONMESSAGE_PNGPATH; m_pResMessageBar[3] = MODE_EXITMESSAGE_PNGPATH; m_pResMessageBar[4] = MODE_RANKINGMESSAGE_PNGPATH; m_pResMessageBar[5] = MODE_RECORDMESSAGE_PNGPATH; for( int i = 0; i < 6; ++ i ) { CResourceManager::GetInstance()->LoadTexture( m_pResMessageBar[i] ); } } //---------------------------------------------------- // デストラクタ  //---------------------------------------------------- CModeSelectBackManager::~CModeSelectBackManager( void ) { SAFE_DELETE( m_pModeSelectStage ); SAFE_DELETE( m_pAlphaBlend ); SAFE_DELETE( m_pMenuValue ); SAFE_DELETE( m_pMessageBar ); } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CModeSelectBackManager::Init( void ) { m_pModeSelectStage->Init(); m_pModeSelectStage->SetWorldPos( -1.0f,0.0f, 2.0f ); // αブレンド用画像 m_pAlphaBlend->SetVertexPos( 400.0f,320.0f,800.0f,640.0f ); m_pAlphaBlend->SetDiffuse( 255,255,255,0 ); // メニューの画像 m_pMenuValue->Init(); m_pMenuValue->SetVertexPos( 150.0f, 80.0f, 230.0f,120.0f ); // メッセージバー m_pMessageBar->Init(); m_pMessageBar->SetVertexPos( 550.0f,540.0f, 470.0f, 128.0f ); m_eMessageBarStatus = eMessageBarStatus::eMessageBarNormal; return true; } //---------------------------------------------------- // 処理 //---------------------------------------------------- void CModeSelectBackManager::Run( void ) { this->MessageBarAnimation(); } //---------------------------------------------------- // フェードアウト処理 //---------------------------------------------------- bool CModeSelectBackManager::Fade( void ) { if ( m_pAlphaBlend->FadeOut( 5 ) ) { return true; } return false; } //---------------------------------------------------- // キー入力 //---------------------------------------------------- void CModeSelectBackManager::RunKey( CONST UINT index ) { m_resIndexNo = index; // 添え字の番号を対応させる m_isBarAnimation = true; } //---------------------------------------------------- // エンターキー入力 //---------------------------------------------------- void CModeSelectBackManager::RunKeyEnter( void ) { m_isAlphaBlend = true; } //---------------------------------------------------- // メッセージバーのアニメーション //---------------------------------------------------- bool CModeSelectBackManager::MessageBarAnimation( void ) { static bool isHide = false; // アニメーションのフラグがONになったら if( m_isBarAnimation == true ) { if( m_pMessageBar->RepositionRight( 1000.0f, 40.0f ) == true ) { m_isBarAnimation = false; isHide = true; } } if( isHide == true ) { if( m_pMessageBar->RepositionLeft( 550.0f, 40.0f ) == true ) { isHide = false; // アニメーションが終わった m_eMessageBarStatus = eMessageBarStatus::eMessageBarNormal; return true; } } return false; } //---------------------------------------------------- // 描画 //---------------------------------------------------- void CModeSelectBackManager::Draw( void ) { CDirectDrawSystem::GetInstance()->Draw3D( CResourceManager::GetInstance()->GetXFile( m_pResModeSelectStageFilePath ), m_pModeSelectStage->GetWorldMtx() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResMenuValueFilePath )->Get(), m_pMenuValue->GetVertex() ); CDirectDrawSystem::GetInstance()->DrawSpriteRHW( CResourceManager::GetInstance()->GetTexture( m_pResMessageBar[m_resIndexNo] )->Get(), m_pMessageBar->GetVertex() ); } //---------------------------------------------------- // αブレンド用画像の描画 //---------------------------------------------------- void CModeSelectBackManager::DrawAlpha( void ) { CDirectDrawSystem::GetInstance()->DrawSpriteRHW( m_pAlphaBlend->GetVertex() ); } //---------------------------------------------------- // 終了 //---------------------------------------------------- bool CModeSelectBackManager::Uninit( void ) { return true; }<file_sep>//---------------------------------------------------- // CMySQLScoreManager // Scoreテーブルの管理クラス // // @date 2014/2/19 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MYSQL_SCORE_MANAGER_H_ #define _C_MYSQL_SCORE_MANAGER_H_ #include "../MySQLSource/CMySQLManager.hpp" #include "../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" #include <string> #include "../ObjectSource/CScore.hpp" #pragma warning(disable : 4996) // 使うテーブルの名前 #define SCORE_TABLE "score" class CMySQLScoreManager { private: std::string m_scoreID; std::string m_userID; std::string m_userName; public: CMySQLScoreManager(); // コンストラクタ virtual ~CMySQLScoreManager(); // デストラクタ //---------------------------------------------------- // ユーザ情報のセット //---------------------------------------------------- void SetUserInfo ( CONST std::string* userID, CONST std::string* userName ) { m_userID = *userID; m_userName = *userName; } public: //---------------------------------------------------- // @name UpdateHighScore // @content ハイスコアの更新 // @param updateSql 更新したいSQL文 // @return bool ハイスコアの更新が成功か失敗 // @date 2014/2/19 //---------------------------------------------------- bool UpdateHighScore ( CONST std::string* updateSql ); //---------------------------------------------------- // @name GetTable // @content スコアテーブルの取得 // @param // @return CScore // @date 2014/2/19 //---------------------------------------------------- CScore* GetScore ( CScore* score ); }; #endif _C_MYSQL_SCORE_MANAGER_H_<file_sep>//---------------------------------------------------- // CModelViewBackManager // モデルの背景の管理クラス // // @author T.Kawashita //---------------------------------------------------- #ifndef _C_MODELVIEW_BACK_MANAGER_H_ #define _C_MODELVIEW_BACK_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" class CModelViewBackManager { private: C2DSpriteAlphaBlend *m_pModelViewBack; private: bool m_isFade; public: CModelViewBackManager ( void ); ~CModelViewBackManager ( void ); public: void Run ( void ); void Draw ( void ); void Init ( void ); void Uninit ( void ); public: //---------------------------------------------------- // Fade // @data none // @return bool //---------------------------------------------------- bool Fade ( void ); //---------------------------------------------------- // フェードのフラグセット // @data isFade // @return none //---------------------------------------------------- void SetIsFade ( bool isFade ) { m_isFade = isFade; } //---------------------------------------------------- // フェードのフラグゲット // @data none // @return m_isFade //---------------------------------------------------- bool GetIsFade ( void ) { return m_isFade; } }; #endif _C_MODELVIEW_BACK_MANAGER_H_<file_sep> #include "../../KaiFrameWorkHeader/ResourceHeader/CResourceTexture.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CResourceTexture::CResourceTexture( void ) { m_pTexture = nullptr; } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CResourceTexture::~CResourceTexture( void ) { SAFE_DELETE_RELESE( m_pTexture ); } //---------------------------------------------------- // テクスチャのロード //---------------------------------------------------- bool CResourceTexture::Load( CONST LPSTR filePath ) { //デバイスハンドルをシングルトンで取得 CONST LPDIRECT3DDEVICE9& pd3dDevice = CDirectX9FrameWork::Getpd3dDevice(); DEBUG::PrintfColor(DEBUG::H_CYAN,"%s\n", filePath ); // テクスチャロード if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, filePath, &m_pTexture ))) { // ロード失敗 DEBUG::PrintfColor(DEBUG::H_RED," Load Texture Failed...\n" ); return false; } DEBUG::PrintfColor( DEBUG::H_GREEN,"Load Texture Successfully \n" ); return true; }<file_sep>//---------------------------------------------------- // CStageBlock // ステージのダイスの管理クラス // // @date 2013/11/28 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_STAGE_BLOCK_MANAGER_H_ #define _C_STAGE_BLOCK_MANAGER_H_ #include <Windows.h> #include "../../GameMathSource/CDiceRandSystem.h" #include "../../ObjectSource/GameScene/CStageBlockObj.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/UtilityHeader/Macro.hpp" #define BLOCK_SIZE ( 4.0f ) // マス目一つの大きさ #define BLOCK_MAXSIZE ( 12.0f ) // ステージの最大の大きさ #define BLOCK_DEFAULT_NUM_X ( 7 ) // デフォルトのステージのXマス目数 #define BLOCK_DEFAULT_NUM_Y ( 1 ) // デフォルトのステージのYマス目数 #define BLOCK_DEFAULT_NUM_Z ( 7 ) // デフォルトのステージのZマス目数 // デフォルトのステージのブロックの数 #define BLOCK_DEFAULT_MAX_NUM ( BLOCK_DEFAULT_NUM_X * BLOCK_DEFAULT_NUM_Y * BLOCK_DEFAULT_NUM_Z ) class CStageBlockManager { private: CStageBlockObj m_stageBlock[ BLOCK_DEFAULT_MAX_NUM ]; // ステージのブロックOBJ USHORT m_blockNum; // ステージのブロック数 USHORT m_xNum; // ステージのブロックのXマス目数 USHORT m_yNum; // ステージのブロックのYマス目数 USHORT m_zNum; // ステージのブロックのZマス目数 // コンストラクタ CStageBlockManager ( void ); CStageBlockManager ( CONST CStageBlockManager& stageBlockManager ){} // コピーコンストラクタを防ぐ CStageBlockManager operator= ( CONST CStageBlockManager& stageBlockManager ){} // メンバの代入を防ぐ public: // インスタンス取得場所 static CStageBlockManager* GetInstance( void ) { static CStageBlockManager stageBlockManager; return &stageBlockManager; } // ステージのブロックOBJの取得 CStageBlockObj* GetStageBlock ( CONST UINT index ) { return &m_stageBlock[ index ]; } public: //---------------------------------------------------- // マス目数取得 //---------------------------------------------------- CONST USHORT GetXNum ( void ) { return m_xNum; } CONST USHORT GetYNum ( void ) { return m_yNum; } CONST USHORT GetZNum ( void ) { return m_zNum; } private: float m_xSize; // ステージのブロック最大横サイズ float m_ySize; // ステージのブロック最大縦サイズ float m_zSize; // ステージのブロック最大奥行サイズ public: //---------------------------------------------------- // サイズ取得 //---------------------------------------------------- CONST float GetXSize ( void ) { return m_xSize; } CONST float GetYSize ( void ) { return m_ySize; } CONST float GetZSize ( void ) { return m_zSize; } public: // デストラクタ ~CStageBlockManager ( void ); //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool Init ( void ); //---------------------------------------------------- // @name SetStagePos // @content ステージのブロック位置情報をセット(デフォルト値) // @param none // @return none // @date 2013/11/29 //---------------------------------------------------- void SetBlockPos ( void ); //---------------------------------------------------- // @name SetStagePos // @content ステージのブロック位置情報をセット // @param xNum 横数 // @param yNum 高さ // @param zNum 奥数 // @return none // @date 2013/11/29 //---------------------------------------------------- bool SetBlockPos ( CONST UINT xNum, CONST UINT yNum, CONST UINT zNum ); //---------------------------------------------------- // @name GetIndexToDicePos // @content ブロックのインデックスをダイスの位置から取得 // @param xPos X座標 // @param zPos Z座標 // @return UINT ブロックインデックス番号 // @date 2013/12/2 // @update 2014/2/1 引数 Y座標をはずしました //---------------------------------------------------- CONST UINT GetIndexToDicePos ( CONST float xPos, CONST float zPos ); //---------------------------------------------------- // @name GetIndexToPlayerPos // @content ブロックのインデックスをプレイヤー位置から取得 // @param xPos X座標 // @param zPos Z座標 // @return UINT ブロックインデックス番号 // @date 2014/2/1 // @update //---------------------------------------------------- CONST UINT GetIndexToPlayerPos ( CONST float xPos, CONST float zPos ); //---------------------------------------------------- // @name GetPos // @content ブロックの位置を添え字から位置取得 // @param index 添え字 // @return D3DXVECTOR3* // @date 2013/12/2 //---------------------------------------------------- D3DXVECTOR3* GetPos ( UINT index ) { return m_stageBlock[ index ].GetPosition(); } //---------------------------------------------------- // @name GetBlockIndexRnd // @content ランダムでブロックの添え字を取得 // @param none // @return UINT 位置情報 // @date 2013/12/2 //---------------------------------------------------- CONST UINT GetBlockIndexRnd ( void ) { unsigned int rnd = CDiceRandSystem::GetInstance()->GetPos( m_blockNum ); return rnd; } //---------------------------------------------------- // @name GetDiceNum // @content ステージのブロックの数を取得 // @param none // @return UINT ブロックの最大数 // @date 2013/12/2 //---------------------------------------------------- CONST UINT GetDiceNum ( void ) { return m_blockNum; } //---------------------------------------------------- // @name GetIsOnDice // @content ブロック上にダイスがあるかどうか取得 // @param diceNo 調べたい添え字番号 // @return bool あるかないか // @date 2013/12/2 //---------------------------------------------------- bool GetIsOnDice ( CONST UINT diceNo ) { if( diceNo >= 0 ) return m_stageBlock[ diceNo ].CheckOnDice(); else return 0; } //---------------------------------------------------- // @name SetBlockToDice // @content ブロックにダイスの情報をセット // @param CDiceObj* ダイス本体 // @param diceNo ダイスの番号 // @return none // @date 2013/12/2 //---------------------------------------------------- void SetBlockToDiceInfo ( CDiceObj* dice, int diceNo ); //---------------------------------------------------- // @name SetIsOnDice // @content ダイスが乗っているかどうかのフラグをセット // @param diceNo セットしたいダイスの番号 // @param isDice true or false // @return none //---------------------------------------------------- void SetIsOnDice ( CONST UINT diceNo, bool isDice ) { m_stageBlock[ diceNo ].SetIsOnDice( isDice ); } }; #endif _C_STAGE_BLOCK_MANAGER_H_<file_sep>//---------------------------------------------------- // CDiceInfoManager // 現在乗っているダイスを表示するマネージャ // // @date 2014/2/9 // @author T.Kawashita //---------------------------------------------------- #ifndef _C_DICE_INFO_MANAGER_H_ #define _C_DICE_INFO_MANAGER_H_ #include "../../KaiFrameWork/KaiFrameWorkHeader/DirectX9Header/CDirectX9DrawSystem.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/ResourceHeader/CResourceManager.h" #include "../../KaiFrameWork/KaiFrameWorkHeader/GameObjectHeader/2D/C2DSpriteAlphaBlend.h" #include "../../ObjectSource/GameScene/CDiceInfoObj.h" class CDiceInfoManager { private: C2DSpriteRHW* m_pInfo; LPSTR m_pResInfoFilePath; CDiceInfoObj* m_pDiceInfo; // 描画用の本体のアドレス LPSTR m_pResInfoDiceFilePath; // 描画用の本体のファイルパス public: CDiceInfoManager ( void ); // コンストラクタ ~CDiceInfoManager ( void ); // デストラクタ public: void SetInfoDice ( CONST D3DXMATRIX* mainDiceWorldMtx ); bool Init ( void ); bool Uninit ( void ); void Draw ( void ); void SetIsExist ( bool isExist ) { m_pDiceInfo->SetIsExist( isExist ); } public: void BrightChange ( bool isBright ) { if( isBright == true ) { m_pInfo->SetDiffuse( 255, 255, 255, 255 ); } else { m_pInfo->SetDiffuse( 100, 100, 100, 255 ); } } }; #endif _C_DICE_INFO_MANAGER_H_<file_sep> #include "CStageBlockManager.h" //---------------------------------------------------- // コンストラクタ //---------------------------------------------------- CStageBlockManager::CStageBlockManager( void ) { } //---------------------------------------------------- // デストラクタ //---------------------------------------------------- CStageBlockManager::~CStageBlockManager( void ) { } //---------------------------------------------------- // ステージのサイズセット(デフォルトサイズ) //---------------------------------------------------- void CStageBlockManager::SetBlockPos( void ) { float workX = -BLOCK_MAXSIZE; float workZ = BLOCK_MAXSIZE; int no = 0; // ステージの情報格納 for( int i = 0; i < BLOCK_DEFAULT_NUM_Z; ++ i ) { for( int j = 0; j < BLOCK_DEFAULT_NUM_X; ++ j ) { m_stageBlock[no].SetPosition( workX,0.0f,workZ ); workX += BLOCK_SIZE; m_stageBlock[no].SetNo( no ); no ++; } workX = -BLOCK_MAXSIZE; workZ -= BLOCK_SIZE; } // ステージの最大サイズをメンバにセット m_xSize = BLOCK_MAXSIZE; m_ySize = 1; m_zSize = BLOCK_MAXSIZE; // ステージのマス目数をメンバにセット m_xNum = BLOCK_DEFAULT_NUM_X; m_yNum = BLOCK_DEFAULT_NUM_Y; m_zNum = BLOCK_DEFAULT_NUM_Z; // ステージのブロックの数をセット m_blockNum = BLOCK_DEFAULT_NUM_X * BLOCK_DEFAULT_NUM_Z; } //---------------------------------------------------- // ステージのサイズセット //---------------------------------------------------- bool CStageBlockManager::SetBlockPos( UINT xNum, UINT yNum, UINT zNum ) { // 引数でセットされた値が0ならセットしない if( xNum == 0 || yNum == 0 || zNum == 0 ) { return false; } float maxX = -( xNum * BLOCK_SIZE ); float maxZ = zNum * BLOCK_SIZE; // ステージの最大サイズをメンバにセット // m_xSize = BLOCK_MAXSIZE; // m_ySize = 0.0f; // m_zSize = BLOCK_MAXSIZE; // ステージのブロック数をセット m_blockNum = xNum * yNum *zNum; // ステージのマス目数をメンバにセット m_xNum = BLOCK_DEFAULT_NUM_X; m_yNum = BLOCK_DEFAULT_NUM_Y; m_zNum = BLOCK_DEFAULT_NUM_Z; return true; } //---------------------------------------------------- // ダイスの位置からインデックス番号を取得 //---------------------------------------------------- CONST UINT CStageBlockManager::GetIndexToDicePos( CONST float xPos, CONST float zPos ) { float workX = xPos / BLOCK_SIZE; float workZ = -zPos / BLOCK_SIZE; workX = workX + ( m_xSize / BLOCK_SIZE ); workZ = workZ + ( m_zSize / BLOCK_SIZE ); UINT index = UINT( workX + ( workZ * m_xNum )); return index; } //---------------------------------------------------- // プレイヤーの位置からインデックス番号を取得 //---------------------------------------------------- CONST UINT CStageBlockManager::GetIndexToPlayerPos( CONST float xPos, CONST float zPos ) { // 切り下げを行う double workX = floor( ( xPos + 2.0f ) / BLOCK_SIZE); double workZ = -floor( ( zPos + 2.0f ) / BLOCK_SIZE); workX = workX + ( m_xSize / BLOCK_SIZE ); workZ = workZ + ( m_zSize / BLOCK_SIZE ); UINT index = UINT( workX + ( workZ * m_xNum )); return index; } //---------------------------------------------------- // 初期化 //---------------------------------------------------- bool CStageBlockManager::Init( void ) { for( int i = 0; i < BLOCK_DEFAULT_MAX_NUM; ++ i ) { m_stageBlock[i].Init(); } return true; } //---------------------------------------------------- // ステージにダイスの情報をセット(移動の時はこちら) //---------------------------------------------------- void CStageBlockManager::SetBlockToDiceInfo( CDiceObj* dice, int diceNo ) { m_stageBlock[ diceNo ].SetDice( dice ); m_stageBlock[ diceNo ].SetIsOnDice( true ); }
fd32e26f395722f05e82709756ad5a3fd20cc345
[ "SQL", "Markdown", "Text", "C", "C++" ]
133
C++
Ka1kai/XI-Remake-
f8b3aaea958200d2e04d34365289ea495de28b25
a11625f9f2879069ca12b10243dccdbc62621adb
refs/heads/master
<repo_name>P79N6A/RecognitionDemo<file_sep>/ShopDEMO/app/src/main/java/com/lxl/shop/page/MainActivity.java package com.lxl.shop.page; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.TextView; import com.lxl.shop.R; /** * Created by yanglei on 2018/11/23. */ public class MainActivity extends Activity implements View.OnClickListener { TextView textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shop_page_main); initView(); initAction(); } private void initAction() { textView.setOnClickListener(this); } private void initView() { textView = findViewById(R.id.add_customer); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onClick(View view) { int id = view.getId(); if (id == R.id.add_customer) { Intent intent = new Intent(); intent.setClass(this, AddCustomerPage.class); startActivity(intent); } else { } } } <file_sep>/ShopDEMO/app/src/main/java/com/lxl/shop/viewmodel/CustomerModel.java package com.lxl.shop.viewmodel; /** * Created by yanglei on 2018/11/23. */ public class CustomerModel { public String name; public String moblie; public String email; public String birthday; public String address; public String faceId; public String iconImg; } <file_sep>/AttDEMO/base/build.gradle configurations.maybeCreate("default") artifacts.add("default", file('Aiwinn_base-1.0.5-release.aar'))
f4f6f68f956b9f0107877397a6cecbf1177e45ca
[ "Java", "Gradle" ]
3
Java
P79N6A/RecognitionDemo
c91f988a5aad3daee33f338cc0403b67deab9e0c
a07183e0b8d20d74fb8e20d93ae670ab833b3025
refs/heads/master
<file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; /** * A class for x509 certificate parsing */ class Certificate extends Structure { public static function map() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'tbsCertificate' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => [ 'name' => 0, 'implicit' => false, 'tag' => ASN1::TYPE_INTEGER, 'map' => [1=>'v1','v2','v3'] ], 'serialNumber' => [ 'tag' => ASN1::TYPE_INTEGER, 'base' => 16 ], 'signature' => Common::AlgorithmIdentifier(), 'issuer' => Common::RDNSequence(), 'validity' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'notBefore' => [ 'tag' => ASN1::TYPE_CHOICE, 'children' => [ [ 'tag' => ASN1::TYPE_GENERALIZED_TIME ], [ 'tag' => ASN1::TYPE_UTC_TIME ] ] ], 'notAfter' => [ 'tag' => ASN1::TYPE_CHOICE, 'children' => [ [ 'tag' => ASN1::TYPE_GENERALIZED_TIME ], [ 'tag' => ASN1::TYPE_UTC_TIME ] ] ] ] ], 'subject' => Common::RDNSequence(), 'SubjectPublicKeyInfo' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'algorithm' => Common::AlgorithmIdentifier(), 'publicKey' => [ 'tag' => ASN1::TYPE_BIT_STRING ] ] ], 'issuerUniqueID' => [ 'tag' => ASN1::TYPE_BIT_STRING, 'name' => 1, 'implicit' => true, 'optional' => true ], 'subjectUniqueID' => [ 'tag' => ASN1::TYPE_BIT_STRING, 'name' => 2, 'implicit' => true, 'optional' => true ], 'extensions' => Common::extensions() + [ 'name' => 3, 'implicit' => false ] ] ], 'signatureAlgorithm' => Common::AlgorithmIdentifier(), 'signatureValue' => [ 'tag' => ASN1::TYPE_BIT_STRING, ] ] ]; } } <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; /** * A class for CRL parsing */ class CRL extends Structure { public static function map() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'tbsCertList' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => [ 'tag' => ASN1::TYPE_INTEGER, 'map' => [1=>'v1','v2','v3'], 'optional' => true ], 'signature' => Common::AlgorithmIdentifier(), 'issuer' => Common::RDNSequence(), 'thisUpdate' => [ 'tag' => ASN1::TYPE_CHOICE, 'children' => [ [ 'tag' => ASN1::TYPE_GENERALIZED_TIME ], [ 'tag' => ASN1::TYPE_UTC_TIME ] ] ], 'nextUpdate' => [ 'tag' => ASN1::TYPE_CHOICE, 'optional' => true, 'children' => [ [ 'tag' => ASN1::TYPE_GENERALIZED_TIME ], [ 'tag' => ASN1::TYPE_UTC_TIME ] ] ], 'revokedCertificates' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'optional' => true, 'repeat' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'userCertificate' => [ 'tag' => ASN1::TYPE_INTEGER, 'base' => 16 ], 'revocationDate' => [ 'tag' => ASN1::TYPE_CHOICE, 'children' => [ [ 'tag' => ASN1::TYPE_GENERALIZED_TIME ], [ 'tag' => ASN1::TYPE_UTC_TIME ] ] ], 'extensions' => Common::extensions() ] ] ], 'extensions' => Common::extensions() + [ 'name' => 0, 'implicit' => false, 'optional' => true ] ] ], 'signatureAlgorithm' => Common::AlgorithmIdentifier(), 'signatureValue' => [ 'tag' => ASN1::TYPE_BIT_STRING, ] ] ]; } } <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\Decoder; use \vakata\asn1\LazyDecoder; use \vakata\asn1\Reader; abstract class Structure { protected $reader; /** * Create an instance by passing in an instantiated reader. * * @param Reader $reader */ public function __construct(Reader $reader) { $this->reader = $reader; } /** * Create an instance from a string. * * @param string $data * @return Structure */ public static function fromString($data) { if (preg_match('(^[\-]+BEGIN.*?\n)i', $data)) { $data = base64_decode(preg_replace('(^[\-]+(BEGIN|END).*$)im', '', $data)); } return new static(Reader::fromString($data)); } /** * Create an instance from a file * * @param string $path the path to the file to parse * @return Structure */ public static function fromFile($path) { $reader = Reader::fromFile($path); $data = $reader->bytes(1024); if (preg_match('(^[\-]+BEGIN.*?\n)i', $data)) { return static::fromString( base64_decode(preg_replace('(^[\-]+(BEGIN|END).*$)im', '', file_get_contents($path))) ); } return new static(Reader::fromFile($path)); } /** * Output the raw ASN1 structure of the data. * * @return array */ public function structure(bool $lazy = false) { $this->reader->seek(0); $decoder = $lazy ? (new LazyDecoder($this->reader)) : (new Decoder($this->reader)); return $decoder->structure(); } /** * Get the mapped or values only view of the parsed data. * * @param boolean $valuesOnly should only values be returned or the map be used - defaults to `false` - use a map * @return mixed */ public function toArray(bool $valuesOnly = false, bool $lazy = false) { $this->reader->seek(0); $decoder = $lazy ? (new LazyDecoder($this->reader)) : (new Decoder($this->reader)); return $valuesOnly ? $decoder->values() : $decoder->map(static::map()); } public function __toString() { $iterator = new \RecursiveIteratorIterator( new \RecursiveArrayIterator($this->toArray()), \RecursiveIteratorIterator::LEAVES_ONLY ); $result = []; foreach ($iterator as $k => $v) { if (strlen($v)) { $result[] = str_repeat(' ', $iterator->getDepth()) . $v; } } return implode("\r\n", $result); } public function getReader() { return $this->reader; } abstract protected static function map(); } <file_sep><?php /* Based on PHPSECLIB: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/File/ASN1.php */ namespace vakata\asn1; use DateTime; /** * A class handling ASN1 decoding. */ class Decoder { protected $reader; /** * Create an instance by passing in an instantiated reader. * * @param Reader $reader */ public function __construct(Reader $reader) { $this->reader = $reader; } /** * Create a new instance from an ASN1 string. * * @param string $data the ASN1 data * @return Decoder */ public static function fromString($data) { return new static(Reader::fromString($data)); } /** * Create a new instance from a file. * * @param string $path the path to the file to parse * @return Decoder */ public static function fromFile($path) { return new static(Reader::fromFile($path)); } public function getReader() { return $this->reader; } protected function header() { $start = $this->reader->pos(); $identifier = ord($this->reader->byte()); $constructed = ($identifier >> 5) & 1; // 6th bit $class = ($identifier >> 6) & 3; // 7th and 8th bits $tag = $identifier & 31; // first 5 bits if ($tag === 31) { // long tag (read each 7 bits until the 8th is 0) $tag = 0; while (true) { $temp = ord($this->reader->byte()); $tag <<= 7; $tag |= $temp & 127; if (($temp & 128) === 0) { break; } } } if ($tag === 0 && $class === 0) { return [ 'constructed' => $constructed, 'class' => $class, 'tag' => $tag, 'start' => $start, 'length' => ($this->reader->pos() - $start), 'content_start' => $this->reader->pos(), 'content_length' => 0 ]; } $temp = ord($this->reader->byte()); $length = null; if ($temp === 128) { // indefinite $length = null; } elseif ($temp & 128) { // long form $octets = $temp & 127; $length = 0; for ($i = 0; $i < $octets; $i++) { $length <<= 8; $length |= ord($this->reader->byte()); } } else { // short form $length = $temp; } return [ 'constructed' => $constructed, 'class' => $class, 'tag' => $tag, 'start' => $start, 'length' => $length !== null ? $length + ($this->reader->pos() - $start) : null, 'content_start' => $this->reader->pos(), 'content_length' => $length ]; } protected function decode($header) { $contents = $header['content_length'] > 0 ? $this->reader->chunk($header['content_start'], $header['content_length']) : ''; if ($header['class'] !== ASN1::CLASS_UNIVERSAL) { return $contents; } return $this->decodeContents($header['tag'], $header['constructed'], $contents); } protected function decodeContents($tag, $constructed, $contents) { switch ($tag) { case ASN1::TYPE_BOOLEAN: return (bool)ord($contents[0]); case ASN1::TYPE_INTEGER: return ASN1::fromBase256($contents); case ASN1::TYPE_ENUMERATED: return (int)base_convert(ASN1::fromBase256($contents), 2, 10); case ASN1::TYPE_REAL: // TODO: read the specs return false; case ASN1::TYPE_BIT_STRING: if ($constructed) { $temp = static::fromString($contents)->values(); $real = ''; for ($i = 0; $i < count($temp) - 1; $i++) { $real .= $temp['value']; } return $temp[count($temp) - 1]['value'][0] . $real . substr($temp[$i]['value'], 1); } return $contents; case ASN1::TYPE_OCTET_STRING: if ($constructed) { return implode('', array_map(function ($v) { if (!is_array($v)) { return $v; } return $v['value']; }, static::fromString($contents)->values())); } return $contents; case ASN1::TYPE_BMP_STRING: return extension_loaded("iconv") ? iconv('UCS-2BE', 'UTF-8', $contents) : $contents; case ASN1::TYPE_UNIVERSAL_STRING: return extension_loaded("iconv") ? iconv('UCS-4BE', 'UTF-8', $contents) : $contents; case ASN1::TYPE_NULL: return null; case ASN1::TYPE_UTC_TIME: $format = 'YmdHis'; $matches = []; if (preg_match('#^(\d{10})(Z|[+-]\d{4})$#', $contents, $matches)) { $contents = $matches[1] . '00' . $matches[2]; } $prefix = substr($contents, 0, 2) >= 50 ? '19' : '20'; $contents = $prefix . $contents; if ($contents[strlen($contents) - 1] == 'Z') { $contents = substr($contents, 0, -1) . '+0000'; } if (strpos($contents, '-') !== false || strpos($contents, '+') !== false) { $format .= 'O'; } $result = @DateTime::createFromFormat($format, $contents); return $result ? $result->getTimestamp() : false; case ASN1::TYPE_GENERALIZED_TIME: $format = 'YmdHis'; if (strpos($contents, '.') !== false) { $format .= '.v'; } if ($contents[strlen($contents) - 1] == 'Z') { $contents = substr($contents, 0, -1) . '+0000'; } if (strpos($contents, '-') !== false || strpos($contents, '+') !== false) { $format .= 'O'; } $result = @DateTime::createFromFormat($format, $contents); return $result ? $result->format(strpos($contents, '.') !== false ? 'U.v' : 'U') : false; case ASN1::TYPE_OBJECT_IDENTIFIER: $temp = ord($contents[0]); $real = sprintf('%d.%d', floor($temp / 40), $temp % 40); $obid = 0; // process septets for ($i = 1; $i < strlen($contents); $i++) { $temp = ord($contents[$i]); $obid <<= 7; $obid |= $temp & 0x7F; if (~$temp & 0x80) { $real .= '.' . $obid; $obid = 0; } } return $real; default: return $contents; } } /** * Dump the parsed structure of the ASN1 data. * * @param mixed $max internal - do not use * @return mixed in most cases this is an array, as all complex structures are either a sequence or a set */ public function structure($max = null) { $skeleton = []; while (!$this->reader->eof() && ($max === null || $this->reader->pos() < $max)) { $header = $this->header(); if ($header['class'] === 0 && $header['tag'] === 0) { if ($max === null) { break; } else { continue; } } if ($header['class'] !== ASN1::CLASS_UNIVERSAL && $header['constructed']) { $header['children'] = $this->structure( $header['length'] ? $header['start'] + $header['length'] - 1 : null ); if ($header['length'] === null) { $this->reader->byte(); $header['length'] = $this->reader->pos() - $header['start']; $header['content_length'] = $this->reader->pos() - $header['content_start']; } $skeleton[] = $header; } else { if ($header['class'] === ASN1::CLASS_UNIVERSAL && in_array($header['tag'], [ASN1::TYPE_SET, ASN1::TYPE_SEQUENCE]) ) { $header['children'] = $this->structure( $header['length'] ? $header['start'] + $header['length'] - 1 : null ); if ($header['length'] === null) { $this->reader->byte(); $header['length'] = $this->reader->pos() - $header['start']; $header['content_length'] = $this->reader->pos() - $header['content_start']; } } else { if ($header['length'] === null) { $this->reader->readUntil(chr(0).chr(0)); $header['length'] = $this->reader->pos() - $header['start']; $header['content_length'] = $this->reader->pos() - $header['content_start']; } else { if ($header['content_length'] > 0) { $this->reader->bytes($header['content_length']); } } } if (!isset($header['children'])) { $pos = $this->reader->pos(); $header['value'] = $this->decode($header); $this->reader->seek($pos); } $skeleton[] = $header; } } return $skeleton; } /** * Dump the parsed values only. * * @param mixed $skeleton internal - do not use * @return mixed in most cases this is an array, as all complex structures are either a sequence or a set */ public function values($skeleton = null) { $skeleton = $skeleton ?? $this->structure(); foreach ($skeleton as $k => $v) { if (isset($v['children'])) { $skeleton[$k] = $this->values($v['children']); } else { $skeleton[$k] = $v['value'] ?? null; } } return $skeleton; } /** * Map the parsed data to a map * * @param array $map the map to use - look in the structure classes for example map arrays * @param mixed $skeleton internal - do not use * @return mixed in most cases this is an array, as all complex structures are either a sequence or a set */ public function map($map, $skeleton = null) { $null = null; if ($skeleton === null && $this->reader->pos() !== 0) { $this->reader->rewind(); } $skeleton = $skeleton ?? $this->structure()[0] ?? null; if (!isset($skeleton)) { throw new ASN1Exception('No decoded data for map'); } if ($skeleton['class'] !== ASN1::CLASS_UNIVERSAL) { if ($map['tag'] === ASN1::TYPE_CHOICE) { foreach ($map['children'] as $child) { if (isset($child['name']) && (int)$skeleton['tag'] === (int)$child['name']) { $map = $child; if (isset($child['value']) && $child['value']) { return $child['value']; } break; } } } } if ($skeleton['class'] !== ASN1::CLASS_UNIVERSAL) { if (isset($map['implicit']) && $map['implicit']) { $skeleton['class'] = ASN1::CLASS_UNIVERSAL; $skeleton['tag'] = $map['tag']; if (isset($skeleton['value'])) { $skeleton['value'] = $this->decodeContents($skeleton['tag'], true, $skeleton['value']); } } else { $skeleton = $skeleton['children'][0] ?? null; } } if ($map['tag'] === ASN1::TYPE_CHOICE) { foreach ($map['children'] as $child) { if ($skeleton['tag'] === $child['tag']) { $map = $child; if (isset($child['value']) && $child['value']) { return $child['value']; } break; } } } if (in_array($map['tag'], [ASN1::TYPE_SEQUENCE, ASN1::TYPE_SET]) && in_array($skeleton['tag'], [ASN1::TYPE_SEQUENCE, ASN1::TYPE_SET])) { $map['tag'] = $skeleton['tag']; } if ($map['tag'] === ASN1::TYPE_ANY && isset($skeleton['tag'])) { $map['tag'] = $skeleton['tag']; } if (!in_array($map['tag'], [ASN1::TYPE_ANY, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_ANY_DER]) && $map['tag'] !== $skeleton['tag'] ) { if (!isset($map['optional']) || !$map['optional']) { throw new ASN1Exception('Decoded data does not match mapping - ' . $skeleton['tag']); } return $null; } else { switch ($map['tag']) { case ASN1::TYPE_ANY_DER: $temp = $this->reader->chunk($skeleton['start'], $skeleton['length']); return $temp; case ASN1::TYPE_ANY_SKIP: return $null; case ASN1::TYPE_ANY_RAW: return $skeleton['value'] ?? null; case ASN1::TYPE_SET: if (isset($map['repeat'])) { $result = []; foreach ($skeleton['children'] as $v) { $result[] = $this->map($map['repeat'], $v); } return $result; } else { if (!isset($map['children'])) { return $null; } $temp = $skeleton['children']; $result = []; // named first foreach ($map['children'] as $k => $v) { if (isset($v['name'])) { $result[$k] = null; foreach ($temp as $kk => $vv) { if ($vv['class'] !== ASN1::CLASS_UNIVERSAL && (int)$v['name'] === $vv['tag']) { try { if (isset($v['implicit']) && $v['implicit']) { $vv['class'] = ASN1::CLASS_UNIVERSAL; $vv['tag'] = $map['tag']; if (isset($vv['value'])) { $vv['value'] = $this->decodeContents($vv['tag'], true, $vv['value']); } } else { $vv = $vv['children'][0] ?? null; } $result[$k] = $this->map($v, $vv); unset($temp[$kk]); break; } catch (ASN1Exception $e) { // continue trying other children in case of failure } } } if ($result[$k] === null && (!isset($v['optional']) || !$v['optional'])) { throw new ASN1Exception('Missing tagged type - ' . $k); } } } foreach ($map['children'] as $k => $v) { if (isset($v['name'])) { continue; } $result[$k] = null; foreach ($temp as $kk => $vv) { if ($v['tag'] === $vv['tag'] || in_array( $v['tag'], [ ASN1::TYPE_ANY, ASN1::TYPE_ANY_DER, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_CHOICE ] ) ) { try { $result[$k] = $this->map($v, $vv); unset($temp[$kk]); break; } catch (ASN1Exception $e) { $result[$k] = null; } } } if ($result[$k] === null && (!isset($v['optional']) || !$v['optional'])) { throw new ASN1Exception('Decoded data does not match mapping - ' . $k); } } return $result; } break; case ASN1::TYPE_SEQUENCE: if (isset($map['repeat'])) { $result = []; foreach ($skeleton['children'] as $v) { $result[] = $this->map($map['repeat'], $v); } return $result; } else { if (!isset($map['children'])) { return $null; } $result = []; foreach ($skeleton['children'] as $kk => $vv) { foreach ($map['children'] as $k => $v) { if (isset($v['name'])) { $result[$k] = null; if ($vv['class'] !== ASN1::CLASS_UNIVERSAL && (int)$v['name'] === $vv['tag']) { if (isset($v['implicit']) && $v['implicit']) { $vv['class'] = ASN1::CLASS_UNIVERSAL; $vv['tag'] = $v['tag']; if (isset($vv['value'])) { $vv['value'] = $this->decodeContents($vv['tag'], true, $vv['value']); } } else { $vv = $vv['children'][0] ?? null; } $result[$k] = $this->map($v, $vv); unset($map['children'][$k]); break; } else { if (!isset($v['optional']) || !$v['optional']) { throw new ASN1Exception('Missing tagged type - ' . $k); } } unset($map['children'][$k]); continue; } if ($v['tag'] === $vv['tag'] || in_array( $v['tag'], [ ASN1::TYPE_ANY, ASN1::TYPE_ANY_DER, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_CHOICE ] ) ) { try { unset($map['children'][$k]); $result[$k] = $this->map($v, $vv); break; } catch (ASN1Exception $e) { // continue trying other children in case of failure } } if (!isset($v['optional']) || !$v['optional']) { throw new ASN1Exception('Missing type - ' . $k); } else { $result[$k] = null; unset($map['children'][$k]); } } } return $result; } break; case ASN1::TYPE_OBJECT_IDENTIFIER: $temp = isset($map['resolve']) && $map['resolve'] ? ASN1::OIDtoText($skeleton['value']) : $skeleton['value']; return $temp; case ASN1::TYPE_OCTET_STRING: if (isset($map['der']) && $map['der']) { $temp = static::fromString($skeleton['value']); $temp = isset($map['map']) ? $temp->map($map['map']) : $temp->values(); return $temp; } else { $temp = isset($map['raw']) && $map['raw'] ? $skeleton['value'] : base64_encode($skeleton['value']); return $temp; } break; case ASN1::TYPE_INTEGER: $base = isset($map['base']) && (int)$map['base'] ? (int)$map['base'] : 10; if ($base < 3) { $result = $skeleton['value']; } else { if (strlen($skeleton['value']) > 53 && $base === 16) { $hex = ''; for ($i = strlen($skeleton['value']) - 4; $i >= 0; $i-=4) { $hex .= dechex((int)bindec(substr($skeleton['value'], $i, 4))); } $result = strrev($hex); } else { $temp = base_convert($skeleton['value'], 2, $base); if ($base === 10) { $temp = (int)$temp; } $result = $temp; } } if (isset($map['map']) && isset($map['map'][$result])) { $result = $map['map'][$result]; } return $result; case ASN1::TYPE_UTC_TIME: case ASN1::TYPE_GENERALIZED_TIME: return $skeleton['value']; default: $result = $skeleton['value']; if (isset($map['map']) && isset($map['map'][$result])) { $result = $map['map'][$result]; } return $result; } } } } <file_sep>## Table of contents - [\vakata\asn1\ASN1](#class-vakataasn1asn1) - [\vakata\asn1\ASN1Exception](#class-vakataasn1asn1exception) - [\vakata\asn1\Decoder](#class-vakataasn1decoder) - [\vakata\asn1\Encoder](#class-vakataasn1encoder) - [\vakata\asn1\Reader](#class-vakataasn1reader) - [\vakata\asn1\structures\Certificate](#class-vakataasn1structurescertificate) - [\vakata\asn1\structures\Common](#class-vakataasn1structurescommon) - [\vakata\asn1\structures\CRL](#class-vakataasn1structurescrl) - [\vakata\asn1\structures\OCSPRequest](#class-vakataasn1structuresocsprequest) - [\vakata\asn1\structures\OCSPResponse](#class-vakataasn1structuresocspresponse) - [\vakata\asn1\structures\P7S](#class-vakataasn1structuresp7s) - [\vakata\asn1\structures\Structure (abstract)](#class-vakataasn1structuresstructure-abstract) - [\vakata\asn1\structures\TimestampRequest](#class-vakataasn1structurestimestamprequest) - [\vakata\asn1\structures\TimestampResponse](#class-vakataasn1structurestimestampresponse) <hr /> ### Class: \vakata\asn1\ASN1 | Visibility | Function | |:-----------|:---------| | public static | <strong>OIDtoText(</strong><em>mixed</em> <strong>$id</strong>)</strong> : <em>void</em> | | public static | <strong>TextToOID(</strong><em>mixed</em> <strong>$text</strong>)</strong> : <em>void</em> | | public static | <strong>fromBase256(</strong><em>string</em> <strong>$string</strong>)</strong> : <em>integer/string the converted number</em><br /><em>Convert a number from base256</em> | | public static | <strong>toBase256(</strong><em>integer</em> <strong>$number</strong>, <em>integer</em> <strong>$base=10</strong>)</strong> : <em>string the number in base256</em><br /><em>Convert a number to base256</em> | <hr /> ### Class: \vakata\asn1\ASN1Exception | Visibility | Function | |:-----------|:---------| *This class extends \Exception* *This class implements \Throwable* <hr /> ### Class: \vakata\asn1\Decoder > A class handling ASN1 decoding. | Visibility | Function | |:-----------|:---------| | public | <strong>__construct(</strong><em>[\vakata\asn1\Reader](#class-vakataasn1reader)</em> <strong>$reader</strong>)</strong> : <em>void</em><br /><em>Create an instance by passing in an instantiated reader.</em> | | public static | <strong>fromFile(</strong><em>string</em> <strong>$path</strong>)</strong> : <em>[\vakata\asn1\Decoder](#class-vakataasn1decoder)</em><br /><em>Create a new instance from a file.</em> | | public static | <strong>fromString(</strong><em>string</em> <strong>$data</strong>)</strong> : <em>[\vakata\asn1\Decoder](#class-vakataasn1decoder)</em><br /><em>Create a new instance from an ASN1 string.</em> | | public | <strong>map(</strong><em>array</em> <strong>$map</strong>, <em>mixed</em> <strong>$skeleton=null</strong>)</strong> : <em>mixed in most cases this is an array, as all complex structures are either a sequence or a set</em><br /><em>Map the parsed data to a map</em> | | public | <strong>structure(</strong><em>mixed</em> <strong>$max=null</strong>)</strong> : <em>mixed in most cases this is an array, as all complex structures are either a sequence or a set</em><br /><em>Dump the parsed structure of the ASN1 data.</em> | | public | <strong>values(</strong><em>mixed</em> <strong>$skeleton=null</strong>)</strong> : <em>mixed in most cases this is an array, as all complex structures are either a sequence or a set</em><br /><em>Dump the parsed values only.</em> | | protected | <strong>decode(</strong><em>mixed</em> <strong>$header</strong>)</strong> : <em>void</em> | | protected | <strong>header()</strong> : <em>void</em> | <hr /> ### Class: \vakata\asn1\Encoder > A class handling ASN1 encoding. | Visibility | Function | |:-----------|:---------| | public static | <strong>encode(</strong><em>mixed</em> <strong>$source</strong>, <em>array</em> <strong>$mapping</strong>)</strong> : <em>mixed raw DER output (base64_encode if needed), false on failure</em><br /><em>Encode some data to DER using a mapping array.</em> | | protected static | <strong>length(</strong><em>mixed</em> <strong>$length</strong>)</strong> : <em>void</em> | <hr /> ### Class: \vakata\asn1\Reader | Visibility | Function | |:-----------|:---------| | public | <strong>__construct(</strong><em>mixed</em> <strong>$stream</strong>)</strong> : <em>void</em> | | public | <strong>byte()</strong> : <em>void</em> | | public | <strong>bytes(</strong><em>mixed</em> <strong>$amount=null</strong>)</strong> : <em>void</em> | | public | <strong>chunk(</strong><em>mixed</em> <strong>$beg</strong>, <em>mixed</em> <strong>$length=null</strong>)</strong> : <em>void</em> | | public | <strong>eof()</strong> : <em>void</em> | | public static | <strong>fromFile(</strong><em>mixed</em> <strong>$path</strong>)</strong> : <em>void</em> | | public static | <strong>fromString(</strong><em>mixed</em> <strong>$data</strong>)</strong> : <em>void</em> | | public | <strong>pos()</strong> : <em>void</em> | | public | <strong>readUntil(</strong><em>mixed</em> <strong>$val</strong>, <em>bool</em> <strong>$include=true</strong>)</strong> : <em>void</em> | | public | <strong>rewind()</strong> : <em>void</em> | | public | <strong>seek(</strong><em>mixed</em> <strong>$pos</strong>)</strong> : <em>void</em> | <hr /> ### Class: \vakata\asn1\structures\Certificate > A class for x509 certificate parsing | Visibility | Function | |:-----------|:---------| | public static | <strong>map()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\Common | Visibility | Function | |:-----------|:---------| | public static | <strong>AlgorithmIdentifier()</strong> : <em>void</em> | | public static | <strong>RDNSequence()</strong> : <em>void</em> | | public static | <strong>extensions()</strong> : <em>void</em> | <hr /> ### Class: \vakata\asn1\structures\CRL > A class for CRL parsing | Visibility | Function | |:-----------|:---------| | public static | <strong>map()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\OCSPRequest | Visibility | Function | |:-----------|:---------| | public static | <strong>generate(</strong><em>\string</em> <strong>$algorithm</strong>, <em>\string</em> <strong>$issuerNameHash</strong>, <em>\string</em> <strong>$issuerKeyHash</strong>, <em>\string</em> <strong>$serialNumber</strong>, <em>\string</em> <strong>$requestor=null</strong>)</strong> : <em>void</em> | | public static | <strong>map()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\OCSPResponse > A class for OCSP parsing | Visibility | Function | |:-----------|:---------| | public static | <strong>map()</strong> : <em>void</em> | | public | <strong>subject()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\P7S | Visibility | Function | |:-----------|:---------| | public static | <strong>map()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\Structure (abstract) | Visibility | Function | |:-----------|:---------| | public | <strong>__construct(</strong><em>string</em> <strong>$data</strong>)</strong> : <em>void</em><br /><em>Create an instance.</em> | | public | <strong>__toString()</strong> : <em>void</em> | | public static | <strong>fromFile(</strong><em>string</em> <strong>$path</strong>)</strong> : <em>[\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)</em><br /><em>Create an instance from a file</em> | | public static | <strong>fromString(</strong><em>string</em> <strong>$data</strong>)</strong> : <em>[\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)</em><br /><em>Create an instance from a string.</em> | | public | <strong>structure()</strong> : <em>array</em><br /><em>Output the raw ASN1 structure of the data.</em> | | public | <strong>toArray(</strong><em>\boolean</em> <strong>$valuesOnly=false</strong>)</strong> : <em>mixed</em><br /><em>Get the mapped or values only view of the parsed data.</em> | | protected static | <strong>abstract map()</strong> : <em>void</em> | <hr /> ### Class: \vakata\asn1\structures\TimestampRequest | Visibility | Function | |:-----------|:---------| | public static | <strong>generateFromData(</strong><em>string</em> <strong>$data</strong>, <em>bool/boolean/string</em> <strong>$nonce=true</strong>, <em>bool/boolean</em> <strong>$requireCert=false</strong>, <em>string</em> <strong>$alg=`'sha1'`</strong>, <em>string/null</em> <strong>$policy=null</strong>)</strong> : <em>string the raw timestamp request</em><br /><em>Generate a timestamp request (tsq) for a string</em> | | public static | <strong>generateFromFile(</strong><em>string</em> <strong>$path</strong>, <em>bool/boolean/string</em> <strong>$nonce=true</strong>, <em>bool/boolean</em> <strong>$requireCert=false</strong>, <em>string</em> <strong>$alg=`'sha1'`</strong>, <em>string/null</em> <strong>$policy=null</strong>)</strong> : <em>string the raw timestamp request</em><br /><em>Generate a timestamp request (tsq) for a file path</em> | | public static | <strong>generateFromHash(</strong><em>string</em> <strong>$data</strong>, <em>bool/boolean/string</em> <strong>$nonce=true</strong>, <em>bool/boolean</em> <strong>$requireCert=false</strong>, <em>string</em> <strong>$alg=`'sha1'`</strong>, <em>string/null</em> <strong>$policy=null</strong>)</strong> : <em>string the raw timestamp request</em><br /><em>Generate a timestamp request (tsq) for a given hash</em> | | public static | <strong>map()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <hr /> ### Class: \vakata\asn1\structures\TimestampResponse | Visibility | Function | |:-----------|:---------| | public static | <strong>map()</strong> : <em>void</em> | | public static | <strong>mapToken()</strong> : <em>void</em> | *This class extends [\vakata\asn1\structures\Structure](#class-vakataasn1structuresstructure-abstract)* <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; class TimestampResponse extends Structure { public static function map() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'status' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'status' => [ 'tag' => ASN1::TYPE_INTEGER, 'map' => [ 'granted', 'grantedWithMods', 'rejection', 'waiting', 'revocationWarning', 'revocationNotification' ] ], 'statusString' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'data' => [ 'tag' =>ASN1::TYPE_UTF8_STRING ] ] ], 'failInfo' => [ 'tag' => ASN1::TYPE_BIT_STRING, 'optional' => true ] ] ], 'timeStampToken' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'optional' => true, 'children' => [ 'contentType' => ['tag' => ASN1::TYPE_OBJECT_IDENTIFIER ], 'signedData' => [ 'name' => 0, 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => ['tag' => ASN1::TYPE_INTEGER ], 'algorithms' => [ 'tag' => ASN1::TYPE_SET, 'children' => [ 'hashAlgorithm' => Common::AlgorithmIdentifier(), ], ], "tokenInfo" => [ 'tag' => ASN1::TYPE_SEQUENCE, 'optional' => true, 'children' => [ 'contentType' => ['tag' => ASN1::TYPE_OBJECT_IDENTIFIER ], 'data' => [ 'name' => 0, 'tag' => ASN1::TYPE_OCTET_STRING, 'der' => true, 'map' => static::mapToken() ] ] ] ] ] ] ] ] ]; } public static function mapToken() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => ['tag' => ASN1::TYPE_INTEGER, 'map' => [1 => 'v1','v2','v3'] ], 'policy' => ['tag' => ASN1::TYPE_OBJECT_IDENTIFIER, 'optional' => true ], 'messageImprint' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'hashAlgorithm' => Common::AlgorithmIdentifier(), 'hashedMessage' => [ 'tag' => ASN1::TYPE_OCTET_STRING //'optional' => true // non-optional ] ] ], 'serialNumber' => ['tag' => ASN1::TYPE_INTEGER, 'base' => 16, 'optional' => true ], // non-optional 'genTime' => ['tag' => ASN1::TYPE_GENERALIZED_TIME], // GeneralizedTime (non-optional] 'accuracy' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'optional' => true, 'children' => [ 'seconds' => ['tag' => ASN1::TYPE_INTEGER, 'optional' => true ], 'millis' => ['tag' => ASN1::TYPE_INTEGER, 'optional' => true, 'name' => 0, 'implicit' => true ], 'micros' => ['tag' => ASN1::TYPE_INTEGER, 'optional' => true, 'name' => 1, 'implicit' => true ], ] ], 'ordering' => [ 'tag' => ASN1::TYPE_BOOLEAN, 'optional' => true ], 'nonce' => [ 'tag' => ASN1::TYPE_INTEGER, 'optional' => true ], 'tsa' => ['tag' => ASN1::TYPE_ANY_DER, 'optional' => true, 'name' => 0], // [0] GeneralName 'extensions' => ['tag' => ASN1::TYPE_ANY, 'optional' => true, 'name' => 1] // [0] GeneralName ] ]; } } <file_sep><?php namespace vakata\asn1; class ASN1Exception extends \Exception { } <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; use \vakata\asn1\Encoder; class OCSPRequest extends Structure { public static function generate( string $algorithm, string $issuerNameHash, string $issuerKeyHash, string $serialNumber ) { $alg = ASN1::TextToOID(strtolower($algorithm)); if ($alg === strtolower($algorithm)) { $alg = ASN1::TextToOID('md5'); } $src = [ 'tbsRequest' => [ 'requestList' => [ [ 'reqCert' => [ 'hashAlgorithm' => [ 'algorithm' => $alg ], 'issuerNameHash' => $issuerNameHash, 'issuerKeyHash' => $issuerKeyHash, 'serialNumber' => $serialNumber, ] ] ] ] ]; return Encoder::encode($src, static::map()); } public static function map() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'tbsRequest' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => [ 'tag' => ASN1::TYPE_INTEGER, 'name' => 0, 'implicit' => false, 'map' => [1=>'v1'], 'optional' => true ], 'requestorName' => [ 'tag' => ASN1::TYPE_GENERAL_STRING, 'optional' => true, 'name' => 1, 'implicit' => false, ], 'requestList' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'repeat' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'reqCert' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'hashAlgorithm' => Common::AlgorithmIdentifier(), 'issuerNameHash' => [ 'tag' => ASN1::TYPE_OCTET_STRING, ], 'issuerKeyHash' => [ 'tag' => ASN1::TYPE_OCTET_STRING, ], 'serialNumber' => [ 'tag' => ASN1::TYPE_INTEGER, 'base' => 16 ], ] ], 'extensions' => Common::extensions() + [ 'name' => 0, 'implicit' => false, 'optional' => true ] ] ] ], 'extensions' => Common::extensions() + ['name' => 2, 'implicit' => false, 'optional' => true ] ] ], 'signature' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'name' => 0, 'implicit' => false, 'optional' => true, 'children' => [ 'signatureAlgorithm' => Common::AlgorithmIdentifier(), 'signature' => [ 'tag' => ASN1::TYPE_BIT_STRING, ], 'certs' => [ 'tag' => ASN1::TYPE_ANY, 'name' => 0, 'implicit' => false, 'optional' => true ] ] ] ] ]; } } <file_sep><?php /* Based on PHPSECLIB: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/File/ASN1.php */ namespace vakata\asn1; /** * A class handling ASN1 decoding. */ class LazyDecoder extends Decoder { public function lazyDecodeHeader(array $header) { $this->reader->seek($header['content_start']); if ($header['class'] !== ASN1::CLASS_UNIVERSAL && $header['constructed']) { $header['children'] = $this->lazyParse( null, $header['length'] ? $header['start'] + $header['length'] - 1 : null, 'header' ); } elseif ($header['class'] === ASN1::CLASS_UNIVERSAL && in_array($header['tag'], [ASN1::TYPE_SET, ASN1::TYPE_SEQUENCE]) ) { $header['children'] = $this->lazyParse( null, $header['length'] ? $header['start'] + $header['length'] - 1 : null, 'header' ); } else { $header['value'] = $this->decode($header); } return $header; } public function lazyDecodeValue(array $header) { $this->reader->seek($header['content_start']); if ($header['class'] !== ASN1::CLASS_UNIVERSAL && $header['constructed']) { return $this->lazyParse( null, $header['length'] ? $header['start'] + $header['length'] - 1 : null, 'value' ); } if ($header['class'] === ASN1::CLASS_UNIVERSAL && in_array($header['tag'], [ASN1::TYPE_SET, ASN1::TYPE_SEQUENCE]) ) { return $this->lazyParse( null, $header['length'] ? $header['start'] + $header['length'] - 1 : null, 'value' ); } return $this->decode($header); } public function lazyParse($start = null, $max = null, string $mode = 'header') { if ($start !== null) { $this->reader->seek($start); } $skeleton = []; while (!$this->reader->eof() && ($max === null || $this->reader->pos() < $max)) { $header = $this->header(); if ($header['class'] === 0 && $header['tag'] === 0) { if ($max === null) { break; } else { continue; } } if ($header['length'] === null) { $this->reader->readUntil(chr(0).chr(0)); $header['length'] = $this->reader->pos() - $header['start']; $header['content_length'] = $this->reader->pos() - $header['content_start']; } else { if ($header['content_length'] > 0) { $this->reader->bytes($header['content_length']); } } $skeleton[] = $header; } switch ($mode) { case 'value': return new LazyArray($skeleton, function ($v) { return $this->lazyDecodeValue($v); }); case 'header': default: return new LazyArray($skeleton, function ($v) { return $this->lazyDecodeHeader($v); }); } } public function structure($max = null) { return $this->lazyParse(0, null, 'header'); } public function values($skeleton = null) { return $this->lazyParse(0, null, 'value'); } public function map($map, $skeleton = null) { $null = null; if ($skeleton === null && $this->reader->pos() !== 0) { $this->reader->rewind(); } $skeleton = $skeleton ?? $this->structure()[0] ?? null; if (!isset($skeleton)) { throw new ASN1Exception('No decoded data for map'); } if ($skeleton['class'] !== ASN1::CLASS_UNIVERSAL) { if ($map['tag'] === ASN1::TYPE_CHOICE) { foreach ($map['children'] as $child) { if (isset($child['name']) && (int)$skeleton['tag'] === (int)$child['name']) { $map = $child; if (isset($child['value']) && $child['value']) { return $child['value']; } break; } } } } if ($skeleton['class'] !== ASN1::CLASS_UNIVERSAL) { if (isset($map['implicit']) && $map['implicit']) { $skeleton['class'] = ASN1::CLASS_UNIVERSAL; $skeleton['tag'] = $map['tag']; } else { $skeleton = $skeleton['children'][0] ?? null; } } if ($map['tag'] === ASN1::TYPE_CHOICE) { foreach ($map['children'] as $child) { if ($skeleton['tag'] === $child['tag']) { $map = $child; if (isset($child['value']) && $child['value']) { return $child['value']; } break; } } } if (in_array($map['tag'], [ASN1::TYPE_SEQUENCE, ASN1::TYPE_SET]) && in_array($skeleton['tag'], [ASN1::TYPE_SEQUENCE, ASN1::TYPE_SET])) { $map['tag'] = $skeleton['tag']; } if ($map['tag'] === ASN1::TYPE_ANY && isset($skeleton['tag'])) { $map['tag'] = $skeleton['tag']; } if (!in_array($map['tag'], [ASN1::TYPE_ANY, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_ANY_DER]) && $map['tag'] !== $skeleton['tag'] ) { if (!isset($map['optional']) || !$map['optional']) { throw new ASN1Exception('Decoded data does not match mapping - ' . $skeleton['tag']); } return $null; } else { switch ($map['tag']) { case ASN1::TYPE_ANY_DER: $temp = $this->reader->chunk($skeleton['start'], $skeleton['length']); return $temp; case ASN1::TYPE_ANY_SKIP: return $null; case ASN1::TYPE_ANY_RAW: return $skeleton['value'] ?? null; case ASN1::TYPE_SET: if (isset($map['repeat'])) { $mapRepeat = $map['repeat']; $temp = $skeleton['children']->rawData(); return new LazyArray($temp, function ($v) use ($mapRepeat) { return $this->map($mapRepeat, $this->lazyDecodeHeader($v)); }); } else { if (!isset($map['children'])) { return $null; } $temp = $skeleton['children']; $result = []; // named first foreach ($map['children'] as $k => $v) { if (isset($v['name'])) { $result[$k] = null; foreach ($temp as $kk => $vv) { if ($vv['class'] !== ASN1::CLASS_UNIVERSAL && (int)$v['name'] === $vv['tag']) { try { if (isset($v['implicit']) && $v['implicit']) { $vv['class'] = ASN1::CLASS_UNIVERSAL; $vv['tag'] = $map['tag']; } else { $vv = $vv['children'][0] ?? null; } $result[$k] = $this->map($v, $vv); $vv['map'] = $v; $result[$k] = $vv; unset($temp[$kk]); break; } catch (ASN1Exception $e) { // continue trying other children in case of failure } } } if ($result[$k] === null && (!isset($v['optional']) || !$v['optional'])) { throw new ASN1Exception('Missing tagged type - ' . $k); } } } foreach ($map['children'] as $k => $v) { if (isset($v['name'])) { continue; } $result[$k] = null; foreach ($temp as $kk => $vv) { if ($v['tag'] === $vv['tag'] || in_array( $v['tag'], [ ASN1::TYPE_ANY, ASN1::TYPE_ANY_DER, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_CHOICE ] ) ) { try { $result[$k] = $this->map($v, $vv); $vv['map'] = $v; $result[$k] = $vv; unset($temp[$kk]); break; } catch (ASN1Exception $e) { $result[$k] = null; } } } if ($result[$k] === null && (!isset($v['optional']) || !$v['optional'])) { throw new ASN1Exception('Decoded data does not match mapping - ' . $k); } } return new LazyArray($result, function ($v) { return $v === null ? null : $this->map($v['map'], $this->lazyDecodeHeader($v)); }); } break; case ASN1::TYPE_SEQUENCE: if (isset($map['repeat'])) { $mapRepeat = $map['repeat']; $temp = $skeleton['children']->rawData(); return new LazyArray($temp, function ($v) use ($mapRepeat) { return $this->map($mapRepeat, $this->lazyDecodeHeader($v)); }); } else { if (!isset($map['children'])) { return $null; } $result = []; foreach ($skeleton['children'] as $vv) { foreach ($map['children'] as $k => $v) { if (isset($v['name']) && $vv['class'] !== ASN1::CLASS_UNIVERSAL && (int)$v['name'] === $vv['tag'] ) { if (isset($v['implicit']) && $v['implicit']) { $vv['class'] = ASN1::CLASS_UNIVERSAL; $vv['tag'] = $map['tag']; } else { $vv = $vv['children'][0] ?? null; } $vv['map'] = $v; $result[$k] = $vv; unset($map['children'][$k]); break; } if (!isset($v['name']) && ( $v['tag'] === $vv['tag'] || in_array( $v['tag'], [ ASN1::TYPE_ANY, ASN1::TYPE_ANY_DER, ASN1::TYPE_ANY_RAW, ASN1::TYPE_ANY_SKIP, ASN1::TYPE_CHOICE ] ) ) ) { try { $temp = $this->map($v, $vv); $vv['map'] = $v; $result[$k] = $vv; unset($map['children'][$k]); break; } catch (ASN1Exception $e) { // continue trying other children in case of failure } } if (!isset($v['optional']) || !$v['optional']) { throw new ASN1Exception('Missing type - ' . $k); } else { $result[$k] = null; unset($map['children'][$k]); } } } return new LazyArray($result, function ($v) { return $v === null ? null : $this->map($v['map'], $this->lazyDecodeHeader($v)); }); } break; case ASN1::TYPE_OBJECT_IDENTIFIER: $temp = isset($map['resolve']) && $map['resolve'] ? ASN1::OIDtoText($skeleton['value']) : $skeleton['value']; return $temp; case ASN1::TYPE_OCTET_STRING: if (isset($map['der']) && $map['der']) { $temp = static::fromString($skeleton['value']); $temp = isset($map['map']) ? $temp->map($map['map']) : $temp->values(); return $temp; } else { $temp = isset($map['raw']) && $map['raw'] ? $skeleton['value'] : base64_encode($skeleton['value']); return $temp; } break; case ASN1::TYPE_INTEGER: $base = isset($map['base']) && (int)$map['base'] ? (int)$map['base'] : 10; if ($base < 3) { $result = $skeleton['value']; } else { if (strlen($skeleton['value']) > 53 && $base === 16) { $hex = ''; for ($i = strlen($skeleton['value']) - 4; $i >= 0; $i-=4) { $hex .= dechex((int)bindec(substr($skeleton['value'], $i, 4))); } $result = strrev($hex); } else { $temp = base_convert($skeleton['value'], 2, $base); if ($base === 10) { $temp = (int)$temp; } $result = $temp; } } if (isset($map['map']) && isset($map['map'][$result])) { $result = $map['map'][$result]; } return $result; case ASN1::TYPE_UTC_TIME: case ASN1::TYPE_GENERALIZED_TIME: return $skeleton['value']; default: $result = $skeleton['value']; if (isset($map['map']) && isset($map['map'][$result])) { $result = $map['map'][$result]; } return $result; } } } } <file_sep><?php namespace vakata\asn1; class Reader { protected $stream = null; public function __construct($stream) { $this->stream = $stream; } public static function fromString($data) { $stream = fopen('php://temp', 'r+'); if ($stream !== false) { fwrite($stream, $data); rewind($stream); return new static($stream); } throw new ASN1Exception('Could not create temp stream'); } public static function fromFile($path) { return new static(fopen($path, 'r+')); } public function pos() { return ftell($this->stream); } public function byte() { return $this->bytes(1); } public function bytes($amount = null) { if ($amount === null) { $buff = ''; while (!feof($this->stream)) { $buff .= fread($this->stream, 4096); } return $buff; } return fread($this->stream, $amount); } public function readUntil($val, $include = true) { $tmp = ''; while (!feof($this->stream)) { $tmp .= $this->byte(); if (substr($tmp, strlen($val) * -1) === $val) { break; } } return $include ? $tmp : substr($tmp, 0, strlen($val) * -1); } public function chunk($beg = 0, $length = null) { return $this->seek($beg)->bytes($length); } public function eof() { return feof($this->stream); } public function seek($pos) { fseek($this->stream, $pos); return $this; } public function rewind() { rewind($this->stream); return $this; } } <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; use \vakata\asn1\ASN1Exception; use \vakata\asn1\Encoder; class TimestampRequest extends Structure { /** * Generate a timestamp request (tsq) for a file path * @param string $path the path to the file to be timestamped * @param boolean|string $nonce should a nonce be used - defaults to true, could be a value to use as nonce * @param boolean $requireCert should a certificate be returned in the response, defaults to false * @param string $alg the algorithm to use, defaults to 'sha1' * @param string|null $policy the policy to use, defaults to null * @return string the raw timestamp request * @codeCoverageIgnore */ public static function generateFromFile($path, $nonce = true, $requireCert = false, $alg = 'sha1', $policy = null) { return static::generateFromData(file_get_contents($path), $nonce, $requireCert, $alg, $policy); } /** * Generate a timestamp request (tsq) for a string * @param string $data the data to be timestamped * @param boolean|string $nonce should a nonce be used - defaults to true, could be a value to use as nonce * @param boolean $requireCert should a certificate be returned in the response, defaults to false * @param string $alg the algorithm to use, defaults to 'sha1' * @param string|null $policy the policy to use, defaults to null * @return string the raw timestamp request */ public static function generateFromData($data, $nonce = true, $requireCert = false, $alg = 'sha1', $policy = null) { if (!in_array($alg, ['sha1', 'sha256', 'sha384', 'sha512', 'md5'])) { throw new ASN1Exception('Unsupported hash algorithm'); } $hash = hash($alg, $data, true); if ($nonce === true) { $nonce = rand(1, PHP_INT_MAX); } if (!$nonce) { $nonce = null; } $src = [ 'version' => 'v1', 'reqPolicy' => $policy, 'messageImprint' => [ 'hashAlgorithm' => [ "algorithm" => $alg, 'parameters' => null ], 'hashedMessage' => base64_encode($hash), ], 'nonce' => $nonce, 'certReq' => $requireCert ]; return Encoder::encode($src, static::map()); } /** * Generate a timestamp request (tsq) for a given hash * @param string $data the hash to be timestamped (raw binary) * @param boolean|string $nonce should a nonce be used - defaults to true, could be a value to use as nonce * @param boolean $requireCert should a certificate be returned in the response, defaults to false * @param string $alg the algorithm to use, defaults to 'sha1' * @param string|null $policy the policy to use, defaults to null * @return string the raw timestamp request */ public static function generateFromHash($data, $nonce = true, $requireCert = false, $alg = 'sha1', $policy = null) { if (!in_array($alg, ['sha1', 'sha256', 'sha384', 'sha512', 'md5'])) { throw new ASN1Exception('Unsupported hash algorithm'); } if ($nonce === true) { $nonce = rand(1, PHP_INT_MAX); } if (!$nonce) { $nonce = null; } $src = [ 'version' => 'v1', 'reqPolicy' => $policy, 'messageImprint' => [ 'hashAlgorithm' => [ "algorithm" => $alg, 'parameters' => null ], 'hashedMessage' => base64_encode($data), ], 'nonce' => $nonce, 'certReq' => $requireCert ]; return Encoder::encode($src, static::map()); } public static function map() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => [ 'tag' => ASN1::TYPE_INTEGER, 'map' => [1=>'v1','v2','v3'] ], 'reqPolicy' => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER, 'optional' => true, ], 'messageImprint' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'hashAlgorithm' => Common::AlgorithmIdentifier(), 'hashedMessage' => [ 'tag' => ASN1::TYPE_OCTET_STRING ] ] ], 'nonce' => [ 'tag' => ASN1::TYPE_INTEGER, 'optional' => true ], 'certReq' => [ 'tag' => ASN1::TYPE_BOOLEAN, 'optional' => true ] ] ]; } } <file_sep><?php namespace vakata\asn1; class LazyArray implements \ArrayAccess, \Iterator, \Countable { protected $data; protected $processor; public function __construct(array &$data = [], callable $processor = null) { $this->data = $data; $this->processor = $processor ?? function ($v) { return $v; }; } public function __get($k) { return $this[$k] ?? null; } public function offsetExists($offset): bool { return isset($this->data[$offset]); } public function offsetGet($offset): mixed { return call_user_func($this->processor, $this->data[$offset]); } public function offsetSet($offset, $value) : void { throw new \Exception('Not supported'); } public function offsetUnset($offset) : void { throw new \Exception('Not supported'); } public function current(): mixed { return call_user_func($this->processor, current($this->data)); } public function key(): mixed { return key($this->data); } public function next(): void { next($this->data); } public function rewind(): void { reset($this->data); } public function valid(): bool { return key($this->data) !== null; } public function count(): int { return count($this->data); } public function toArray(): array { return iterator_to_array($this); } public function rawData() { return $this->data; } }<file_sep><?php /* Based on PHPSECLIB: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/File/ASN1.php */ namespace vakata\asn1; use DateTime; /** * A class handling ASN1 encoding. */ class Encoder { /** * Encode some data to DER using a mapping array. * @param mixed $source the data to convert * @param array $mapping rules to convert by (check the example on https://github.com/vakata/asn1) * @return mixed raw DER output (base64_encode if needed), false on failure */ public static function encode($source, $mapping) { if (isset($mapping['default']) && $source === $mapping['default']) { return ''; } $tag = $mapping['tag']; if (isset($mapping['raw']) && $mapping['raw']) { $value = $source ?? ''; } else { switch ($tag) { case ASN1::TYPE_SET: case ASN1::TYPE_SEQUENCE: $tag |= 0x20; // set the constructed bit $value = ''; if (isset($mapping['min']) && isset($mapping['max'])) { $child = $mapping['children']; foreach ($source as $content) { $temp = static::encode($content, $child); if ($temp === false) { return false; } $value .= $temp; } break; } if (isset($mapping['repeat'])) { foreach ($source as $content) { $temp = static::encode($content, $mapping['repeat']); if ($temp === false) { return false; } $value .= $temp; } } else { foreach ($mapping['children'] as $key => $child) { if (!array_key_exists($key, $source)) { if (!isset($child['optional'])) { return false; } continue; } $temp = static::encode($source[$key], $child); if ($temp === false) { return false; } if ($temp === '') { continue; } $value .= $temp; } } break; case ASN1::TYPE_CHOICE: $temp = false; foreach ($mapping['children'] as $key => $child) { if (!isset($source[$key])) { continue; } $temp = static::encode($source[$key], $child); if ($temp === false) { return false; } if ($temp === '') { continue; } } return $temp; case ASN1::TYPE_INTEGER: case ASN1::TYPE_ENUMERATED: if (!isset($mapping['map']) && isset($mapping['base']) && $mapping['base'] === 16) { if (strlen($source) % 2 == 1) { $source = '0' . $source; } $value = hex2bin($source); } else { if (!isset($mapping['map'])) { $value = ASN1::toBase256($source, isset($mapping['base']) ? $mapping['base'] : 10); } else { $value = array_search($source, $mapping['map']); if ($value === false) { return false; } $value = ASN1::toBase256($value, isset($mapping['base']) ? (int)$mapping['base'] : 10); } } if (!strlen($value)) { $value = chr(0); } break; case ASN1::TYPE_UTC_TIME: case ASN1::TYPE_GENERALIZED_TIME: $format = $mapping['tag'] == ASN1::TYPE_UTC_TIME ? 'y' : 'Y'; $format.= 'mdHis'; $value = @gmdate($format, strtotime($source)) . 'Z'; break; case ASN1::TYPE_BIT_STRING: if (isset($mapping['map'])) { $mcnt = count($mapping['map']); $bits = array_fill(0, $mcnt, 0); $size = 0; for ($i = 0; $i < $mcnt; $i++) { if (in_array($mapping['map'][$i], $source)) { $bits[$i] = 1; $size = $i; } } if (isset($mapping['min']) && $mapping['min'] >= 1 && $size < $mapping['min']) { $size = $mapping['min'] - 1; } $offset = 8 - (($size + 1) & 7); $offset = $offset !== 8 ? $offset : 0; $value = chr($offset); for ($i = $size + 1; $i < $mcnt; $i++) { unset($bits[$i]); } $bits = implode('', array_pad($bits, $size + $offset + 1, 0)); $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' '))); foreach ($bytes as $byte) { $value.= chr((int)bindec($byte)); } break; } // default to octet string if no mapping is present case ASN1::TYPE_OCTET_STRING: $value = base64_decode($source); break; case ASN1::TYPE_OBJECT_IDENTIFIER: if (!isset($source) && $mapping['optional']) { return; } $oid = preg_match('(^(\d+\.?)+$)', $source) ? $source : ASN1::TextToOID($source); if (!preg_match('(^(\d+\.?)+$)', $oid)) { throw new ASN1Exception('Invalid OID'); } $parts = explode('.', $oid); $value = chr(40 * $parts[0] + $parts[1]); $pcnt = count($parts); for ($i = 2; $i < $pcnt; $i++) { $temp = ''; if (!$parts[$i]) { $temp = "\0"; } else { while ($parts[$i]) { $temp = chr(0x80 | ($parts[$i] & 0x7F)) . $temp; $parts[$i] >>= 7; } $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F); } $value.= $temp; } break; case ASN1::TYPE_ANY: switch (true) { case !isset($source): return static::encode(null, array('tag' => ASN1::TYPE_NULL) + $mapping); case is_int($source): return static::encode($source, array('tag' => ASN1::TYPE_INTEGER) + $mapping); case is_float($source): return static::encode($source, array('tag' => ASN1::TYPE_REAL) + $mapping); case is_bool($source): return static::encode($source, array('tag' => ASN1::TYPE_BOOLEAN) + $mapping); case is_string($source) && preg_match('(^(\d+\.?)+$)', $source): return static::encode($source, array('tag' => ASN1::TYPE_OBJECT_IDENTIFIER) + $mapping); default: throw new ASN1Exception('Unrecognized type'); } break; case ASN1::TYPE_NULL: $value = ''; break; case ASN1::TYPE_NUMERIC_STRING: case ASN1::TYPE_TELETEX_STRING: case ASN1::TYPE_PRINTABLE_STRING: case ASN1::TYPE_UNIVERSAL_STRING: case ASN1::TYPE_UTF8_STRING: case ASN1::TYPE_BMP_STRING: case ASN1::TYPE_IA5_STRING: case ASN1::TYPE_VISIBLE_STRING: case ASN1::TYPE_VIDEOTEX_STRING: case ASN1::TYPE_GRAPHIC_STRING: case ASN1::TYPE_GENERAL_STRING: $value = $source; break; case ASN1::TYPE_BOOLEAN: $value = $source ? "\xFF" : "\x00"; break; default: throw new ASN1Exception('Mapping provides no type definition'); } } $length = static::length(strlen($value)); if (isset($mapping['name'])) { if (isset($mapping['implicit']) && $mapping['implicit']) { $tag = ((ASN1::CLASS_CONTEXT_SPECIFIC ?? 2) << 6) | (ord($value[0]) & 0x20) | $mapping['name']; return chr($tag) . $length . $value; } else { $value = chr($tag) . $length . $value; return chr(((ASN1::CLASS_CONTEXT_SPECIFIC ?? 2) << 6) | 0x20 | $mapping['name']) . static::length(strlen($value)) . $value; } } return chr($tag) . $length . $value; } protected static function length($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } } <file_sep><?php namespace vakata\asn1\structures; use \vakata\asn1\ASN1; class Common { public static function AlgorithmIdentifier() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ "algorithm" => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER ], 'parameters' => [ 'tag' => ASN1::TYPE_ANY, 'optional' => true ] ] ]; } public static function RDNSequence() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'repeat' => [ 'tag' => ASN1::TYPE_SET, 'repeat' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'key' => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER ], 'value' => [ 'tag' => ASN1::TYPE_ANY, 'optional' => true ] ] ] ] ]; } public static function extensions() { return [ 'tag' => ASN1::TYPE_SEQUENCE, 'repeat' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'extnID' => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER ], 'critical' => [ 'tag' => ASN1::TYPE_BOOLEAN, 'optional' => true ], 'extnValue' => [ 'tag' => ASN1::TYPE_OCTET_STRING, 'der' => true ] ] ], 'optional' => true ]; } } <file_sep><?php namespace vakata\asn1\test; use vakata\asn1\ASN1; use vakata\asn1\Encoder; use vakata\asn1\Decoder; use vakata\asn1\structures\Certificate; use vakata\asn1\structures\CRL; use vakata\asn1\structures\OCSPRequest; use vakata\asn1\structures\OCSPResponse; use vakata\asn1\structures\P7S; use vakata\asn1\structures\TimestampRequest; use vakata\asn1\structures\TimestampResponse; class ASN1Test extends \PHPUnit\Framework\TestCase { public function testEncodeDecode() { $tsq = [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'version' => [ 'tag' => ASN1::TYPE_INTEGER, 'map' => [1=>'v1','v2','v3'] ], 'messageImprint' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ 'hashAlgorithm' => [ 'tag' => ASN1::TYPE_SEQUENCE, 'children' => [ "algorithm" => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER, 'resolve' => true ], 'parameters' => [ 'tag' => ASN1::TYPE_ANY, 'optional' => true ] ] ], 'hashedMessage' => [ 'tag' => ASN1::TYPE_OCTET_STRING ] ] ], 'reqPolicy' => [ 'tag' => ASN1::TYPE_OBJECT_IDENTIFIER, 'optional' => true ], 'certReq' => [ 'tag' => ASN1::TYPE_BOOLEAN, 'optional' => true ], 'nonce' => [ 'tag' => ASN1::TYPE_INTEGER, 'optional' => true ] ] ]; $src = array( 'version' => 'v1', 'messageImprint' => array ( 'hashAlgorithm' => array("algorithm" => 'sha1', 'parameters' => null), 'hashedMessage' => base64_encode(sha1("asdf", true)), ), 'reqPolicy' => null, 'certReq' => true, 'nonce' => rand(0, PHP_INT_MAX) ); $res = Encoder::encode($src, $tsq); $res = Decoder::fromString($res)->map($tsq); $this->assertEquals($src, $res); } public function testCertificate() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/certificate.crt.dump')), str_replace("\r", "", (string)Certificate::fromFile(__DIR__ . '/samples/certificate.crt')) ); } public function testCRL() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/revocation.crl.dump')), str_replace("\r", "", (string)CRL::fromFile(__DIR__ . '/samples/revocation.crl')) ); } public function testOCSPRequest() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/ocsp.req.dump')), str_replace("\r", "", (string)OCSPRequest::fromFile(__DIR__ . '/samples/ocsp.req')) ); } public function testOCSPResponse() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/ocsp.res.dump')), str_replace("\r", "", (string)OCSPResponse::fromFile(__DIR__ . '/samples/ocsp.res')) ); } public function testP7S() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/signed.p7s.dump')), str_replace("\r", "", (string)P7S::fromFile(__DIR__ . '/samples/signed.p7s')) ); } public function testTimestampRequest() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/timestamp.tsq.dump')), str_replace("\r", "", (string)TimestampRequest::fromFile(__DIR__ . '/samples/timestamp.tsq')) ); } public function testTimestampResponse() { $this->assertEquals( str_replace("\r", "", file_get_contents(__DIR__ . '/samples/timestamp.tsr.dump')), str_replace("\r", "", (string)TimestampResponse::fromFile(__DIR__ . '/samples/timestamp.tsr')) ); } } <file_sep># asn1 [![Latest Version on Packagist][ico-version]][link-packagist] [![Software License][ico-license]](LICENSE.md) [![Build Status][ico-travis]][link-travis] [![Scrutinizer Code Quality][ico-code-quality]][link-scrutinizer] [![Code Coverage][ico-scrutinizer]][link-scrutinizer] Am ASN1 encoder / decoder. ## Install Via Composer ``` bash $ composer require vakata/asn1 ``` ## Usage The main part of the library are the `Decoder` and `Encoder` classes. ```php // first create an instance (there is a fromFile static method as well) $decoded = \vakata\asn1\Decoder::fromString("...ASN1 data here ..."); // you can then inspect the parsed raw data $decoded->structure(); // more info $decoded->values(); // just values // or map the data to an existing map $decoded->map($mapArray); // the encoder on the otherhand needs some data and a map \vakata\asn1\Encoder::encode($dataArray, $mapArray); ``` There are helper classes in the `structures` namespace - these help with working with common known structures. All the structures have `fromString` and `fromFile` static constructor methods, and a `toArray` method. ``` php // Timestamp example: \vakata\asn1\structures\TimestampRequest::fromString($tsq)->toArray(); \vakata\asn1\structures\TimestampResponse::fromFile('/path/to/timestamp/response')->toArray(); \vakata\asn1\structures\TimestampRequest::generateFromFile('/path/to/file/to/timestamp'); // You can also work with Certificate, CRL, OCSPRequest, OCSPResponse, P7S ``` Read more in the [API docs](api.md) ## Testing ``` bash $ composer test ``` ## Contributing Please see [CONTRIBUTING](CONTRIBUTING.md) for details. ## Security If you discover any security related issues, please email <EMAIL> instead of using the issue tracker. ## Credits - [vakata][link-author] - [All Contributors][link-contributors] ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. [ico-version]: https://img.shields.io/packagist/v/vakata/asn1.svg?style=flat-square [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square [ico-travis]: https://img.shields.io/travis/vakata/asn1/master.svg?style=flat-square [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/vakata/asn1.svg?style=flat-square [ico-code-quality]: https://img.shields.io/scrutinizer/g/vakata/asn1.svg?style=flat-square [ico-downloads]: https://img.shields.io/packagist/dt/vakata/asn1.svg?style=flat-square [ico-cc]: https://img.shields.io/codeclimate/github/vakata/asn1.svg?style=flat-square [ico-cc-coverage]: https://img.shields.io/codeclimate/coverage/github/vakata/asn1.svg?style=flat-square [link-packagist]: https://packagist.org/packages/vakata/asn1 [link-travis]: https://travis-ci.org/vakata/asn1 [link-scrutinizer]: https://scrutinizer-ci.com/g/vakata/asn1 [link-code-quality]: https://scrutinizer-ci.com/g/vakata/asn1 [link-downloads]: https://packagist.org/packages/vakata/asn1 [link-author]: https://github.com/vakata [link-contributors]: ../../contributors [link-cc]: https://codeclimate.com/github/vakata/asn1 <file_sep><?php namespace vakata\asn1; class ASN1 { const CLASS_UNIVERSAL = 0; const CLASS_APPLICATION = 1; const CLASS_CONTEXT_SPECIFIC = 2; const CLASS_PRIVATE = 3; const TYPE_BOOLEAN = 1; const TYPE_INTEGER = 2; const TYPE_BIT_STRING = 3; const TYPE_OCTET_STRING = 4; const TYPE_NULL = 5; const TYPE_OBJECT_IDENTIFIER = 6; const TYPE_OBJECT_DESCRIPTOR = 7; const TYPE_INSTANCE_OF = 8; // EXTERNAL const TYPE_REAL = 9; const TYPE_ENUMERATED = 10; const TYPE_EMBEDDED = 11; const TYPE_UTF8_STRING = 12; const TYPE_RELATIVE_OID = 13; const TYPE_SEQUENCE = 16; // SEQUENCE OF const TYPE_SET = 17; // SET OF const TYPE_NUMERIC_STRING = 18; const TYPE_PRINTABLE_STRING = 19; const TYPE_TELETEX_STRING = 20; // T61String const TYPE_VIDEOTEX_STRING = 21; const TYPE_IA5_STRING = 22; const TYPE_UTC_TIME = 23; const TYPE_GENERALIZED_TIME = 24; const TYPE_GRAPHIC_STRING = 25; const TYPE_VISIBLE_STRING = 26; // ISO646String const TYPE_GENERAL_STRING = 27; const TYPE_UNIVERSAL_STRING = 28; const TYPE_CHARACTER_STRING = 29; const TYPE_BMP_STRING = 30; const TYPE_CHOICE = -1; const TYPE_ANY = -2; const TYPE_ANY_RAW = -3; const TYPE_ANY_SKIP = -4; const TYPE_ANY_DER = -5; /** * Convert a number to base256 * @param integer|string $number the number to convert * @param integer $base the current base of the number (optional, defaults to 10) * @return string the number in base256 */ public static function toBase256($number, $base = 10) { $bin = base_convert($number, $base, 2); $res = ""; $len = (int)ceil(strlen($bin) / 8) * 8; $bin = str_pad($bin, $len, "0", STR_PAD_LEFT); for ($i = ($len-8); $i >= 0; $i -= 8) { $res = chr((int)base_convert(substr($bin, $i, 8), 2, 10)) . $res; } return $res; } /** * Convert a number from base256 * @param string $string the number to convert * @return integer|string the converted number */ public static function fromBase256($string) { $number = ""; for ($i = 0; $i < strlen($string); $i++) { $number .= str_pad(base_convert(ord($string[$i]), 10, 2), 8, "0", STR_PAD_LEFT); } return $number; } public static $oids = [ 'sha1' => '1.3.14.3.2.26', 'sha256' => '2.16.840.1.101.3.4.2.1', 'sha384' => '2.16.840.1.101.3.4.2.2', 'sha512' => '2.16.840.1.101.3.4.2.3', 'sha224' => '2.16.840.1.101.3.4.2.4', 'md5' => '1.2.840.113549.2.5', 'md2' => '1.3.14.7.2.2.1', 'ripemd160' => '1.3.36.3.2.1', 'MD4withRSA' => '1.2.840.113549.1.1.3', 'SHA1withECDSA' => '1.2.840.10045.4.1', 'SHA224withECDSA' => '1.2.840.10045.4.3.1', 'SHA256withECDSA' => '1.2.840.10045.4.3.2', 'SHA384withECDSA' => '1.2.840.10045.4.3.3', 'SHA512withECDSA' => '1.2.840.10045.4.3.4', 'dsa' => '1.2.840.10040.4.1', 'SHA1withDSA' => '1.2.840.10040.4.3', 'SHA224withDSA' => '2.16.840.1.101.3.4.3.1', 'SHA256withDSA' => '2.16.840.1.101.3.4.3.2', 'rsaEncryption' => '1.2.840.113549.1.1.1', 'countryName' => '2.5.4.6', 'organization' => '2.5.4.10', 'organizationalUnit' => '2.5.4.11', 'stateOrProvinceName' => '2.5.4.8', 'locality' => '2.5.4.7', 'commonName' => '2.5.4.3', 'subjectKeyIdentifier' => '172.16.17.32', 'keyUsage' => '192.168.3.11', 'subjectAltName' => '172.16.17.32', 'basicConstraints' => '192.168.3.11', 'nameConstraints' => '172.16.17.32', 'cRLDistributionPoints' =>'172.16.17.32', 'certificatePolicies' => '172.16.17.32', 'authorityKeyIdentifier'=>'192.168.127.12', 'policyConstraints' => '192.168.3.11', 'extKeyUsage' => '172.16.31.10', 'authorityInfoAccess' => '1.3.6.1.5.192.168.127.12', 'anyExtendedKeyUsage' => '2.5.29.37.0', 'serverAuth' => '172.16.31.10.5.5.7.3.1', 'clientAuth' => '172.16.31.10.5.5.7.3.2', 'codeSigning' => '1.3.6.1.5.5.7.3.3', 'emailProtection' => '1.3.6.1.5.5.7.3.4', 'timeStamping' => '1.3.6.1.5.5.7.3.8', 'ocspSigning' => '1.3.6.1.5.5.7.3.9', 'ecPublicKey' => '1.2.840.10045.2.1', 'secp256r1' => '1.2.840.10045.3.1.7', 'secp256k1' => '172.16.17.32.10', 'secp384r1' => '172.16.17.32.34', 'pkcs5PBES2' => '1.2.840.113549.1.5.13', 'pkcs5PBKDF2' => '1.2.840.113549.1.5.12', 'des-EDE3-CBC' => '1.2.840.113549.3.7', 'data' => '1.2.840.113549.1.7.1', // CMS data 'signed-data' => '1.2.840.113549.1.7.2', // CMS signed-data 'enveloped-data' => '1.2.840.113549.1.7.3', // CMS enveloped-data 'digested-data' => '1.2.840.113549.1.7.5', // CMS digested-data 'encrypted-data' => '1.2.840.113549.1.7.6', // CMS encrypted-data 'authenticated-data' => '1.2.840.113549.172.16.58.3.2', // CMS authenticated-data 'tstinfo' => '1.2.840.113549.172.16.58.3.4', // RFC3161 TSTInfo, 'pkix' => '1.3.6.1.5.5.7', 'pe' => '1.3.6.1.5.5.7.1', 'qt' => '1.3.6.1.5.5.7.2', 'kp' => '1.3.6.1.5.5.7.3', 'ad' => '1.3.6.1.5.5.7.48', 'cps' => '1.3.6.1.5.5.7.2.1', 'unotice' => '1.3.6.1.5.5.7.2.2', 'ocsp' =>'1.3.6.1.5.172.16.58.3', 'caIssuers' => '1.3.6.1.5.192.168.127.12', 'timeStamping' => '1.3.6.1.5.5.7.48.3', 'caRepository' => '1.3.6.1.5.5.7.48.5', 'at' => '2.5.4', 'name' => '2.5.4.41', 'surname' => '2.5.4.4', 'givenName' => '2.5.4.42', 'initials' => '2.5.4.43', 'generationQualifier' => '2.5.4.44', 'commonName' => '2.5.4.3', 'localityName' => '2.5.4.7', 'stateOrProvinceName' => '2.5.4.8', 'organizationName' => '2.5.4.10', 'organizationalUnitName' => '2.5.4.11', 'title' => '2.5.4.12', 'description' => '2.5.4.13', 'dnQualifier' => '2.5.4.46', 'countryName' => '2.5.4.6', 'serialNumber' => '2.5.4.5', 'pseudonym' => '2.5.4.65', 'postalCode' => '2.5.4.17', 'streetAddress' => '2.5.4.9', 'uniqueIdentifier' => '2.5.4.45', 'role' => '2.5.4.72', 'postalAddress' => '2.5.4.16', 'domainComponent' => '0.9.2342.19200300.100.1.25', 'pkcs-9' => '1.2.840.113549.1.9', 'emailAddress' => '1.2.840.113549.1.9.1', 'ce' => '2.5.29', 'authorityKeyIdentifier' => '192.168.127.12', 'subjectKeyIdentifier' => '172.16.17.32', 'keyUsage' => '192.168.3.11', 'privateKeyUsagePeriod' => '192.168.3.11', 'certificatePolicies' => '172.16.17.32', 'anyPolicy' => '2.5.29.32.0', 'policyMappings' => '172.16.17.32', 'subjectAltName' => '172.16.17.32', 'issuerAltName' => '172.16.58.3', 'subjectDirectoryAttributes' => '172.16.58.3', 'basicConstraints' => '192.168.3.11', 'nameConstraints' => '172.16.17.32', 'policyConstraints' => '192.168.3.11', 'cRLDistributionPoints' => '172.16.17.32', 'extKeyUsage' => '172.16.31.10', 'anyExtendedKeyUsage' => '2.5.29.37.0', 'kp-serverAuth' => '172.16.31.10.5.5.7.3.1', 'kp-clientAuth' => '172.16.31.10.5.5.7.3.2', 'kp-codeSigning' => '1.3.6.1.5.5.7.3.3', 'kp-emailProtection' => '1.3.6.1.5.5.7.3.4', 'kp-timeStamping' => '1.3.6.1.5.5.7.3.8', 'kp-OCSPSigning' => '1.3.6.1.5.5.7.3.9', 'inhibitAnyPolicy' => '192.168.3.11', 'freshestCRL' => '172.16.58.3', 'pe-authorityInfoAccess' => '1.3.6.1.5.5.7.1.1', 'pe-subjectInfoAccess' => '1.3.6.1.5.5.7.1.11', 'cRLNumber' => '192.168.127.12', 'issuingDistributionPoint' => '172.16.58.3', 'deltaCRLIndicator' => '172.16.58.3', 'cRLReasons' => '172.16.17.32', 'certificateIssuer' => '192.168.3.11', 'holdInstructionCode' => '172.16.58.3', 'holdInstruction' => '1.2.840.10040.2', 'holdinstruction-none' => '1.2.840.10040.2.1', 'holdinstruction-callissuer' => '1.2.840.10040.2.2', 'holdinstruction-reject' => '1.2.840.10040.2.3', 'invalidityDate' => '172.16.58.3', 'md2' => '1.2.840.113549.2.2', 'md5' => '1.2.840.113549.2.5', 'sha1' => '1.3.14.3.2.26', 'dsa' => '1.2.840.10040.4.1', 'dsa-with-sha1' => '1.2.840.10040.4.3', 'pkcs-1' => '1.2.840.113549.1.1', 'rsaEncryption' => '1.2.840.113549.1.1.1', 'md2WithRSAEncryption' => '1.2.840.113549.1.1.2', 'md5WithRSAEncryption' => '1.2.840.113549.1.1.4', 'sha1WithRSAEncryption' => ['1.2.840.113549.1.1.5', '1.3.14.3.2.29'], 'dhpublicnumber' => '1.2.840.10046.2.1', 'keyExchangeAlgorithm' => '2.16.840.1.101.2.1.1.22', 'ansi-X9-62' => '1.2.840.10045', 'ecSigType' => '1.2.840.10045.4', 'ecdsa-with-SHA1' => '1.2.840.10045.4.1', 'fieldType' => '1.2.840.10045.1', 'prime-field' => '1.2.840.10045.1.1', 'characteristic-two-field' => '1.2.840.10045.1.2', 'characteristic-two-basis' => '1.2.840.10045.1.2.3', 'gnBasis' => '1.2.840.10045.1.2.3.1', 'tpBasis' => '1.2.840.10045.1.2.3.2', 'ppBasis' => '1.2.840.10045.1.2.3.3', 'publicKeyType' => '1.2.840.10045.2', 'ecPublicKey' => '1.2.840.10045.2.1', 'ellipticCurve' => '1.2.840.10045.3', 'c-TwoCurve' => '1.2.840.10045.3.0', 'c2pnb163v1' => '1.2.840.10045.3.0.1', 'c2pnb163v2' => '1.2.840.10045.3.0.2', 'c2pnb163v3' => '1.2.840.10045.3.0.3', 'c2pnb176w1' => '1.2.840.10045.3.0.4', 'c2pnb191v1' => '1.2.840.10045.3.0.5', 'c2pnb191v2' => '1.2.840.10045.3.0.6', 'c2pnb191v3' => '1.2.840.10045.3.0.7', 'c2pnb191v4' => '1.2.840.10045.3.0.8', 'c2pnb191v5' => '1.2.840.10045.3.0.9', 'c2pnb208w1' => '1.2.840.10045.3.0.10', 'c2pnb239v1' => '1.2.840.10045.3.0.11', 'c2pnb239v2' => '1.2.840.10045.3.0.12', 'c2pnb239v3' => '1.2.840.10045.3.0.13', 'c2pnb239v4' => '1.2.840.10045.3.0.14', 'c2pnb239v5' => '1.2.840.10045.3.0.15', 'c2pnb272w1' => '1.2.840.10045.3.0.16', 'c2pnb304w1' => '1.2.840.10045.3.0.17', 'c2pnb359v1' => '1.2.840.10045.3.0.18', 'c2pnb368w1' => '1.2.840.10045.3.0.19', 'c2pnb431r1' => '1.2.840.10045.3.0.20', 'primeCurve' => '1.2.840.10045.3.1', 'prime192v1' => '1.2.840.10045.3.1.1', 'prime192v2' => '1.2.840.10045.3.1.2', 'prime192v3' => '1.2.840.10045.3.1.3', 'prime239v1' => '1.2.840.10045.3.1.4', 'prime239v2' => '1.2.840.10045.3.1.5', 'prime239v3' => '1.2.840.10045.3.1.6', 'prime256v1' => '1.2.840.10045.3.1.7', 'RSAES-OAEP' => '1.2.840.113549.1.1.7', 'pSpecified' => '1.2.840.113549.1.1.9', 'RSASSA-PSS' => '1.2.840.113549.1.1.10', 'mgf1' => '1.2.840.113549.1.1.8', 'sha224WithRSAEncryption' => '1.2.840.113549.1.1.14', 'sha256WithRSAEncryption' => '1.2.840.113549.1.1.11', 'sha384WithRSAEncryption' => '1.2.840.113549.1.1.12', 'sha512WithRSAEncryption' => '1.2.840.113549.1.1.13', 'sha224' => '2.16.840.1.101.3.4.2.4', 'sha256' => '2.16.840.1.101.3.4.2.1', 'sha384' => '2.16.840.1.101.3.4.2.2', 'sha512' => '2.16.840.1.101.3.4.2.3', 'GostR3411-94-with-GostR3410-94' => '1.2.643.2.2.4', 'GostR3411-94-with-GostR3410-2001' => '1.2.643.2.2.3', 'GostR3410-2001' => '1.2.643.2.2.20', 'GostR3410-94' => '1.2.643.2.2.19', 'netscape' => '2.16.840.1.113730', 'netscape-cert-extension' => '2.16.840.1.113730.1', 'netscape-cert-type' => '2.16.840.1.113730.1.1', 'netscape-comment' => '2.16.840.1.113730.1.13', 'netscape-ca-policy-url' => '2.16.840.1.113730.1.8', 'logotype' => '1.3.6.1.5.5.7.1.12', 'entrustVersInfo' => '1.2.840.113533.7.65.0', 'verisignPrivate' => '2.16.840.1.113733.1.6.9', 'unstructuredName' => '1.2.840.113549.1.9.2', 'challengePassword' => '<PASSWORD>', 'extensionRequest' => '1.2.840.113549.1.9.14', 'userid' => '0.9.2342.19200300.100.1.1', 's/mime' => '1.2.840.113549.1.9.15', 'unstructuredAddress' => '1.2.840.113549.1.9.8', 'rc2-cbc' => '1.2.840.113549.3.2', 'rc4' => '1.2.840.113549.3.4', 'desCBC' => '1.3.14.3.2.7', 'qcStatements' => '1.3.6.1.5.5.7.1.3', 'pkixQCSyntax-v1' => '1.3.6.1.5.192.168.127.12', 'pkixQCSyntax-v2' => '1.3.6.1.5.172.16.31.10', 'ipsecEndSystem' => '1.3.6.1.5.5.7.3.5', 'ipsecTunnel' => '1.3.6.1.5.5.7.3.6', 'ipsecUser' => '1.3.6.1.5.5.7.3.7', 'OCSP' => '1.3.6.1.5.172.16.58.3', 'countryOfCitizenship' => '1.3.6.1.5.5.7.9.4', 'IPSECProtection' => '1.3.6.1.5.5.8.2.2', 'telephoneNumber' => '172.16.58.3', 'organizationIdentifier' => '2.5.4.97' ]; public static function OIDtoText($id) { foreach (static::$oids as $k => $v) { if (is_array($v) && in_array($id, $v)) { return $k; } if (!is_array($v) && $id === $v) { return $k; } } return $id; } public static function TextToOID($text) { $res = static::$oids[$text] ?? null; if (is_array($res)) { $res = $res[0]; } return $res ?? $text; } }
f456e1d73fc6dc8618b82720e1f856e379c3d98d
[ "Markdown", "PHP" ]
17
PHP
vakata/asn1
a20519811025c1959323502e5021ec9c3e12aa8a
01aaf0efd8dc20f0cf40b393c687ede030c3a9e0
refs/heads/master
<file_sep>#!/bin/bash c++ -I $BOOST_INCLUDE_DIR example.cpp -o example -L$BOOST_LIB_DIR/ -lboost_regex <file_sep>#!/bin/bash c++ -I $BOOST_INCLUDE_DIR main.cpp -o executable -L$BOOST_LIB_DIR/ -lboost_date_time -lboost_system <file_sep>#include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; string make_daytime_string() { time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_service io_service; int port = 9100; cout << "Registering port: " << port << endl; tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port)); for (;;) { tcp::socket socket(io_service); cout << "Waiting for connection..." << endl; acceptor.accept(socket); cout << "Received connection." << endl; string reply_message = make_daytime_string(); boost::system::error_code ignored_error; cout << "Sending response message: " << reply_message << endl; boost::asio::write(socket, boost::asio::buffer(reply_message), ignored_error); cout << endl; } } catch (exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <file_sep>#!/bin/bash GREEN='tput setaf 2' RESET='tput sgr 0' EXECUTABLE_NAME=executable echo "$($GREEN)Building...$($RESET)" c++ -I $BOOST_INCLUDE_DIR main.cpp -o $EXECUTABLE_NAME -L$BOOST_LIB_DIR/ -lboost_date_time -lboost_system -lboost_thread echo "$($GREEN)Running...$($RESET)" ./$EXECUTABLE_NAME abcd echo "$($GREEN)Cleaning...$($RESET)" rm $EXECUTABLE_NAME
639539b271aabd7e1dc582fa49124a737ad946fa
[ "C++", "Shell" ]
4
Shell
lizhieffe/boost-examples
ab5f77efb195e5107e3418254386edbe4a3f1ac2
a55275dd76e0a4161b57da89c3a9dcd2d37805b4
refs/heads/main
<file_sep>function randIntBetween(low, high) { return Math.floor(Math.random() * (high - low + 1)) + low; } function pickRandomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; } export { pickRandomFromArray, randIntBetween }; <file_sep>import React from "react"; const SpriteContainer = ({ width, height, children, scale }) => { const style = { width: `${width * scale}px`, height: `${height * scale}px`, }; return <div style={style}>{children}</div>; }; const Sprite = ({ sheet, row, col, width, height, scale }) => { const style = { background: `url(${sheet}) -${col * width}px -${row * height}px`, imageRendering: "pixelated", width: `${width}px`, height: `${height}px`, transform: `scale(${scale})`, transformOrigin: "top left", }; return <div style={style} />; }; const SpriteSheet = ({ sheet, width, height, tileWidth, tileHeight, scale }) => ({ row, col }) => { return ( <SpriteContainer height={tileHeight} width={tileWidth} scale={scale}> <Sprite height={tileHeight} width={tileWidth} sheet={sheet} row={row} col={col} scale={scale} /> </SpriteContainer> ); }; export default SpriteSheet; <file_sep>import React from "react"; import { getDimensions, mapMatrix } from "functional-game-utils"; const Grid = ({ tiles, renderTile, cellSize }) => { const { height, width } = getDimensions(tiles); const gridStyles = { display: "grid", gridTemplateColumns: `${cellSize} `.repeat(width), gridTemplateRows: `${cellSize} `.repeat(height), }; return <div style={gridStyles}>{mapMatrix(renderTile, tiles)}</div>; }; export default Grid; <file_sep>import React, { Fragment, useEffect, useState } from "react"; import Grid from "./Grid"; import Tile from "./Tile"; import Heart from "./Heart"; import SpriteSheet from "./SpriteSheet"; import sprites from "../../assets/sprites.png"; import { compareLocations, constructArray, constructMatrix, constructMatrixFromTemplate, getCrossDirections, getLocation, getNeighbors, isLocationInBounds, mapMatrix, } from "functional-game-utils"; import { remove, update } from "ramda"; import { pickRandomFromArray, randIntBetween } from "../utils/random"; // use mobx-state-tree to store game state const spriteConfig = { size: 16, scale: 4, }; const createSprite = SpriteSheet({ sheet: sprites, width: 10, height: 10, tileWidth: spriteConfig.size, tileHeight: spriteConfig.size, scale: spriteConfig.scale, }); const isLocationSelected = ({ location, selected }) => selected && selected.some((selectedLocation) => compareLocations(location, selectedLocation) ); const omitKeys = (comparator, obj) => { return Object.entries(obj).reduce((newObj, [key, value]) => { if (comparator(value)) { return newObj; } return { ...newObj, [key]: value, }; }, {}); }; const getRelativeDirection = (locationA, locationB) => { const relativeDirection = { up: false, down: false, left: false, right: false, }; const rowDiff = locationA.row - locationB.row; const colDiff = locationA.col - locationB.col; if (rowDiff < 0) { relativeDirection.up = true; } if (rowDiff > 0) { relativeDirection.down = true; } if (colDiff < 0) { relativeDirection.left = true; } if (colDiff > 0) { relativeDirection.right = true; } return relativeDirection; }; const getSelectedNeighborDirections = ({ tiles, location, selected }) => { const neighbors = getNeighbors(getCrossDirections, tiles, location); const selectedNeighbors = neighbors.filter((neighbor) => selected.some((selectedLocation) => compareLocations(neighbor, selectedLocation) ) ); return selectedNeighbors.reduce( (direction, neighborLocation) => ({ ...direction, ...omitKeys( (key) => key === false, getRelativeDirection(location, neighborLocation) ), }), {} ); }; const createBag = (items) => { let bag = [...items]; // This function will return undefined once // your bag is empty. const pickFromBag = () => { const pickedIndex = randIntBetween(0, bag.length - 1); const pickedItem = bag[pickedIndex]; bag = remove(pickedIndex, 1, bag); return pickedItem; }; return pickFromBag; }; const compareArraysIgnoringOrder = (a, b) => { if (a.length !== b.length) { return false; } const aCopy = [...a].sort(); const bCopy = [...b].sort(); return aCopy.every((aValue, index) => aValue === bCopy[index]); }; const areTilesSettled = (tiles) => { let isAnyTileEmpty = false; // misuse mapMatrix as a pseudo "Array.some" style function mapMatrix((tile) => { if (tile === "") { isAnyTileEmpty = true; } }, tiles); return !isAnyTileEmpty; }; const areAllItemsEqual = (items) => { return items.every((item) => item === items[0]); }; const doItemsMatch = (a, b) => { switch (a) { case "ANY_INGREDIENT": if (b !== "SKULL" && b !== "CLOUD") { return true; } break; default: if (b === a) { return true; } break; } return false; }; const getSelectedRecipe = ({ selected, recipes, tiles }) => { const selectedIngredients = selected.map(getLocation(tiles)); let selectedRecipe = recipes.find((recipe) => { switch (recipe.ingredients.type) { case "MATCHING": if (areAllItemsEqual(selectedIngredients)) { if (doItemsMatch(recipe.ingredients.item, selectedIngredients[0])) { const { min, max = Infinity } = recipe.ingredients; if ( selectedIngredients.length >= min && selectedIngredients.length <= max ) { return true; } } } break; default: break; } return false; }); return selectedRecipe; }; const App = () => { const [tiles, setTiles] = useState([[""]]); const [selected, setSelected] = useState([]); const [isMouseDown, setMouseDown] = useState(false); const [mouseDownLocation, setMouseDownLocation] = useState(); const [levels, setLevels] = useState([]); const [currentLevel, setCurrentLevel] = useState(0); const [prevCurrentLevel, setPrevCurrentLevel] = useState(); const [items, setItems] = useState({ BOTTLE: { sprite: { row: 0, col: 0 }, }, FLOWER_TULIP: { sprite: { row: 0, col: 1 }, }, SKULL: { sprite: { row: 0, col: 2 }, }, SKULL_POWER: { sprite: { row: 0, col: 3 }, }, MUSHROOM_RED: { sprite: { row: 0, col: 4 }, }, MUSHROOM_GREEN: { sprite: { row: 0, col: 5 }, }, ACORN: { sprite: { row: 0, col: 6 }, }, EYE: { sprite: { row: 0, col: 7 }, }, AMETHYST: { sprite: { row: 0, col: 8 }, }, EGG_BLUE: { sprite: { row: 0, col: 9 }, }, LEAF_GREEN: { sprite: { row: 1, col: 0 }, }, FEATHER: { sprite: { row: 1, col: 1 }, }, SPIDER: { sprite: { row: 1, col: 2 }, }, WORM: { sprite: { row: 1, col: 3 }, }, LEAF_MAPLE: { sprite: { row: 1, col: 4 }, }, FLOWER_SUNFLOWER: { sprite: { row: 1, col: 5 }, }, BUTTERFLY: { sprite: { row: 1, col: 6 }, }, FLY: { sprite: { row: 1, col: 7 }, }, EGG_GREEN: { sprite: { row: 1, col: 8 }, }, EGG_RED: { sprite: { row: 1, col: 9 }, }, FAIRY: { sprite: { row: 2, col: 7 }, }, HEART_FULL: { sprite: { row: 3, col: 5 }, }, HEART_HALF: { sprite: { row: 3, col: 6 }, }, HEART_EMPTY: { sprite: { row: 3, col: 7 }, }, CLOUD: { sprite: { row: 2, col: 5 }, }, SHIELD: { sprite: { row: 3, col: 8 }, }, }); const [score, setScore] = useState(0); const [hearts, setHearts] = useState([2, 2, 2, 2]); const [shields, setShields] = useState([0, 0, 0, 0]); const [nextAnimationId, setNextAnimationId] = useState(0); const [animations, setAnimations] = useState([]); useEffect(() => { setLevels([ { target: 300, items: ["ACORN", "LEAF_GREEN", "FEATHER", "MUSHROOM_RED"], recipes: [ { ingredients: { type: "MATCHING", item: "ANY_INGREDIENT", min: 1, max: 1, }, effects: [ { type: "DAMAGE_COLUMN", value: 1, }, ], }, { ingredients: { type: "MATCHING", item: "ANY_INGREDIENT", min: 2, max: 2, }, effects: [], }, { ingredients: { type: "MATCHING", item: "ANY_INGREDIENT", min: 3, max: 3, }, effects: [ { type: "SCORE", }, ], }, { ingredients: { type: "MATCHING", item: "ACORN", min: 4, }, effects: [ { type: "SCORE", }, { type: "BOMB", }, ], }, { ingredients: { type: "MATCHING", item: "LEAF_GREEN", min: 4, }, effects: [ { type: "SCORE", }, { type: "BONUS_POINTS", }, ], }, { ingredients: { type: "MATCHING", item: "FEATHER", min: 4, }, effects: [ { type: "SCORE", }, { type: "CLOUDS", }, ], }, { ingredients: { type: "MATCHING", item: "MUSHROOM_RED", min: 4, }, effects: [ { type: "SCORE", }, { type: "SHIELD_COLUMNS", }, ], }, ], }, ]); }, [setLevels]); useEffect(() => { if (!levels[currentLevel]) { return; } if (currentLevel === prevCurrentLevel) { return; } const initialTiles = constructMatrix( () => pickRandomFromArray(levels[currentLevel].items), { height: 6, width: 4, } ); setPrevCurrentLevel(currentLevel); setTiles(initialTiles); }, [setTiles, levels, currentLevel]); const addSelection = (location) => { if ( !selected.some((selectedLocation) => compareLocations(selectedLocation, location) ) ) { setSelected([...selected, location]); } }; const removeSelection = (location) => { const removedSelectionIndex = selected.findIndex((selectedLocation) => compareLocations(selectedLocation, location) ); const newSelected = remove(removedSelectionIndex, 1, selected); setSelected(newSelected); }; // TODO: none of this id and animatoin stuff is going to work right now // if we set more than one animation per move const getAnimationId = () => { const animationId = nextAnimationId; setNextAnimationId(nextAnimationId + 1); return animationId; }; const addAnimation = (...newAnimations) => { const identifiedAnimations = newAnimations.map((animation) => { return { ...animation, id: getAnimationId() }; }); setAnimations([ ...animations, { target, name, id: getAnimationId(), }, ]); }; const finishAnimation = (id) => { const animationIndex = animations.findIndex( (animation) => animation.id === id ); const newAnimations = remove(animationIndex, 1, animations); setAnimations(newAnimations); }; const applyGravity = () => { const newTiles = mapMatrix((tile, location) => { const lowerLocation = { row: location.row + 1, col: location.col, }; const upperLocation = { row: location.row - 1, col: location.col, }; // This tile is empty, drop one above down if (tile === "") { if (isLocationInBounds(tiles, upperLocation)) { const upperTile = getLocation(tiles, upperLocation); return upperTile; } // if no upper tile, spawn a new one return pickRandomFromArray([...levels[currentLevel].items, "SKULL"]); } if (isLocationInBounds(tiles, lowerLocation)) { const lowerTile = getLocation(tiles, lowerLocation); // Lower tile is empty, drop down if (lowerTile === "") { return ""; } } else { // this means we're at the bottom of the grid if (tile === "SKULL") { // damage the heart below you if (shields[location.col] <= 0) { setHearts(update(location.col, hearts[location.col] - 1, hearts)); } return ""; } } // gravity doesn't affect us return tile; }, tiles); setTiles(newTiles); }; const startGravityTimeout = () => { const applyGravityTimeout = () => { if (areTilesSettled(tiles)) { return; } applyGravity(); setTimeout(applyGravityTimeout, 500); }; applyGravityTimeout(); }; useEffect(() => { if (!levels[currentLevel]) { return; } if (areTilesSettled(tiles)) { return; } setTimeout(() => applyGravity(), 100); // startGravityTimeout(); }, [tiles]); if (!levels[currentLevel]) { return <p>Loading...</p>; } const selectedRecipe = getSelectedRecipe({ selected, recipes: levels[currentLevel].recipes, tiles, }); const castSelectedSpell = () => { let newScore = score; let newTiles = tiles; let newHearts = hearts; let newShields = shields; const updateSelectedTiles = (newTile, currentTiles) => { return mapMatrix((tile, location) => { if (isLocationSelected({ location, selected })) { return newTile; } return tile; }, currentTiles); }; newTiles = updateSelectedTiles("", newTiles); // clean up previous applied effects // degrade clouds newTiles = mapMatrix((tile) => { if (tile === "CLOUD") { return ""; } return tile; }, newTiles); // degrade shields newShields = newShields.map((shield) => (shield > 0 ? shield - 1 : 0)); // act on new recipes if (selectedRecipe) { selectedRecipe.effects.forEach((effect) => { switch (effect.type) { case "DAMAGE_COLUMN": newHearts = selected.reduce((currentHearts, selectedLocation) => { if (shields[selectedLocation.col] <= 0) { return update( selectedLocation.col, hearts[selectedLocation.col] - effect.value, currentHearts ); } return currentHearts; }, hearts); break; case "SCORE": newScore = score + selected.length * 10; break; case "BONUS_SCORE": newScore = score + 50; break; case "BOMB": newTiles = mapMatrix((tile, location) => { const neighbors = getNeighbors( getCrossDirections, newTiles, location ); if ( neighbors.some((neighbor) => isLocationSelected({ location: neighbor, selected }) ) ) { return ""; } return tile; }, newTiles); break; case "CLOUDS": newTiles = updateSelectedTiles("CLOUD", newTiles); break; case "SHIELD_COLUMNS": newShields = selected.reduce( (currentShields, selectedLocation) => update( selectedLocation.col, shields[selectedLocation.col] + 1, currentShields ), shields ); break; default: break; } }); setScore(newScore); setHearts(newHearts); setShields(newShields); setTiles(newTiles); setSelected([]); } }; if (hearts.every((heart) => heart <= 0)) { return ( <div className="container"> <p>Game Over!</p> <button onClick={() => window.location.reload()}>Restart</button> </div> ); } return ( <div className="container" onMouseUp={() => setSelected([])}> <div> <div className="score-bar"> <p>{String(score).padStart(4, "0")}</p> <p>{String(levels[currentLevel].target).padStart(4, "0")}</p> </div> <Grid tiles={tiles} renderTile={(tile, location) => ( <Tile createSprite={createSprite} tile={tile} items={items} location={location} selected={isLocationSelected({ location, selected })} selectedNeighborDirections={getSelectedNeighborDirections({ tiles, location, selected, })} onMouseDown={(e) => { setMouseDown(true); setMouseDownLocation(location); if ( // isMouseDownLocationSame && isLocationSelected({ location, selected }) ) { // If we mouse up on the same location we mouse downed on // and that location was selected, clear all selection. // setSelected([]); // If we mouse up on same location we have already selected, case the ability // if (isLocationSelected({ location, selected })) { castSelectedSpell(); // } } else { setSelected([location]); } e.stopPropagation(); }} onMouseUp={(e) => { setMouseDown(false); e.stopPropagation(); }} onMouseEnter={() => { if (isMouseDown) { addSelection(location); } }} highlighted={ isLocationSelected({ location, selected }) && Boolean(selectedRecipe) } spriteConfig={spriteConfig} key={JSON.stringify(location)} /> )} cellSize={`${spriteConfig.size * spriteConfig.scale}px`} /> <div className="health-bar"> {hearts.map((value, index) => { return ( <div key={index} className="heart-container" style={{ width: `${spriteConfig.size * spriteConfig.scale}px`, height: `${spriteConfig.size * spriteConfig.scale}px`, }} > <Heart value={value} createSprite={createSprite} items={items} /> {shields[index] > 0 ? createSprite(items.SHIELD.sprite) : null} <div style={{ width: `${spriteConfig.size * spriteConfig.scale}px`, height: `${spriteConfig.size * spriteConfig.scale}px`, }} className={value} /> </div> ); })} </div> {/* <pre>{JSON.stringify({ isMouseDown })}</pre> */} </div> </div> ); }; export default App; <file_sep>import React from "react"; const createBackground = ({ location, selected, createSprite }) => { const isEvenCol = location.col % 2 === 0; const isEvenRow = location.row % 2 === 0; let col; if (isEvenRow) { col = isEvenCol ? 1 : 2; } else { col = isEvenCol ? 3 : 4; } const row = selected ? 4 : 2; return createSprite({ row, col }); }; const createItem = ({ tile, createSprite, items }) => { if (!items[tile]) { return null; } return createSprite(items[tile].sprite); }; const createSelector = ({ selected, selectedNeighborDirections, createSprite, }) => { if (!selected) { return null; } // left, up, right down return ( <div className="selector"> {!selectedNeighborDirections.right && createSprite({ row: 3, col: 0 })} {!selectedNeighborDirections.down && createSprite({ row: 3, col: 1 })} {!selectedNeighborDirections.left && createSprite({ row: 3, col: 2 })} {!selectedNeighborDirections.up && createSprite({ row: 3, col: 3 })} </div> ); }; const Tile = ({ createSprite, tile, location, selected, onClick, onMouseDown, onMouseUp, onMouseEnter, selectedNeighborDirections, items, highlighted, spriteConfig, }) => { const background = createBackground({ location, createSprite, selected }); const item = createItem({ tile, createSprite, items }); const selector = createSelector({ selected, selectedNeighborDirections, createSprite, }); return ( <div className="tile" onClick={onClick} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onMouseEnter={onMouseEnter} > {background} {highlighted && ( <div style={{ width: `${spriteConfig.size * spriteConfig.scale}px`, height: `${spriteConfig.size * spriteConfig.scale}px`, }} className="highlight-anim" /> )} {item} {selector} </div> ); }; export default Tile;
9ddf78566429c42ef3a23601022c2b51732f5050
[ "JavaScript" ]
5
JavaScript
rmkubik/making-magic
5603511092e7203080d41ca23dd5d25a03f944c9
6c7ba9ef4f4516be1a4056f2cd84069d2c756357
refs/heads/master
<repo_name>vincent-landolfi/Python-SQL-Simulation<file_sep>/database.py class Table(): '''A class to represent a SQuEaL table''' def __init__(self): '''(Table,dict of {str: list of str}) -> NoneType Creates a new Table using the data from the given dictionary ''' # make the class variable equal to table self._table = {} def set_dict(self, new_dict): '''(Table, dict of {str: list of str}) -> NoneType Populate this table with the data in new_dict. The input dictionary must be of the form: column_name: list_of_values ''' # make the table the new dict self._table = new_dict def get_dict(self): '''(Table) -> dict of {str: list of str} Return the dictionary representation of this table. The dictionary keys will be the column names, and the list will contain the values for that column. ''' # return the table in that class return self._table def reset(self): '''(Table) -> NoneType Reset the dictionary in the table to a blank table ''' self._table = {} def add_column(self, key, value): '''(Table,str,list) -> NoneType Adds the column to the dict in the table with the list as that value for the key ''' # add the key value pairing to the dict self._table.update({key: value}) def merge_tables(self, table): '''(Table,Table) -> NoneType Takes two tables which have been prepped for the cartesian equation and merges them together ''' # update one table with the other self._table.update(table._table) def add_value(self, key, value): '''(Table,str,str) -> NoneType Appends the given value to the list at the given key ''' # append the value to the list at that key self._table[key].append(value) def __str__(self): return str(self._table) def get_columns(self): '''(Table) -> list Returns the names of the keys in the dict in a list ''' # return the keys in the classes table return self._table.keys() def get_length_columns(self): '''(Table) -> int Returns the length of the table in an integer ''' # get a list of the keys key_list = list(self.get_columns()) # check if there are keys if (key_list != []): length = len(self._table[key_list[0]]) else: length = 0 # get the length of the column return length def get_length_rows(self): '''(Table) -> int Returns the number of rows the table has ''' # make a list of the keys key_list = list(self.get_columns()) # return the length of one keys list length return len(key_list) def delete_column(self, column): '''(Table,str) -> NoneType Delete the given column from the table REQ: column is in the table ''' # delete the key:value pairing at that key del self._table[column] def delete_row(self, row): '''(Table,int) -> NoneType Delete the row by using the row number or index of the list REQ: row>=0 ''' # go through all the columns for i in self.get_columns(): # delete the list value at given index del self._table[i][row] def delete_column(self, column): '''(Table,str) -> NoneType Deletes the given column REQ: column in table ''' del self._table[column] def get_value_index(self, key, index): '''(Table) -> str Returns the value at an index of the list in the key:value pairing REQ: key is in dict REQ: index is in list at key ''' # returns the value at that key and index of the value return self._table[key][index] def get_value(self, key): '''(Table) -> list Returns the list at the key in the table REQ: key is in dict ''' return self._table[key] class Database(): '''A class to represent a SQuEaL database''' def __init__(self, database={}): '''(Database, dict of {str: Table}) -> NoneType Populate this database with the data in new_dict. new_dict must have the format: table_name: table ''' # make the class variable the given database self._database = database def set_dict(self, new_dict): '''(Database, dict of {str: Table}) -> NoneType Populate this database with the data in new_dict. new_dict must have the format: table_name: table ''' # make the database the new dict self._database = new_dict def get_dict(self): '''(Database) -> dict of {str: Table} Return the dictionary representation of this database. The database keys will be the name of the table, and the value with be the table itself. ''' # return the current database variable return self._database def add_table(self, key, table): '''(Database,str,list) -> NoneType Adds the column to the database with the table as the value ''' # add the key value pairing to the dict self._database.update({key: table}) def __str__(self): return str(self._database) def get_tables(self): '''(Database) -> list of str Returns all the tables in the database ''' # return the tables in the databse return self._database.keys() def get_table_value(self, key): '''(Database) -> Table Returns the table at the given key REQ: table(key) is in database ''' return self._database[key] <file_sep>/reading.py # Functions for reading tables and databases import glob from database import * # a table is a dict of {str:list of str}. # The keys are column names and the values are the values # in the column, from top row to bottom row. # A database is a dict of {str:table}, # where the keys are table names and values are the tables. # Write the read_table and read_database functions below def read_table(filename): '''(str) -> Table Opens the .csv file and makes the line a table REQ: file is in same directory as .py file >>>read_table('books.csv') ''' # take the str, make filehandle filehandle = open(filename, 'r') # read the lines of the file line_list = filehandle.readlines() # make a blank table reader = Table() reader.reset() # make a blank list to save the keys key_list = [] # go through all of the lines for i in range(0, len(line_list)): # split at the commas,mutate list line_list[i] = line_list[i].strip('\n').split(',') # check if it is the first iteration if (i == 0): # put the keys into the dictionary with blank list for j in line_list[i]: reader.add_column(j, []) # save the actual keys to a list to help later key_list.append(j) # any other iteration else: # check for messy inputs if (len(line_list[i]) == len(line_list[0])): # add proper values to proper table key for j in range(0, len(key_list)): reader.add_value(key_list[j], line_list[i][j]) # close the file filehandle.close() # return a new table return reader def read_database(): ''' () -> Database Reads all the .csv files in the directory and returns a database of all of them. ''' # make the blank database database = Database() # get a list of all the file names file_list = glob.glob('*.csv') # go through each of the files for i in file_list: # get a name for the key key_name = i.replace('.csv', '') # get the table form read table table_name = read_table(i) # update our database database.add_table(key_name, table_name) # return a new database return database <file_sep>/squeal.py from reading import * from database import * # Below, write: # *The cartesian_product function # *All other functions and helper functions # *Main code that obtains queries from the keyboard, # processes them, and uses the below function to output csv results def print_csv(table): '''(Table or Database) -> NoneType Print a representation of table. >>>princt_csv(movies) m.year,m.title,m.studio,m.gross 1997,Titanic,Par.,2186.8 2003,The Lord of the Rings: The Return of the King,NL,1119.9 2010,Toy Story 3,BV,1063.2 ''' dict_rep = table.get_dict() columns = list(dict_rep.keys()) print(','.join(columns)) rows = num_rows(table) for i in range(rows): cur_column = [] for column in columns: cur_column.append(dict_rep[column][i]) print(','.join(cur_column)) def num_rows(table): '''(Table) -> int Takes a Table and determines the number of rows that the table has >>> num_rows(movies) 3 ''' # get the length of the table return table.get_length_columns() def run_query(database, query): '''(Database,str) -> Table Takes a database object and a query, and then runs the query on the database to create and return a table REQ: query of form 'select x from y (where x=z)' >>> run_query(database,'select book.year from books') ''' # make blank table to work with work_table = Table() # make an empty list of rows to delete delete_list = [] # split the query query = query.split() # go check which tables we're taking from, make list query[3] = query[3].split(',') # check if we have more than one table if (len(query[3]) > 1): # make the cartesian product for i in range(0, len(query[3]) - 1): # do the cartesian product of two values for first time if (i == 0): # cartesian product of first two work_table = cartesian_product(database.get_table_value( query[3][i]), database.get_table_value(query[3][i + 1])) # if it is not the first time else: # do the cartesian product with the previous work_table = cartesian_product( work_table, database.get_table_value(query[3][i + 1])) # check if there is a 'where' clause if (len(query) > 4): # split the where clauses query[5] = query[5].split(',') # check if there are spaces if (len(query) > 6): # go through the extra words in the where clause for i in range(6, len(query)): # And the extra words to the query were testing query[5][0] += (' ' + query[i]) # check if we have only one table if (len(query[3]) == 1): work_table = database.get_table_value(query[3][0]) # go through the where clauses for j in query[5]: # go through the values in each row for i in range(0, work_table.get_length_columns()): # check if the statement is false if not(evaluate_where(j, work_table, i)): delete_list.append(i) for num in range(len(delete_list) - 1, -1, -1): work_table.delete_row(delete_list[num]) # now take care of the columns wanted # split the columns at the commas query[1] = query[1].split(',') # check if we have more than one table if (len(query[3]) > 1): # get all the columns from the current table current_columns = list(work_table.get_columns()) # if we only have one table else: # get all the columns from the one table current_columns = list( database.get_table_value(query[3][0]).get_columns()) # use the table at query[3][0] for deleting work_table = database.get_table_value(query[3][0]) # go through the columns in the current table for i in current_columns: # check if we want to delete the column if (i not in query[1] and query[1][0] != '*'): # delete the column work_table.delete_column(i) # return the table we worked with return work_table def cartesian_product(table1, table2): '''(Table,Table) -> Table The cartesian product of two tables is a new table where each row in the first table is paired with every row in the second table REQ: table1,table2 in database ''' # make empty dicts for the product cartesian1 = Table() cartesian2 = Table() # get the two lists of keys from each table keys1 = table1.get_columns() keys2 = table2.get_columns() # go through the first table for i in keys1: # make an empty list for values value_list = [] # go the the elements of the list value at the key for j in range(0, table1.get_length_columns()): # apply the same value, table2 length times for k in range(0, table2.get_length_columns()): # update the value list with the values obtained value_list.append(table1.get_value_index(i, j)) # put the completed value list in the cartesian dict cartesian1.add_column(i, value_list) # go through the second table for i in keys2: # list of empty values value_list2 = [] # go the the elements of the list value at the key for j in range(0, table1.get_length_columns()): # apply the same value, table2 length times for k in range(0, table2.get_length_columns()): # update the value list with the values obtained value_list2.append(table2.get_value_index(i, k)) # add the made list to the proper key cartesian2.add_column(i, value_list2) # combine the two lists together cartesian1.merge_tables(cartesian2) # return the merged tables return cartesian1 def evaluate_where(where_clause, table, index): '''(list,table,int) -> bool Takes the where clause and tells the program whether it is True or False at various instances.Index is the index of the row. >>> evaluate_where(['book.year=2015'],books,2) False >>> evaluate_where(['book.year=2015'],books,3) True ''' # make a list of operators to look for op_list = ['>', '='] # go through the letters in the clause for i in where_clause: # find the operator if (i in op_list): # get first key by going from beginning to operator t1 = where_clause[0:where_clause.index(i)] # get the operator op = i # get second key by going from operator to end t2 = where_clause[where_clause.index(i) + 1:len(where_clause)] # check if there are quotes after the equal sign if ('"' in t2) or ("'" in t2): # get rid of the quotes t2 = t2[1:-1] # check if the operator is equals if (op == '='): # check if the value isn't hard coded if (t2 in table.get_columns()): # check if the actual values equal each other ret_bool = (table.get_value_index(t1, index).lstrip() == table.get_value_index(t2, index).lstrip()) # if the value is had coded else: # check if it equals the hard coded value ret_bool = (table.get_value_index( t1, index).lstrip() == t2.lstrip()) # check if the operator is greater than elif (op == '>'): # check if the value isn't hard coded if (t2 in table.get_columns()): # check if the actual values equal each other ret_bool = (table.get_value_index(t1, index).lstrip() > table.get_value_index(t2, index).lstrip()) # if the value is had coded else: # check if it equals the hard coded value ret_bool = (table.get_value_index(t1, index).strip() > t2.lstrip()) # return the boolean resolving each expression return ret_bool if(__name__ == "__main__"): query = input("Enter a SQuEaL query, or a blank line to exit:") database = read_database() print_csv(run_query(database, query))
9deffa22b89b157559aa55a70230fcec422d23ac
[ "Python" ]
3
Python
vincent-landolfi/Python-SQL-Simulation
68104b0f7a7091c70da7d510bb8bf822feb16a57
ed198b69a5cb6806ace67fd01d27af444045520b
refs/heads/master
<repo_name>lovelearn/myzookeeper<file_sep>/README.md * 运行环境 1.zookeeper 版本:3.4.6 端口:2181 2.apache-tomcat 版本:7.0.68 端口:8080 3.mysql 版本:5.6 端口:3306<file_sep>/user.sql SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'admin', 'admin', null);
42998718bbb6d5a502ebc75d078b1d5d8cc8491e
[ "Markdown", "SQL" ]
2
Markdown
lovelearn/myzookeeper
a37aab15ff22188a2f5c25ce850bb9ca83717473
30649d8db522364d44fd5a3a534de6f987228c89
refs/heads/master
<repo_name>colinthornton/strava-segments<file_sep>/src/components/Segments/SegmentOptionsForm.js import React from 'react'; import PropTypes from 'prop-types'; import SegmentOptions from '../../data/services/SegmentOptions'; import LabeledSelect from '../LabeledSelect'; const locationOptions = SegmentOptions.locationKeys.map(key => ({ value: key, text: SegmentOptions.locations[key].text, })); const activityTypeOptions = SegmentOptions.activityTypeKeys.map(key => ({ value: key, text: SegmentOptions.activityTypes[key].text, })); const climbingCategoryOptions = SegmentOptions.climbingCategoryKeys.map( key => ({ value: key, text: SegmentOptions.climbingCategories[key].text, }), ); export default function SegmentOptionsForm({ state, setState, disabled }) { return ( <form className="d-flex flex-row flex-wrap w-100"> <div className="form-group ml-4 mb-2"> <LabeledSelect id="locationSelect" label="Location" value={state.locationKey} setValue={locationKey => setState({ ...state, locationKey })} options={locationOptions} labelClass="d-flex flex-row align-items-center" selectClass="form-control ml-2" disabled={disabled} /> </div> <div className="form-group ml-4 mb-2"> <LabeledSelect id="activityTypeSelect" label="Activity" value={state.activityTypeKey} setValue={activityTypeKey => setState({ ...state, activityTypeKey })} options={activityTypeOptions} labelClass="d-flex flex-row align-items-center" selectClass="form-control ml-2" disabled={disabled} /> </div> <div className="form-group d-flex flex-row align-items-center ml-4 mb-2"> <LabeledSelect id="minCatSelect" label="Climbing Category" value={state.minCatKey} setValue={minCatKey => setState({ ...state, minCatKey, maxCatKey: state.maxCatKey < minCatKey ? minCatKey : state.maxCatKey, }) } options={climbingCategoryOptions} labelClass="d-flex flex-row align-items-center text-nowrap" selectClass="form-control mx-2" disabled={disabled} /> <LabeledSelect id="maxCatSelect" label="~" value={state.maxCatKey} setValue={maxCatKey => setState({ ...state, maxCatKey, minCatKey: state.minCatKey > maxCatKey ? maxCatKey : state.minCatKey, }) } options={climbingCategoryOptions} labelClass="d-flex flex-row align-items-center text-nowrap" selectClass="form-control ml-2" disabled={disabled} /> </div> </form> ); } SegmentOptionsForm.propTypes = { state: PropTypes.exact({ locationKey: PropTypes.string, activityTypeKey: PropTypes.string, minCatKey: PropTypes.string, maxCatKey: PropTypes.string, }).isRequired, setState: PropTypes.func.isRequired, disabled: PropTypes.bool.isRequired, }; <file_sep>/src/routes/home/index.js import React from 'react'; import Layout from '../../components/Layout'; import SegmentOptions from '../../data/services/SegmentOptions'; import fetchSegments from './fetchSegments'; import Home from './Home'; const initialOptions = { locationKey: 'kanto', activityTypeKey: 'any', minCatKey: 'cat0', maxCatKey: 'cat5', }; const variables = { startLatlong: SegmentOptions.locations[initialOptions.locationKey].value.startLatlong, endLatlong: SegmentOptions.locations[initialOptions.locationKey].value.endLatlong, activityType: SegmentOptions.activityTypes[initialOptions.activityTypeKey].value, minCat: SegmentOptions.climbingCategories[initialOptions.minCatKey].value, maxCat: SegmentOptions.climbingCategories[initialOptions.maxCatKey].value, }; async function action({ fetch }) { const segments = await fetchSegments(fetch, variables); return { chunks: ['home'], title: 'Strava Segments', component: ( <Layout> <Home initialSegments={segments} initialOptions={initialOptions} /> </Layout> ), }; } export default action; <file_sep>/src/data/types/SegmentType.js import { GraphQLObjectType as ObjectType, GraphQLNonNull as NonNull, GraphQLInt as IntType, GraphQLString as StringType, GraphQLFloat as FloatType, GraphQLList as ListType, GraphQLBoolean as BoolType, } from 'graphql'; const SegmentType = new ObjectType({ name: 'Segment', fields: { id: { type: new NonNull(IntType) }, name: { type: new NonNull(StringType) }, climbCategory: { type: new NonNull(IntType) }, climbCategoryDesc: { type: new NonNull(StringType) }, avgGrade: { type: new NonNull(FloatType) }, startLatlng: { type: new NonNull(new ListType(FloatType)) }, endLatlng: { type: new NonNull(new ListType(FloatType)) }, elevDifference: { type: new NonNull(FloatType) }, distance: { type: new NonNull(FloatType) }, points: { type: new NonNull(StringType) }, starred: { type: new NonNull(BoolType) }, }, }); export default SegmentType; <file_sep>/src/components/LabeledSelect.js import React from 'react'; import PropTypes from 'prop-types'; export default function LabeledSelect({ id, label, value, setValue, options, labelClass, selectClass, optionClass, disabled, }) { return ( <label className={labelClass} htmlFor={id}> {label} <select disabled={disabled} className={selectClass} id={id} value={value} onChange={e => setValue(e.target.value)} > {options.map(({ value: optionVal, text }) => ( <option className={optionClass} key={optionVal} value={optionVal}> {text} </option> ))} </select> </label> ); } LabeledSelect.propTypes = { id: PropTypes.string.isRequired, value: PropTypes.string.isRequired, setValue: PropTypes.func.isRequired, options: PropTypes.arrayOf( PropTypes.shape({ value: PropTypes.string, text: PropTypes.string, }), ).isRequired, label: PropTypes.string, labelClass: PropTypes.string, selectClass: PropTypes.string, optionClass: PropTypes.string, disabled: PropTypes.bool, }; LabeledSelect.defaultProps = { label: '', labelClass: '', selectClass: '', optionClass: '', disabled: false, }; <file_sep>/test/data/utils.test.js import { snakeToCamel, toParamString } from '../../src/data/utils'; describe('snakeToCamel', () => { test.each([ [{ snake_case: 0 }, { snakeCase: 0 }], [ { snake_case: 0, camelCase: 1 }, { snakeCase: 0, camelCase: 1 }, ], [{ the_value_for_this_key_is_zero: 0 }, { theValueForThisKeyIsZero: 0 }], [ { CAPITAL_SNAKES: 0, lowercase_snakes: 1, half_CAPITALS: 2 }, { capitalSnakes: 0, lowercaseSnakes: 1, halfCapitals: 2 }, ], ])( 'should return an object with snake_case keys converted to camelCase', (input, expected) => { expect(snakeToCamel(input)).toStrictEqual(expected); }, ); }); describe('toParamString', () => { test.each([ [{ key: 'value' }, 'key=value'], [ { key: 'value', anotherKey: 'anotherValue', }, 'key=value&anotherKey=anotherValue', ], [{}, ''], [{ 1: 1, 2: 2, string: 'string' }, '1=1&2=2&string=string'], ])('should return an object in param string form', (input, expected) => { expect(toParamString(input)).toBe(expected); }); }); <file_sep>/src/components/Segments/SegmentMessage.js import React from 'react'; import PropTypes from 'prop-types'; export default function SegmentMessage({ noSegments, loading, errorMessage }) { return ( <div className="d-flex justify-content-center w-100"> {noSegments && !errorMessage ? <p>No segments found</p> : null} {loading ? ( <div className="spinner-border" role="status"> <span className="sr-only">Loading...</span> </div> ) : null} {errorMessage ? <p className="text-danger">{errorMessage}</p> : null} </div> ); } SegmentMessage.propTypes = { noSegments: PropTypes.bool.isRequired, loading: PropTypes.bool.isRequired, errorMessage: PropTypes.string, }; SegmentMessage.defaultProps = { errorMessage: null, }; <file_sep>/src/data/services/SegmentOptions.js const locations = { kanto: { text: 'Kanto', value: { startLatlong: [34.8968, 138.3825], endLatlong: [37.1622, 140.9011], }, }, honshu: { text: 'Honshu', value: { startLatlong: [33.4, 130.85], endLatlong: [41.55, 142.08], }, }, kyushu: { text: 'Kyushu', value: { startLatlong: [30.9843, 128.5272], endLatlong: [33.9635, 132.0867], }, }, shikoku: { text: 'Shikoku', value: { startLatlong: [32.5373, 131.7891], endLatlong: [34.6282, 135.4551], }, }, hokkaido: { text: 'Hokkaido', value: { startLatlong: [41.37, 139.32], endLatlong: [45.58, 145.54], }, }, colorado: { text: 'Colorado', value: { startLatlong: [36.99, -109.04], endLatlong: [41.0, -102.04], }, }, }; const activityTypes = { any: { text: 'Any', value: null, }, riding: { text: 'Riding', value: 'riding', }, running: { text: 'Running', value: 'running', }, }; const climbingCategories = { cat5: { text: 'HC', value: 5, }, cat4: { text: '1', value: 4, }, cat3: { text: '2', value: 3, }, cat2: { text: '3', value: 2, }, cat1: { text: '4', value: 1, }, cat0: { text: 'NC', value: 0, }, }; export default class SegmentOptions { static get locationKeys() { return Object.keys(locations); } static get locations() { return { ...locations }; } static get activityTypeKeys() { return Object.keys(activityTypes); } static get activityTypes() { return { ...activityTypes }; } static get climbingCategoryKeys() { return Object.keys(climbingCategories); } static get climbingCategories() { return { ...climbingCategories }; } static toQueryVariables({ locationKey, activityTypeKey, minCatKey, maxCatKey, }) { return { startLatlong: SegmentOptions.locations[locationKey].value.startLatlong, endLatlong: SegmentOptions.locations[locationKey].value.endLatlong, activityType: SegmentOptions.activityTypes[activityTypeKey].value, minCat: SegmentOptions.climbingCategories[minCatKey].value, maxCat: SegmentOptions.climbingCategories[maxCatKey].value, }; } } <file_sep>/src/routes/home/fetchSegments.js const segmentsQuery = `query Segments( $startLatlong: [Float]!, $endLatlong: [Float]!, $activityType: String, $minCat: Int, $maxCat: Int ) { segments( startLatlong: $startLatlong, endLatlong: $endLatlong, activityType: $activityType, minCat: $minCat, maxCat: $maxCat ) { id name distance avgGrade elevDifference climbCategoryDesc } }`; async function fetchSegments(fetch, variables) { const res = await fetch('/graphql', { body: JSON.stringify({ query: segmentsQuery, variables, }), }); const { data } = await res.json(); if (!data || !data.segments) { throw new Error('Failed to load segments.'); } return data.segments; } export default fetchSegments; <file_sep>/src/data/services/stravaToken.js import fetch from 'node-fetch'; import config from '../../config'; const url = 'https://www.strava.com/oauth/token'; let accessToken; let expiresAt = 0; let lastFetch = null; async function getStravaToken() { if (lastFetch !== null) { return lastFetch; } if (Math.floor(Date.now() / 1000) > expiresAt) { lastFetch = fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ ...config.auth.strava, grant_type: 'refresh_token', }), }) .then(res => { if (!res.ok) { throw new Error(`${res.status}: ${res.statusText}`); } return res.json(); }) .then(data => { expiresAt = data.expires_at; accessToken = data.access_token; return accessToken; }) .finally(() => { lastFetch = null; }); return lastFetch; } return accessToken; } export default getStravaToken; <file_sep>/README.md # Strava Segments ## Setup Set your Strava API information in `src/config.js`. Otherwise set the corresponding environment variables when you start the server. ```js // src/config.js strava: { client_id: process.env.STRAVA_CLIENT_ID || 'client_id_here', client_secret: process.env.STRAVA_CLIENT_SECRET || 'client_secret_here', refresh_token: process.env.STRAVA_REFRESH_TOKEN || 'refresh_token_here', }; ``` Make sure you have Node.js installed (version >= 8.16.2) and run `npm install` in the project folder. Run `npm start` to start the server, by default it's accessible at `localhost:3000`. <file_sep>/src/data/utils.js function convertSnakeToCamel(snake) { return snake .split('_') .map((word, i, words) => { // No snakes found if (words.length === 1) { return word; } if (i === 0) { return word.toLowerCase(); } return ( word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase() ); }) .join(''); } /** * Returns a new object with all the keys from `snakeKeyObj` converted to camel * case. * @param {Object} snakeKeyObj Object with keys in snake case (like_this) * @return {Object} Object with keys in camel case (likeThis) */ export function snakeToCamel(snakeKeyObj) { return Object.keys(snakeKeyObj).reduce((camelKeyObj, snakeKey) => { const camelKey = convertSnakeToCamel(snakeKey); return { ...camelKeyObj, [camelKey]: snakeKeyObj[snakeKey] }; }, {}); } /** * Returns a new string with `params`. * @param {Object} params Query parameter key:value pairs * @return {string} Params in the form `key=value&otherKey=otherValue` */ export function toParamString(params) { return Object.entries(params) .map(([key, value]) => `${key}=${value}`) .join('&'); }
6449c275f2dcebe928ad22453150e9501ba6b8e3
[ "JavaScript", "Markdown" ]
11
JavaScript
colinthornton/strava-segments
a2c862202590580a757a97fcc3bf57cffba9cdd9
19a47300bfafd5eb550021e90c071040b856d479
refs/heads/master
<file_sep>import React from "react"; import { Row, Col, Card } from "reactstrap"; import PerfectScrollbar from 'react-perfect-scrollbar'; import Style from "../scss/MsgCont.scss"; class MsgCont extends React.PureComponent{ constructor(props){ super(props); } componentDidUpdate(){ let sCont = this._contRef._container; //console.log(sCont); let sTop = sCont.scrollHeight - sCont.offsetHeight; if(sTop > 0){ sCont.scrollTop = sTop; } } render(){ let rendMsg; let chatHeader; let msgArr; if(this.props.histArr){ msgArr = [...this.props.histArr, ...this.props.currArr] } else{ msgArr = this.props.currArr; } console.log(msgArr); rendMsg = msgArr.map((msgObj, ind) => { if(msgObj.uid){ return <Row className="justify-content-end mr-0"><div className={Style.rightBlock}>{msgObj.msg}</div></Row> }else{ return <Row className="justify-content-start ml-0"><div className={Style.leftBlock}>{msgObj.msg}</div></Row> } }); if(this.props.currChat){ chatHeader = <div className={Style.chatHeader}>{this.props.currChat}</div> } return( <div id="msgCont" className={Style.mainCont}> {chatHeader} <PerfectScrollbar ref={(contRef) => {this._contRef = contRef;}} option={{suppressScrollX: true}}> {rendMsg} </PerfectScrollbar> </div> ); } } export default MsgCont;<file_sep>import React from 'react'; import { Container, Spinner } from 'reactstrap'; const contStyle = { height: "100%", width: "100%", maxWidth: "100%", maxHeight: "100%", backgroundColor: "white", margin: "0", display: "flex", alignItems: "center", justifyContent: "center", padding: "0" } class LoadComp extends React.Component { render(){ return( <div className="container d-flex justify-content-center align-items-center"> <Spinner style={{ width: '3rem', height: '3rem' }} type="grow" color="dark" /> <Spinner style={{ width: '3rem', height: '3rem' }} type="grow" color="dark" /> <Spinner style={{ width: '3rem', height: '3rem' }} type="grow" color="dark" /> </div> ); } } export default LoadComp;<file_sep>import React, { Suspense, lazy } from 'react'; import io from 'socket.io-client'; import { BrowserRouter, Switch, Route } from "react-router-dom"; import LoadComp from './LoadComp.js'; const Auth = lazy(() => import("./Auth.js")); const Chat = lazy(() => import("./Chat.js")); class Root2 extends React.Component{ constructor(props){ super(props); this.state = { connect: false }; this.socket; } componentDidMount(){ this.socket = io.connect("http://localhost:5000", {transports: ['websocket']}); this.setState({ connect: true }) } compnentDidUpdate(){ console.log("updated", this.socket); } render(){ console.log(this.socket); return( <BrowserRouter basename="/"> <Switch> <Route exact path="/" render={props => ( <Suspense fallback={<LoadComp />}> <Auth {...props} socket={this.socket} /> </Suspense> )} /> <Route exact path="/chat" render={props => ( <Suspense fallback={<LoadComp />}> <Chat {...props} socket={this.socket} /> </Suspense> )} /> </Switch> </BrowserRouter> ); } } export default Root2;<file_sep>import React from 'react'; class Root extends React.Component{ constructor(props){ super(props); this.state = { message: [], input: "", error: null } this.handleChange = this.handleChange.bind(this); this.handleSend = this.handleSend.bind(this); } handleChange(e){ let id = e.currentTarget.id; let val = e.currentTarget.value; let stateObj = {}; stateObj[id] = val; this.setState(stateObj); } handleSend(e){ e.preventDefault(); let msgObj = { msg: this.state.input } msgObj = JSON.stringify(msgObj); this.socket.send(msgObj); this.setState({ input: "" }) } componentDidMount(){ this.socket = new WebSocket('ws://localhost:5000', ['json']); this.socket.onerror = err => { console.log(err) /*this.setState({ error: err; })*/ } this.socket.onmessage = e => { let res = JSON.parse(e.data); console.log(e, res); let copyArr = [...this.state.message] copyArr.push(res); this.setState({ message: copyArr }); } } render(){ let rendChat = this.state.message.map((elem, id) => <div> {elem} </div>) return( <div> <h3>Test</h3> <div> {rendChat} </div> <p>{this.state.error}</p> <input type="text" id="input" value={this.state.input} onChange={this.handleChange} /> <button onClick={this.handleSend}>Send</button> </div> ); } } export default Root; <file_sep>import React from "react"; import { Col, InputGroup, InputGroupAddon, Input, Button } from "reactstrap"; import { Send } from "react-feather"; class InputCont extends React.PureComponent{ constructor(props){ super(props); this.state = { input: "" } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e){ let id = e.currentTarget.id; let val = e.currentTarget.value; let stateObj = {}; stateObj[id] = val; this.setState(stateObj); } handleSubmit(e){ e.preventDefault(); let inStr = String(this.state.input); if(inStr.length > 0){ this.props.onSubmit(inStr); this.setState({ input: "" }); } /* if(this.props.currentChat){ //this.props.socket.emit("message", this.state.input, this.state.currentChat, () => {}); let inStr = String(this.state.input); if(inStr.length > 0){ this.onSubmit(inStr); this.setState({ input: "" }); } } else{ console.log("no one to chat with") this.props.onError("Pick someone to chat with first"); } */ } render(){ return( <form onSubmit={this.handleSubmit}> <InputGroup> <Input type="text" style={{border: "1px solid rgba(0,0,0,0.4)"}} id="input" onChange={this.handleChange} value={this.state.input} /> <InputGroupAddon addonType="append" onClick={this.handleSubmit}> <Button type="submit" color="info"><Send size={18} /></Button> </InputGroupAddon> </InputGroup> </form> ); } } export default InputCont;
092ef65bae89d3502414fba4449beffcf050b65c
[ "JavaScript" ]
5
JavaScript
mingyuea/websocket_chat_client_application
506083973868347f3a00362f4519e83e44f9ce20
f142c426db65898a1cc5ced29a9237445696ec39
refs/heads/master
<repo_name>qiulirensheng1/Caliper<file_sep>/src/main/java/com/example/demo16/TestDemo.java package com.example.demo16;/** * @Auther: dongguabai * @Date: 2018/9/16 17:04 * @Description: */ /** * @Auther: dongguabai * @Date: 2018/9/16 17:04 * @Description: */ public class TestDemo { }
1106f52e3984ee102007a341168ef896312656cd
[ "Java" ]
1
Java
qiulirensheng1/Caliper
31034316ab5e905c0c130525580fe4d909a33ecd
0824d96ae704aeaa271c84e3377be440310dbc7d
refs/heads/master
<file_sep>package com.wanyz.myquick4j.web.service.impl; import com.wanyz.myquick4j.core.generic.GenericDao; import com.wanyz.myquick4j.core.generic.GenericServiceImpl; import com.wanyz.myquick4j.web.dao.PermissionMapper; import com.wanyz.myquick4j.web.model.Permission; import com.wanyz.myquick4j.web.service.PermissionService; import javax.annotation.Resource; import java.util.List; /** * Created by rjh on 15-12-28. * 权限 Service 实现类 */ public class PermissionServiceImpl extends GenericServiceImpl<Permission, Long> implements PermissionService { @Resource private PermissionMapper permissionMapper; @Override public GenericDao<Permission, Long> getDao(){ return permissionMapper; } @Override public List<Permission> selectPermissionByRoleId(Long roleId){ return permissionMapper.selectPermissionsByRoleId(roleId); } } <file_sep>package com.wanyz.myquick4j.core.feature.orm.dialect; /** * Created by rjh on 15-12-25. * Postgre 数据库方言 */ public class PostgrsDialect extends Dialect { protected static final String SQL_END_DELIMITER = ";"; @Override public String getLimitString(String sql, int offset, int limit){ return PostgrePageHelper.getLimitString(sql, offset, limit); } @Override public String getCountString(String sql){ return PostgrePageHelper.getCountString(sql); } } <file_sep>package com.wanyz.myquick4j.web.dao; import com.wanyz.myquick4j.core.generic.GenericDao; import com.wanyz.myquick4j.web.model.Role; import com.wanyz.myquick4j.web.model.RoleExample; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by rjh on 15-12-28. * 角色的dao接口 */ public interface RoleMapper extends GenericDao<Role, Long> { int countByExample(RoleExample example); int deleteByExample(RoleExample id); int deleteByPrimary(Long id); int insert(Role role); int insertSelective(Role record); List<Role> selectByExample(RoleExample example); Role selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") Role record, @Param("example") RoleExample example); int updateByExample(@Param("record") Role record, @Param("example") RoleExample example); int updateByPrimaryKeySelective(Role record); int updateByPrimaryKey(Role record); /** * 通过用户id 查询用户拥有的权限 * @param id * @return */ List<Role> selectRolesByUserId(Long id); } <file_sep>package com.wanyz.myquick4j.core.feature.orm.dialect; /** * Created by rjh on 15-12-24. * MySql 数据库方言 */ public class MySql5Dialect extends Dialect{ protected final String SQL_END_DELIMITER = ";"; @Override public String getLimitString(String sql, int offset, int limit){ return MySql5PageHelper.getLimitString(sql, offset, limit); } @Override public String getCountString(String sql){ return MySql5PageHelper.getCountString(sql); } } <file_sep>package com.wanyz.myquick4j.core.feature.orm.dialect; import org.apache.ibatis.session.Configuration; /** * Created by rjh on 15-12-24. * 数据库方言工厂,产生方言对象 */ public class DialectFactory { public static String dialectClass = null; public static Dialect buildObject(Configuration configuration){ if(dialectClass == null){ synchronized(DialectFactory.class){ if(dialectClass == null) dialectClass = configuration.getVariables().getProperty("dialectClass"); } } Dialect dialect = null; try{ dialect = (Dialect)Class.forName(dialectClass).newInstance(); }catch(Exception e){ e.printStackTrace(); System.err.println("请检查 mybatis 总配置文件中 dialectClass 是否正确配置"); } return dialect; } } <file_sep>package com.wanyz.myquick4j.core.utils; import org.apache.commons.codec.digest.DigestUtils; import java.util.UUID; /** * Created by rjh on 15-12-25. * 加密用的方法类 */ public class ApplicationUtils { /** * 产生一个32字符的 UUID * @return */ public static String randomUUID(){ return UUID.randomUUID().toString(); } /** * 字符串 MD5 加密 * @param value * @return */ public static String md5Hex(String value){ return DigestUtils.md5Hex(value); } /** * sha1 加密 * @param value * @return */ public static String sha1Hex(String value){ return DigestUtils.sha1Hex(value); } /** * sha256 加密 * @param value * @return */ public static String sha256Hex(String value){ return DigestUtils.sha256Hex(value); } } <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.wanyz</groupId> <artifactId>myQuick4j</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>myQuick4j</name> <description>a project with Spring, Spring MVC, Mybatis coped from quick4j</description> <build> <finalName>myQuick4j</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${plugin.mybatis.generator}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${plugin.maven.compiler}</version> <configuration> <source>${project.build.jdk}</source> <target>${project.build.jdk}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${plugin.maven.surefire}</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> </plugins> <!-- 配置 maven 对resource文件的过滤 --> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <!-- base setting --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.locales>zh_CN</project.build.locales> <project.build.jdk>1.7</project.build.jdk> <!-- plugin version --> <plugin.mybatis.generator>1.3.1</plugin.mybatis.generator> <plugin.maven.compiler>3.1</plugin.maven.compiler> <plugin.maven.surefire>2.18.1</plugin.maven.surefire> <!-- lib version --> <junit.version>4.11</junit.version> <spring.version>4.2.4.RELEASE</spring.version> <mybatis.version>3.2.8</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <mysql-connector.version>5.1.36</mysql-connector.version> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> <cglib.version>3.1</cglib.version> <aspectj.version>1.8.7</aspectj.version> <commons.dbcp.version>1.4</commons.dbcp.version> <shiro.version>1.2.3</shiro.version> </properties> <dependencies> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <!-- springframe --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!-- spring mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- datasource --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${commons.dbcp.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector.version}</version> </dependency> <!-- jackson json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- apache tools --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- cglib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>${cglib.version}</version> </dependency> <!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-quartz</artifactId> <version>${shiro.version}</version> </dependency> <!-- aspectj weaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> </project><file_sep>package com.wanyz.myquick4j.core.generic; /** * Created by rjh on 15-12-25. * 所有自定义dao的顶级接口,封装常用的增删改查 * 可以通过 Mybatis Generator Maven 自动生成 dao * 也可以手动编码,然后继承 GenericDao * @param <Model> 代表数据库中的表 映射Java对象类型 * @param <PK> 代表对象的主键类型 */ public interface GenericDao<Model, PK> { /** * 插入对象 * @param model 对象 * @return */ int insertSelective(Model model); /** * 更新对象 * @param model 对象 * @return */ int updateByPrimaryKeySelective(Model model); /** * 通过逐渐 删除对象 * @param id 主键 * @return */ int deleteByPrimaryKey(PK id); /** * 通过主键 查询对象 * @param id * @return */ Model selectByPrimartKey(PK id); } <file_sep>package com.wanyz.myquick4j.core.generic; /** * Created by rjh on 15-12-25. * 所有自定义枚举类经实现这个接口 */ public interface GenericEnum { /** * 为保存在数据库中的值 * @return */ public String getValue(); /** * 为前端显示值 * @return */ public String getText(); }
a9cea1191eab773d74be15ed94102e4ece978cf2
[ "Java", "Maven POM" ]
9
Java
ashitakasan/myQuick4j
daf9a82ee385c1a1994617127fffea8cb10ac275
480b74b52208f69e568204cf6d4ee6c1eb9d6722
refs/heads/master
<file_sep>#!/usr/bin/python import sys class TreeNode: def __init__(self, data, parent=None): self.data = data self.parent = parent def __str__(self): return str(self.data) class Tree: def __init__(self): self.tree = [] def insert(self, data, parent): if self.tree == []: self.tree.append(TreeNode(data)) return i = 0 for el in self.tree: if el.data == parent: self.tree.append(TreeNode(data, self.find(parent))) break i = i + 1 def find(self, data): i = 0 for el in self.tree: if el.data == data: return i i = i + 1 return None def delete(self, data): i = 0 for el in self.tree: if el.data == data: self.tree.pop(i) i = i + 1 def getParents(self, data): for el in self.tree: if el.data == data: if el.parent == None: return None return self.tree[el.parent] return None def getChild(self, data): child = [] for el in self.tree: if el.parent == None: continue if self.tree[el.parent].data == data: child.append(el) return child t = Tree() t.insert(5, -1) t.insert(4, 5) t.insert(3, 5) t.insert(2, 5) for el in t.tree: print str(el.data) + " " + str(el.parent) <file_sep>#!/usr/bin/python import sys class BSTNode: def __init__(self, data): self.data = data self.left = None self.right = None def __str__(self): return str(self.data) class BST: def __init__(self, data): self.bst = BSTNode(data) self.left = None self.right = None def insert(self, data): node = self.bst lastNode = node while node != None: lastNode = node if data < node.data: node = node.left else: node = node.right newNode = BSTNode(data) if data < lastNode.data: lastNode.left = newNode else: lastNode.right = newNode def delete(self, data): foundNode = self.find(data) traverseNode = foundNode.right while traverseNode.left != None: traverseNode = traverseNode.left foundNode.data = traverseNode.data foundNode.right = traverseNode.right def find(self, data): node = self.bst while node != None: print node.data if node.data == data: return node if data < node.data: node = node.left else: node = node.right return None bst = BST(50) bst.insert(25) bst.insert(75) bst.insert(22) bst.insert(19) bst.insert(23) bst.insert(30) bst.insert(40) bst.insert(43) bst.find(23) bst.delete(25) print "-----" bst.find(40)<file_sep>#include <stdlib.h> #include <stdio.h> static int size = 0; struct listNode{ int data; struct listNode *next; }; /** * This function is used to add an object at the given position * and insert it to the list without changing the much of it. */ void insert(struct listNode **L, int position, int data){ // If the Position is -1, then don't even bother adding it if(position == -1) return; // Set up the new data struct listNode *newNode = malloc(sizeof(struct listNode)); newNode->data = data; newNode->next = NULL; if(*L == NULL){ *L = newNode; }else{ struct listNode **nextList = L; struct listNode *lastItem = NULL; int i=0; // Loop through the list while( *nextList != NULL){ // Check for the position if(i == position){ lastItem = *nextList; break; } nextList = &(*nextList)->next; i ++; } newNode->next = lastItem; *nextList = newNode; } // Increase the size size = size + 1; } /** * This function is used to delete an object of a given data */ void delete(struct listNode **L, int data){ struct listNode **nextList = L; struct listNode *laggingPointer = NULL; int isFound = 0; // Keep looping until the element is found while( *nextList != NULL){ // We have found the element if((*nextList)->data == data){ isFound = 1; nextList = &(*nextList)->next; break; } laggingPointer = *nextList; nextList = &(*nextList)->next; } // If element is not found return it if(!isFound) return; // Check if it is at the beginning of the lsit // or at the end if(laggingPointer == NULL){ *L = (*nextList); }else{ laggingPointer->next = *nextList; } // Decrease the size size = size - 1; } /** * This function serves to return the size of the list */ int getSize(){ return size; } /** * This list serves to find the location of the * first occurence of a given list */ int locate(struct listNode **L, int data){ struct listNode **nextList = L; int i = 0; // Keep looping until the element is found while( *nextList != NULL){ if((*nextList)->data == data){ return i; } nextList = &(*nextList)->next; i ++; } return -1; } /** * This function prints the list */ void printList(struct listNode ** L){ struct listNode *items = *L; while(items != NULL){ printf("%d ", items->data); items = items->next; } printf("\n"); } int main(int argc, char** argv) { struct listNode *list = NULL; insert(&list, 0, 5); insert(&list, 1, 4); insert(&list, 2, 3); insert(&list, 1, 2); delete(&list, 3); printList(&list); //printf("%d\n", locate(&list, 3)); return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> int left_child(int value, int length){ int left = 2 * (value + 1) - 1; if (left >= length){ return -1; } return left; } int right_child(int value, int length){ int right = 2*(value+1); if (right >= length){ return -1; } return right; } int parent(int value){ if(value <= 0) return 0; return (value - 1)/2; } void down_heap(int **heap, int value, int length){ int largestIndex, temp; int currPointer = value; while(left_child(currPointer, length) != -1){ largestIndex = left_child(currPointer, length); if (right_child(currPointer, length) != -1){ if((*heap)[right_child(currPointer, length)] > (*heap)[left_child(currPointer, length)]){ largestIndex = right_child(currPointer, length); } } if((*heap)[largestIndex] <= (*heap)[currPointer]){ break; } temp = (*heap)[largestIndex]; (*heap)[largestIndex] = (*heap)[currPointer]; (*heap)[currPointer] = temp; currPointer = largestIndex; } } void make_heap(int **heap, int length){ int value = length - 1; while (value != -1){ down_heap(&(*heap), parent(value),length); value = value - 1; } } int extract_max(int **heap, int *length){ int maxValue = (*heap)[0]; (*heap)[0] = (*heap)[*length - 1]; *length = *length - 1; if(*length <= 0) return maxValue; down_heap(&(*heap), 0, *length); return maxValue; } int main(int argc, char** argv) { int length = 4; int *heap = malloc(sizeof(int) * length); heap[0] = 3; heap[1] = 5; heap[2] = 2; heap[3] = 1; make_heap(&heap, length); for (int i = 0; i < 4; ++i) { printf("%d\n", extract_max(&heap, &length)); } return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> struct queueNode{ int data; struct queueNode *next; struct queueNode *last; }; void enqueue(struct queueNode **S, int data){ struct queueNode *newNode = malloc(sizeof(struct queueNode)); newNode->data = data; newNode->next = NULL; newNode->last = newNode; if(*S == NULL){ *S = newNode; }else{ (*S)->last->next = newNode; (*S)->last = newNode; } } int dequeue(struct queueNode **S){ int dequeueData = (*S)->data; struct queueNode *last = (*S)->last; *S = (*S)->next; if(*S != NULL) (*S)->last = last; return dequeueData; } int front(struct queueNode **S){ int dequeueData = (*S)->data; return dequeueData; } int main(int argc, char** argv) { struct queueNode *queue = NULL; enqueue(&queue, 5); enqueue(&queue, 4); enqueue(&queue, 3); enqueue(&queue, 2); printf("%d\n", dequeue(&queue)); printf("%d\n", dequeue(&queue)); printf("%d\n", dequeue(&queue)); printf("%d\n", dequeue(&queue)); return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> struct stackNode{ int data; struct stackNode *next; }; /** * This function serves to be a stack the next element on the stack. */ void Push(struct stackNode **S, int data){ struct stackNode *newNode = malloc(sizeof(struct stackNode)); newNode->data = data; newNode->next = *S; *S = newNode; } /** * This function gives the most top element */ int Top(struct stackNode **S){ return (*S) ->data; } /** * This functions serves to get the first element from the * stack and remove it */ int Pop(struct stackNode **S){ int popData = (*S)->data; *S = (*S)->next; return popData; } /** * This function prints out the current stack */ void printStack(struct stackNode **S){ struct stackNode *items = *S; while(items != NULL){ printf("%d ", items->data); items = items->next; } printf("\n"); } int main(int argc, char** argv) { struct stackNode *stack = NULL; Push(&stack, 5); Push(&stack, 4); Push(&stack, 3); Push(&stack, 2); printf("%d\n", Pop(&stack)); printStack(&stack); return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> struct bstNode{ int data; struct bstNode *left; struct bstNode *right; }; void insert(struct bstNode **bst, int data){ if(*bst == NULL){ struct bstNode *newNode = malloc(sizeof(struct bstNode)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; *bst = newNode; }else{ if(data > (*bst)->data){ insert(&(*bst)->right, data); }else{ insert(&(*bst)->left, data); } } } struct bstNode *find(struct bstNode **bst, int data){ if(*bst == NULL) return NULL; printf("%d\n", (*bst)->data); if((*bst)->data == data){ return (*bst); } if(data > (*bst)->data){ return find(&(*bst)->right, data); } return find(&(*bst)->left, data); } void delete(struct bstNode **bst, int data){ struct bstNode *nodeData = find(bst, data); if(nodeData == NULL) return; struct bstNode *smallestNode = nodeData->right; struct bstNode *lagNode = NULL; while(smallestNode->left != NULL){ lagNode = smallestNode; smallestNode = smallestNode->left; } if(lagNode != NULL){ lagNode->left = NULL; } nodeData->data = smallestNode->data; printf("%d\n", smallestNode->data); } int main(int argc, char** argv) { struct bstNode *bst = NULL; insert(&bst, 50); insert(&bst, 45); insert(&bst, 49); insert(&bst, 48); insert(&bst, 46); insert(&bst, 44); insert(&bst, 55); insert(&bst, 58); insert(&bst, 53); delete(&bst, 45); printf("-----\n"); find(&bst, 44); insert(&bst, 47); printf("-----\n"); find(&bst, 47); return 0; }<file_sep>#!/usr/bin/python import sys class StackNode: def __init__(self, data, next=None): self.data = data self.next = next def __str__(self): return str(self.data) class Stack: def __init__(self, data): self.stack = StackNode(data) def Push(self, data): if self.stack == None: self.stack = StackNode(data) return self.stack = StackNode(data, self.stack) def Pop(self): if(self.stack == None): return None data = self.stack.data self.stack = self.stack.next return data def Top(self): return self.stack.data s = Stack(5) s.Push(4) s.Push(3) s.Push(2) s.Push(1) print s.Top() print s.Top() print s.Top() print s.Top() print s.Top() <file_sep>#!/usr/bin/python import sys class ListNode: def __init__(self, data, next=None): self.data = data self.next = next def __str__(self): return str(self.data) class List: def __init__(self, data): self.list = ListNode(data) self.size = 1 def insert(self, data, position=-1): if(self.list == None): self.list = ListNode(data) return if (position == 0): self.list = ListNode(data, self.list) return # Get the temporary List tempList = self.list i = 1 # Loops through the temporary and then adds the element while tempList.next != None: if(position != -1 and i == position): break tempList = tempList.next i = i + 1 # Set the next data tempList.next = ListNode(data, tempList.next) # Increment the size self.size = self.size + 1 def delete(self, data): if(self.list == None): return # Get the temporary List tempList = self.list if(tempList.data == data): self.list = tempList.next return while tempList.next != None: if(tempList.next.data == data): tempList.next = tempList.next.next break tempList = tempList.next self.size = self.size - 1 def getSize(self): return self.size def find(self, data): tempList = self.list i = 0 while tempList.next != None: if tempList.data == data: return i i = i + 1 tempList = tempList.next return None def getList(self): return self.list L = List(5) L.insert(3) L.insert(2) L.insert(4,1) print L.find(5) tt = L.getList() while tt != None: print tt tt = tt.next <file_sep>#!/usr/bin/python import sys class QueueNode: def __init__(self, data, next=None): self.data = data self.next = next self.last = None def __str__(self): return str(self.data) class Queue: def __init__(self, data): self.queue = QueueNode(data) def enqueue(self, data): if self.queue == None: self.queue = QueueNode(data) return newQueue = QueueNode(data) if self.queue.next == None: self.queue.next = newQueue else: self.queue.last.next = newQueue self.queue.last = newQueue def dequeue(self): if(self.queue == None): return None data = self.queue.data self.queue = self.queue.next return data def front(self): return self.queue.data q = Queue(5) q.enqueue(4) q.enqueue(3) q.enqueue(2) q.enqueue(1) print q.dequeue() print q.dequeue() print q.dequeue() print q.dequeue() print q.dequeue()<file_sep>#include <stdlib.h> #include <stdio.h> struct TreeNodeInfo{ int data; int parent; }; static int length = 0; static int size = 0; void printTree(struct TreeNodeInfo *tree){ for (int i = 0; i < length; ++i) { printf("%d\n", tree[i].data); } } int find(struct TreeNodeInfo *tree, int data){ for (int i = 0; i < length; ++i) { if(tree[i].data == data){ return i; } } return -1; } void insertAtEmptySlot(struct TreeNodeInfo **tree, struct TreeNodeInfo newNode){ for (int i = 0; i < length; ++i) { if((*tree)[i].data == 0){ (*tree)[i] = newNode; return; } } } void insert(struct TreeNodeInfo **tree, int data, int parentData){ if((*tree) == NULL){ length = 3; (*tree) = (struct TreeNodeInfo *) malloc(sizeof(struct TreeNodeInfo) * length); for (int i = 0; i < length; ++i) { (*tree)[i].data = 0; } } if(size >= length){ length = length + 2; (*tree) = (struct TreeNodeInfo *) realloc(*tree, sizeof(struct TreeNodeInfo) * length); for (int i = size; i < length; ++i) { (*tree)[i].data = 0; } } struct TreeNodeInfo *newNode = malloc(sizeof(struct TreeNodeInfo)); newNode->data = data; newNode->parent = -1; if(size != 0){ int index = find(*tree, parentData); if(index == -1) return; newNode->parent = index; } insertAtEmptySlot(&(*tree), *newNode); size = size + 1; } void delete(struct TreeNodeInfo **tree, int data){ for (int i = 0; i < length; ++i) { if((*tree)[i].data == data){ (*tree)[i].data = 0; (*tree)[i].parent = -1; size = size - 1; return; } } } int findParent(struct TreeNodeInfo **tree, int data){ for (int i = 0; i < length; ++i) { if((*tree)[i].data == data){ int parent = (*tree)[i].parent; if( parent == -1) return -1; return (*tree)[parent].data; } } return -1; } void findChild(struct TreeNodeInfo **tree, int parentData){ int index = find(*tree, parentData); for (int i = 0; i < length; ++i) { if((*tree)[i].parent == index){ printf("%d ", (*tree)[i].data); } } printf("\n"); } int main(int argc, char** argv) { struct TreeNodeInfo *tree = NULL; insert(&tree, 5, -1); insert(&tree, 3, 5); insert(&tree, 4, 5); delete(&tree, 4); insert(&tree, 2, 5); printf("%d\n", findParent(&tree, 2)); findChild(&tree, 5); return 0; }
2c4efa7a6803f4a326009189d3076e1628c55cac
[ "C", "Python" ]
11
Python
chanyeoh/datastructure
f64bd64e8f7b3d9de4b8ef70fa8fc174cd2edb38
eb26332d4071d426865a3cd0b8a249d445dde5f6
refs/heads/main
<repo_name>leiberj/leiber_virtell_final_repository<file_sep>/leiber_virtell_final_project_repository/button_tempo.X/screen_debouncer.h /* * File: debouncer.h * Author: joshu * * Created on October 11, 2020, 1:42 PM */ #ifndef SCREEN_DEBOUNCER_H #define SCREEN_DEBOUNCER_H #include <inttypes.h> extern void init_screen_debounce_FSM(); extern uint8_t tickFct_screen_debounce(uint8_t z); #endif /* DEBOUNCER_H */ <file_sep>/leiber_virtell_final_project_repository/button_tempo.X/button_detect.c char screen_pressed(uint8_t pressed, uint16_t x, uint16_t y) { if(pressed) { uint8_t count; for(count = 0; count < 20; count++) { if(x > xstart[count] && y > ystart[count] && x < xend[count] && y < yend[count]) { return button_chars[count]; } } } return '$'; } <file_sep>/leiber_virtell_final_project_repository/DDS_Isolated.X/dds_test.c /* * File: dds_test.c - test DDS code * Author: <NAME> * * Created on October 27, 2020, 8:58 PM */ #include <stdio.h> #include <stdlib.h> #include <xc.h> #include <plib.h> #include "ztimer.h" #include "dds.h" #include "dds_fsm.h" // pragmas #include "config.h" /* * */ #define SYSCLK 40000000UL #define PBCLK 40000000UL uint8_t dds_pd = 10; int main() { uint32_t dds_elapsedTime = dds_pd; uint32_t timerPeriod = 1; SYSTEMConfigPerformance(SYSCLK); CM1CON = 0; CM2CON = 0; ANSELA = 0; ANSELB = 0; // why disable comparators? not sure mPORTASetPinsDigitalOut(BIT_0); // this was in Tahmid's example; not sure why // dds_init(); // INTEnableSystemMultiVectoredInt(); // dds_on(440); //Z timer init zTimerSet(timerPeriod); zTimerOn(); init_dds_fsm(); uint16_t count; while (1) { count++; //if(dds_elapsedTime >= dds_pd) { if(count > 80){ tickFct_dds(1); count = 0; } // dds_elapsedTime = 0; //} // while (!zTimerReadFlag()) { // } // dds_elapsedTime += timerPeriod; } return (EXIT_SUCCESS); } <file_sep>/leiber_virtell_final_project_repository/button_tempo.X/main.c /* * File: main.c * Author: leibe * * Created on November 23, 2020, 12:25 PM */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <plib.h> <<<<<<< Updated upstream ======= <<<<<<< HEAD #include "config.h" //PRAGMAS...DO NOT FORGET PRAGMAS ======= >>>>>>> Stashed changes #include "ztimer.h" #include "config.h" #include "button_tempo_controller.h" #include "screen_debouncer.h" #include "debouncer_tempo.h" #include "button_control.h" #include "Adafruit_2_4_LCD_Serial_Library/tft_master.h" #include "Adafruit_2_4_LCD_Serial_Library/tft_gfx.h" #include "adc_intf.h" #include "ts_lcd.h" #define XM AN0 #define YP AN1 <<<<<<< Updated upstream ======= >>>>>>> 1999389e80eb597938e2d55401f4daa4b1dfd22b >>>>>>> Stashed changes /* * */ void main() { uint32_t button_elapsedTime = 75; uint32_t debounce_tempo_elapsedTime = 50; uint32_t dummy; uint8_t tempo_pressed; PORTSetPinsDigitalOut(IOPORT_B, BIT_4); //Touchscreen init configureADC(); SYSTEMConfigPerformance(PBCLK); ts_lcd_init(); //tempo button fsm init_button_fsm(); //Init debouncer init_debounce_tempo_FSM(); init_screen_debounce_FSM(); //Init buttons init_buttons(); INTEnableSystemMultiVectoredInt(); zTimerSet(25); zTimerOn(); while(1) { if(debounce_tempo_elapsedTime >= 50) { tempo_pressed = tickFct_debounce_tempo(!read_tempo_button()); debounce_tempo_elapsedTime = 0; } // if(read_tempo_button()) { // PORTWrite(IOPORT_B, BIT_4); // } // else { // PORTClearBits(IOPORT_B, BIT_4); // } if(button_elapsedTime >= 75) { dummy = tickFct_button(tempo_pressed, zTimerReadms()); button_elapsedTime = 0; } while(!zTimerReadFlag()){ } button_elapsedTime += 25; debounce_tempo_elapsedTime += 25; } }
b776e5035bde1b2ee030f4c2bc07e1e42b065581
[ "C" ]
4
C
leiberj/leiber_virtell_final_repository
fcb9b977179601ac440c525e7e6073535c054e0c
ea197e9e71c195d74818678a7c06627317c54a7e
refs/heads/main
<file_sep>var dog,sadDog,happyDog; var feed, addFood, nameInp, nameSubmit; var storeName; var resetB; var foodS, db; var lastFed; function preload(){ sadDog=loadImage("Images/Dog.png"); happyDog=loadImage("Images/happydog.png"); milk = loadImage("Images/Milk.png"); } function setup() { createCanvas(1000,400); db = firebase.database(); db.ref("foodStock").on("value", function(data) { foodS = data.val(); }); dog=createSprite(800,200,150,150); dog.addImage(sadDog); dog.scale=0.15; feed = createButton("Feed Dog"); feed.position(1100, 95); feed.mousePressed(feedDog); addFood = createButton("Add Food"); addFood.position(1020, 95); addFood.mousePressed(foodSupply); nameInp = createInput().attribute("placeholder", "Dog's Name"); nameInp.position(220, 95); nameSubmit = createButton("Submit"); nameSubmit.position(400, 95); nameSubmit.mousePressed(submit); resetB = createButton("Reset"); resetB.position(680, 450); resetB.mousePressed(reset); } function draw() { var x=50; var y=50; background(46,139,87); drawSprites(); fill("white"); textSize(24); text(foodS, 500, 200); if(foodS!=0) { for(var i = 0; i<foodS; i++){ if(i%10===0) { x = 50; y+=60; } image(milk, x, y, 50, 50); x+=30; } } if(storeName!=null) { fill("white"); textSize(24); text(storeName, 765, 290); } if(lastFed!=undefined) { if(lastFed>11) { textAlign(CENTER); text("Last Fed : " + lastFed + "PM", 500, 40); } else { textAlign(CENTER); text("Last Fed : " + lastFed + "PM", 500, 40); } } } function feedDog() { if(foodS>0) { foodS-=1; db.ref("/").update({foodStock:foodS, feedTime:hour()}); db.ref("feedTime").on("value", function(data){ lastFed = data.val(); }) } } function foodSupply() { if(foodS<40) { foodS++; db.ref("/").update({foodStock:foodS}); } } function submit() { storeName = nameInp.value(); db.ref("/").update({ name:storeName }) nameInp.hide(); nameSubmit.hide(); } function reset() { foodS = 0; storeName = ""; lastFed = undefined; db.ref("/").update({foodStock:foodS, name:storeName}); window.location.reload(); }
8adac2264fbd9f4a3f3c808a143a97ef41976fd1
[ "JavaScript" ]
1
JavaScript
JohnJoseph2007/VirtualPet2
a32054be89f340b5adc680a536d1683913ff9bb1
b2567d94dc47d15ddce4dd8f0e768f8a0ca4c56e
refs/heads/main
<file_sep>import React from 'react' import Image from 'react-bootstrap/Image'; const right = () => { return ( <div> <Image src="./img/Chair.jpg " thumbnail style= {{height:"50%"}} /> </div> ) } export default right <file_sep> import React from 'react'; import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Row , Col} from "react-bootstrap"; import Menu from "./components/Menu"; import Left from "./components/Left"; import Right from "./components/Right"; function App() { return ( <div > <Menu/> <Row className ="part"> <Col> <Left/></Col> <Col> <Right/></Col> </Row> </div> ); } export default App;
1e68665f4ffed9b422911d6035c666bf7e85b6a6
[ "JavaScript" ]
2
JavaScript
amani156/react
d0551a5e819ff98ec473baf29233ac0221d47396
d057f9c3f0fd903e264e1cf91e135277e32e66b6
refs/heads/master
<repo_name>monk-ee/backburner<file_sep>/backburner.py #!/usr/bin/python __author__ = 'monkee' from datetime import date import sys import logging from pprint import pprint import boto.sqs, boto.ec2 import yaml from boto.sqs.message import RawMessage import json def terminationAction(ec2_instance_id,config): print "terminate" #take some action - AutoScalingGroupName print ec2_instance_id['EC2InstanceId'] print ec2_instance_id['AutoScalingGroupName'] ec2_conn = boto.ec2.connect_to_region("us-west-2",aws_access_key_id=config['s3']['aws_access_key'], aws_secret_access_key=config['s3']['aws_secret_key']) reservations = ec2_conn.get_all_instances(instance_ids=[str(ec2_instance_id['EC2InstanceId'])]) instances = [i for r in reservations for i in r.instances] for i in instances: pprint(i.__dict__) def launchAction(ec2_instance_id,config): #take some action print "launch" print ec2_instance_id['EC2InstanceId'] print ec2_instance_id['AutoScalingGroupName'] ec2_conn = boto.ec2.connect_to_region("us-west-2",aws_access_key_id=config['s3']['aws_access_key'], aws_secret_access_key=config['s3']['aws_secret_key']) reservations = ec2_conn.get_all_instances(instance_ids=[str(ec2_instance_id['EC2InstanceId'])]) instances = [i for r in reservations for i in r.instances] for i in instances: pprint(i.__dict__) def main(argv): tag = '' checkout_dir = '' ssh_key = '' timestamp = str(date.today()) #get configuration try: configStr = open('config.yml','r') config = yaml.load(configStr) except (OSError, IOError), emsg: print('Cannot find or parse config file: ' + str(emsg)) sys.exit(2) #logging for debug really you can set to logging.INFO to chill it out logging.basicConfig(filename=config['logfile'],level=logging.INFO) #try: # tag = argv[1] # ip = argv[2] #except BaseException, emsg: # logging.warning(timestamp + ': Missing Arguments: ' + str(emsg) + ' : '+str(argv)) # sys.exit(2) try: sqs = boto.sqs.connect_to_region("us-west-2",aws_access_key_id=config['s3']['aws_access_key'], aws_secret_access_key=config['s3']['aws_secret_key']) queue = sqs.get_queue(config['sqs']['name']) queue.set_message_class(RawMessage) print queue.count() for msg in queue.get_messages(1,visibility_timeout=10): single_message = json.loads(msg.get_body()) message = json.loads(single_message['Message']) #clean up messages on setup if message['Event'] == "autoscaling:TEST_NOTIFICATION": queue.delete_message(msg) elif message['Event'] == "autoscaling:EC2_INSTANCE_TERMINATE": terminationAction(message,config) elif message['Event'] == "autoscaling:EC2_INSTANCE_LAUNCH": launchAction(message,config) except BaseException, emsg: logging.warning(timestamp + ': cannot get messages: ' + str(emsg)) sys.exit(2) sys.exit() if __name__ == "__main__": main(sys.argv)<file_sep>/README.md backburner ========== Dynamic Autoscale Firewalling
f78cf80cf4b2fbda963725ef909bb27f8a5fa8af
[ "Markdown", "Python" ]
2
Python
monk-ee/backburner
7225488ef5a077e92c515c08cf251b688f791cfc
d66ce1a2f0a382064fcd000acb3daaac788b0c7d
refs/heads/master
<repo_name>Aminzare86/Csharp<file_sep>/CalculatorTestLib/UnitTest1.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using CalculatorTestLib; using CalculatorLib; using System.Diagnostics; namespace CalculatorTestLib { [TestClass] public class UnitTest1 { [TestMethod] public void SimpleDisply() { //Arrange Calculator sut = new Calculator(); //Act sut.PowerOn(); //Assert Assert.AreEqual(0,sut.Display); } [TestMethod] public void OneDigitInDisplay() { //Arrange var sut = new Calculator(); //Act sut.Press("7"); //Assert Assert.AreEqual(7, sut.Display); } [TestMethod] public void TwoDigitInDisplay() { //Arrange var sut = new Calculator(); //Act sut.Press("5"); sut.Press("2"); //Assert Assert.AreEqual(52, sut.Display); } [TestMethod] public void Add12and25() { //Arrange var sut = new Calculator(); //Act sut.Press("1"); sut.Press("2"); sut.Press("+"); sut.Press("2"); sut.Press("5"); sut.Press("="); //Assert Assert.AreEqual(37, sut.Display); } } } <file_sep>/TesttestLib/UnitTest1.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestLib; namespace TesttestLib { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Class1 amin = new Class1(); Class2 zare = new Class2(); } } } <file_sep>/FakturaLib/Person.cs using System; namespace FakturaLib { public class Person { public string Street { get; set; } public string Name { get; set; } } } <file_sep>/EmployeeLib/EmployeeConverter.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace EmployeeLib { public class Converter { public string EmployeeConverter(string input) { string pattern = @"\""""(\w+) (\w+)\"""" (\d{1,3}) (\d*.\d*) (.*)"""; Match match = Regex.Match(input, pattern); var Lön = decimal.Parse(match.Groups[4].Value, CultureInfo.InvariantCulture); var telefon = match.Groups[5].Value; var age = int.Parse(match.Groups[3].Value); var year = DateTime.Now.AddYears(-age).Year; return $"{match.Groups[2].Value}, {match.Groups[1].Value} (Lön: {Lön} SEK) Telefon:{telefon} Födelseår:{year}"; } } } <file_sep>/Parter/Part.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Parter { public class Part { public Part(string namn,string juridisktId) { this.Namn=namn; this.JuridisktId = juridisktId; } public string Namn { get; set; } public string JuridisktId { get; set; } public override string ToString() { return $"{Namn} ({JuridisktId})"; } } } <file_sep>/TärningsLib/TärningsSpel.cs using System; namespace TärningsLib { public class TärningsSpel { private int v; public TärningsSpel(int v) { this.v = v; } public string Feedback { get { return $"You are Winner."; } } } } <file_sep>/Student/Student.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Student { public class Student { private string name; private string email; private string Adress; private string Bil; public int countStudy=0; public Student() { } public Student(string Adress, string Bil) { this.Adress = Adress; this.Bil = Bil; } public string Name { get { return name; } set { name = value; } } public string Email { get { return email; } set { email = value; } } public void StudentInfo() { Console.WriteLine(name + "\n" + email); Console.WriteLine(Adress + "\n" + Bil); } public void StudyHarder() { countStudy++; if (countStudy < 3) { Console.WriteLine("you have to study harder"); } else { Console.WriteLine("Amin need to rest"); } } } } <file_sep>/SchoolTestsLib/SchoolSystemTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SchoolLib; namespace SchoolTestsLib { [TestClass] public class SchoolSystemTest { [TestMethod] public void TestMethod1() { var sut = new SchoolSystem(); sut.AddClass("spo16",20); sut.AddClass("spo15", 40); sut.AddClass("spo16", 10); Assert.AreEqual(2,sut.ClassCount); Assert.AreEqual(70, sut.StudentCount); } } } <file_sep>/regexonsole/Program.cs using System; using System.Text.RegularExpressions; public class Example { public static object Assert { get; private set; } public static void Main() { string pattern = @"\""?([^\""""]*)\""?"" (\d{2}) (\d{5}.\d{2}) (\d{10})"; string input = @"""<NAME>"" 46 35000.00 0706186120"; //string output = "<NAME> (Lön: 35000,00 SEK) Telefon:070-6186120 Födelseår:1971"; Match m = Regex.Match(input, pattern); var inputName= m.Groups[1].Value; var inputÅlder = m.Groups[2].Value; var inputLön = m.Groups[3].Value; var inputtel = m.Groups[4].Value; var outputName = Convert.ToString(); Console.ReadLine(); } }<file_sep>/OOPConsoleApp/Lion.cs namespace OOPConsoleApp { internal class Lion : Animal { public Lion() { } } }<file_sep>/PracticLib/PersonalInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace PracticLib { public class PersonalInfo { public static string Convert(string content) { string pattern2 = @"(\d{4})-(\w+-\w+);(\w+ \w+);(\w+-\w+);"; Match m = Regex.Match(content, pattern2); string convertPart1 = m.Groups[1].Value; string convertPart3 = m.Groups[3].Value; string convertPart4 = m.Groups[4].Value; var age = int.Parse(m.Groups[1].Value); var year = DateTime.Now.AddYears(-age).Year; string test = $"{convertPart3} är {year} år gammal och har telefonumret {convertPart4}"; return test; } public static string Transform(string name, string Phone, string personNr) { string pattern = @"(\d{3})(\d{7})"; Match m = Regex.Match(Phone, pattern); string Phonepart1 = m.Groups[1].Value; string Phonepart2 = m.Groups[2].Value; string editPhone = Phonepart1 + "-" + Phonepart2; string PershoInfo = personNr + ";" + name + ";" + editPhone + ";"; return PershoInfo; } } } <file_sep>/OOPConsoleApp/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOPConsoleApp { class Program { static void Main(string[] args) { StudentDemo(); InheritanceDemo(); Console.ReadLine(); } private static void InheritanceDemo() { Animal anAnimal = new Animal(); anAnimal.Eat(); Lion aLion = new Lion(); aLion.Eat(); } private static void StudentDemo() { var Amin = new Student(); Amin.Name = "<NAME>"; Amin.Email = "<EMAIL>"; Amin.TooTired += Amin_TooTired; Amin.StudyHarder(); Amin.StudyHarder(); Amin.StudyHarder(); //Console.WriteLine("Hello word {0}.",Name); Console.WriteLine($"Hello word {Amin}"); Console.ReadLine(); } private static void Amin_TooTired(object sender, EventArgs e) { int x = 5; Console.WriteLine("Student need to rest{0}.",x); Console.ReadLine(); } } } <file_sep>/FakturaLibb/Faktura.cs namespace FakturaLibb { public class Faktura { public Faktura(Part kund, decimal total) { _kund = kund; _total = total; } private Part _kund; private decimal _total; public override string ToString() { return $"{_kund.Namn} ska betala {_total} SEK"; } } }<file_sep>/FakturaLib/Accounting.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FakturaLib { public class Accounting { public static Faktura GenereraFaktura(Beställning beställning) { var enFaktura = new Faktura(beställning.Person); Console.WriteLine(beställning.Rader.Sum(rad => rad.Antal * rad.Product.Price)); return enFaktura; } } } <file_sep>/TwoFileProductApp/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TwoFilesProductLib; namespace TwoFileProductApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnAmountsFile_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); var lines = File.ReadAllLines(openFileDialog1.FileName); foreach (var line in lines) { listBox1.Items.Add(line); } } private void btnQuantitiesFile_Click(object sender, EventArgs e) { openFileDialog2.ShowDialog(); var lines = File.ReadAllLines(openFileDialog2.FileName); foreach (var line in lines) { listBox2.Items.Add(line); } var content1 = File.ReadAllText(openFileDialog1.FileName); var content2 = File.ReadAllText(openFileDialog2.FileName); var result = TwoFilesProduct.Transform(content1, content2); var stringReader = new StringReader(result); while (true) { var line = stringReader.ReadLine(); if (line == null) break; listBox3.Items.Add(line); } } private void btnSaveFile_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(); var content1 = File.ReadAllText(openFileDialog1.FileName); var content2 = File.ReadAllText(openFileDialog2.FileName); var result = TwoFilesProduct.Transform(content1, content2); File.WriteAllText(saveFileDialog1.FileName, result); } } } <file_sep>/FakturaLib/Beställning.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLib { public class Beställning { public Beställning(Person person) { Person = person; } public void LäggtillRad(BeställningsRad rad) { Rader.Add(rad); } internal Person Person; public List<BeställningsRad> Rader = new List<BeställningsRad>(); } } <file_sep>/WindowsFormsApp5/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; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string Name = NameBox.Text; string personNr = PersonNrBox.Text; var personNrSub = personNr.Substring(9, 1); int personNrToInt = Convert.ToInt32(personNrSub) % 2; if (personNrToInt == 1) { ShowLbl.Text=$"God morgon herr {Name}"; } else { ShowLbl.Text=$"God morgon fröken { Name}"; }; } } } <file_sep>/TwoFilesProductLib/TwoFilesProduct.cs using System; using System.Globalization; using System.IO; namespace TwoFilesProductLib { public class TwoFilesProduct { public static string Transform(string input1, string input2) { var stringReader1 = new StringReader(input1); string output = ""; while (true) { var line1 = stringReader1.ReadLine(); if (line1 == null) break; var stringReader2 = new StringReader(input2); while (true) { var line2 = stringReader2.ReadLine(); if (line2 == null) break; var amount = decimal.Parse(line1, CultureInfo.InvariantCulture); var qty = int.Parse(line2); var product = amount * qty; // if you want run test you have to write /n instead for {Environment.NewLine} output += $"{line1}x{line2}={product.ToString(CultureInfo.InstalledUICulture)}{Environment.NewLine}"; } } return output; } } } <file_sep>/SIEConsoleApp/Program.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using SIELib; namespace SIEConsoleApp { class Program { static void Main(string[] args) { var sut = new Class1(); sut.Räknare(); Console.ReadLine(); } } } <file_sep>/transformeraTvåFiler/transformerFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace transformeraTvåFiler { class transformerFile { } } <file_sep>/ByggaHus/Rom.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ByggaHus { class Rom { } } <file_sep>/FakturaLibb/Part.cs using System; namespace FakturaLibb { public class Part { public string Namn { get; set; } public string JuridisktId { get; set; } } } <file_sep>/TotalKontoLib/Class1.cs  using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace TotalKontoLib { public class Class1 { public void Räknare() { var accountsSums =File.ReadAllLines(@"MATTIAS00_SIE4 2015-09-01 - 2016-08-31.SE.txt"). Where(line => line.Contains("#TRANS")). GroupBy(line => Regex.Match(line, @"#TRANS (\d{4}) {} (-?\d*.\d*)").Groups[1].Value). Select(e => new { Account = e.Key, Total = e.Sum(x => decimal.Parse(Regex.Match(x, @"#TRANS (\d{4}) {} (-?\d*.\d*)").Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture)) }). OrderBy(e => e.Account); foreach (var item in accountsSums) { Console.WriteLine($"{item.Account} {item.Total}"); }; } } }<file_sep>/TwoFileProductTestsLib/TwoFileProductTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TwoFilesProductLib; namespace TwoFileProductTestsLib { [TestClass] public class TwoFileProductTests { [TestMethod] public void Two_Rows_In_Each_File() { string input1 = "12.50\n17.50\n"; string input2 = "2\n10\n"; string expected = "12.50x2=25.00\n12.50x10=125.00\n17.50x2=35.00\n17.50x10=175.00\n"; string output = TwoFilesProduct.Transform( input1, input2); Assert.AreEqual(expected, output); } [TestMethod] public void Two_Rows_Times_Three() { string input1 = "12.50\n17.50\n20.00\n"; string input2 = "2\n10\n"; string expected = "12.50x2=25.00\n12.50x10=125.00\n17.50x2=35.00\n17.50x10=175.00\n20.00x2=40.00\n20.00x10=200.00\n"; string output = TwoFilesProduct.Transform(input1, input2); Assert.AreEqual(expected, output); } } } <file_sep>/ReadMe.txt # Övning Tänk dig på två filer med följande innehåll: ```txt 12.50 17.50 ``` ```txt 2 10 ``` Bygg en lösning där man kan välja var och en av dessa två filer och generera en ny fil med följande innehåll: ```txt 12.50x2=25.00 12.50x10=125.00 17.50x2=35.00 17.50x10=175.00 ``` 1. Unit Testing av en klass som utför transformationen 1. En Windows Forms app med användargränssnittet <file_sep>/SchoolLib/Class.cs using System; namespace SchoolLib { public class Class { public int NumberOfStudent { get; set; } public string Name { get; set; } } } <file_sep>/SchoolCount/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolCount { class Program { static void Main(string[] args) { School school = new School(); Class class1 = new Class(34); Class class2 = new Class(23); Class class3 = new Class(43); school.Classes.Add(class1); school.Classes.Add(class1); school.Classes.Add(class1); Console.WriteLine($"There are {school.NumberOfStudents} number of students in this school."); Console.ReadLine(); } } } <file_sep>/PartTestLib/PartTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Parter; namespace PartTestLib { [TestClass] public class PartTest { [TestMethod] public void TestMethod1() { var sut = new Part("<NAME>","19860112-1513"); Assert.AreEqual("<NAME> (19860112-1513)",sut.ToString()); } } } <file_sep>/FakturaWinApp/Rad.cs using FakturaLibb; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FakturaWinApp { internal class Rad { public Produkt Produkt { get; set; } public int Antal { get; set; } public override string ToString() { return $"{Produkt.Namn} {Antal} {Produkt.Pris} {Antal * Produkt.Pris}"; } } } <file_sep>/PershonNumberLib/PersonnummerDigitFinder.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PershonNumberLib { public class PersonnummerDigitFinder { private string pershonNumberInput; public string LastDigit { get { var total = 0; for (int pos = 0; pos < pershonNumberInput.Length; pos++) { var digit = int.Parse(pershonNumberInput[pos].ToString()); if (pos % 2 == 0) { digit *= 2; if (digit > 9) digit -= 9; } total += digit; } var lastDigit = (10 - (total % 10)).ToString(); return lastDigit; } } public void Proses(string PershonNumberInput) { this.pershonNumberInput = PershonNumberInput; } } } <file_sep>/RegexProject/UnitTest1.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text.RegularExpressions; namespace RegexProject { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { //\"?([^\""]*)\"?" (\d{2}) (\d{5}.\d{2}) (\d{10}) string pattern = @"\""?([^\""""]*)\""?"" (\d{2}) (\d{5}.\d{2}) (\d{10})"; //"<NAME>" 46 35000.00 0706186120 string input = @"""<NAME>"" 46 35000.00 0706186120"; Match m = Regex.Match(input, pattern); Assert.AreEqual("<NAME>", m.Groups[1].Value); Assert.AreEqual("46", m.Groups[2].Value); Assert.AreEqual("35000.00", m.Groups[3].Value); Assert.AreEqual("0706186120", m.Groups[4].Value); } } } <file_sep>/SIELib/Class1.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace SIELib { public class Class1 { public void Räknare() { var accounts = new Dictionary<string, decimal>(); var streamReader = File.OpenText(@"SIE-bearbetning.txt"); var totalLine = 0; while (true) { var Line = streamReader.ReadLine(); if (Line == null) break; string pattern = @"(#TRANS) (\d{4}) {.*} (-?\d*.\d*)"; var match = Regex.Match(Line, pattern); if (match.Success) { var accountId = match.Groups[1].Value; var amount = decimal.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture); if (accounts.ContainsKey(accountId)) { accounts[accountId] += amount; totalLine++; } else { accounts[accountId] = amount; totalLine++; } } } Console.WriteLine($"du har { totalLine} rader"); Console.WriteLine($"totalen av de belopp: { accounts.Sum(entry => entry.Value)}"); } } } <file_sep>/FakturaLib/BeställningsRad.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLib { public class BeställningsRad { public BeställningsRad(Product product, int antal) { Product = product; Antal = antal; } internal Product Product; internal int Antal; } } <file_sep>/FakturaWinApp/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 FakturaLibb; namespace FakturaWinApp { public partial class Form1 : Form { private FakturaSystem fakturaSystem = new FakturaSystem(); private Part part; public Form1() { InitializeComponent(); } private void btnSkapaPart_Click(object sender, EventArgs e) { part = fakturaSystem.SkapaPart(txtNamn.Text, txtJuridisktId.Text); } private void Form1_Load(object sender, EventArgs e) { cbValjProdukt.Items.Add(fakturaSystem.SkapaProdukt("Teddy", 79M)); cbValjProdukt.Items.Add(fakturaSystem.SkapaProdukt("Ponny", 15000M)); } private void btnNyRad_Click(object sender, EventArgs e) { lbRader.Items.Add( new Rad { Produkt = (Produkt)cbValjProdukt.SelectedItem, Antal = int.Parse(cbAntal.SelectedItem.ToString()) } ); } private void btnLäggBeställning_Click(object sender, EventArgs e) { var beställning = fakturaSystem.SkapaBeställning(part); foreach (Rad rad in lbRader.Items) { beställning.NyRad(rad.Produkt, rad.Antal); } var faktura = beställning.GenereraFaktura(); MessageBox.Show(faktura.ToString()); } } } <file_sep>/Student/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Student; namespace Student { class Program { static void Main(string[] args) { Student Amin = new Student(); Student AminInfo = new Student(Adress: "Fyrspanssgata172", Bil: "audi"); Student Aminsstudy = new Student(); Student Aminsrest = new Student(); Amin.Name = "<NAME>"; Amin.Email = "<EMAIL>"; Amin.StudentInfo(); AminInfo.StudentInfo(); Aminsstudy.StudyHarder(); Aminsstudy.StudyHarder(); Aminsstudy.StudyHarder(); Console.ReadKey(); } } } <file_sep>/FakturaApp1/Program.cs using FakturaLib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FakturaApp1 { class Program { static void Main(string[] args) { var kund = new Person(); var Faktura = new Faktura(); Faktura.Kund = kund; Console.WriteLine("Enter your Adress : "); var adress = Console.ReadLine(); Faktura.Street = adress; Console.WriteLine("Enter your Products name : "); var productsName = Console.ReadLine(); Console.WriteLine("Enter your Products price : "); var productsPrice = Convert.ToDecimal(Console.ReadLine()); var product = new Product(productsName, productsPrice); Console.WriteLine("Enter your antal Products : "); var antalProducts = Convert.ToInt32(Console.ReadLine()); var enNyBeställning = new Beställning(kund); var enNyRad = new BeställningsRad(product, antalProducts); enNyBeställning.LäggtillRad(enNyRad); var enNyFaktura = Accounting.GenereraFaktura(enNyBeställning); Console.ReadLine(); } } } <file_sep>/FakturaLibb/Produkt.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLibb { public class Produkt { public Produkt(string namn, decimal pris) { if (pris < 0) throw new InvalidOperationException("Pris måste vara större än 0"); this.Namn = namn; this.Pris = pris; } public string Namn { get; set; } public decimal Pris { get; set; } public override string ToString() { return this.Namn; } } } <file_sep>/FakturaLibb/Beställning.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FakturaLibb { public class Beställning { public Beställning(Part beställare) { this.Beställare = beställare; } private Part Beställare; private List<Tuple<Produkt, int>> rader = new List<Tuple<Produkt, int>>(); public decimal Total { get { return rader.Sum(rad => rad.Item1.Pris * rad.Item2); } } public void NyRad(Produkt produkt, int antal) { rader.Add(new Tuple<Produkt, int>(produkt, antal)); } public Faktura GenereraFaktura() { return new Faktura(Beställare, this.Total); } } } <file_sep>/transformeraTvåFiler/Form1.cs using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace transformeraTvåFiler { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); var lines = File.ReadAllLines(openFileDialog1.FileName); foreach (var line in lines) { listBox1.Items.Add(line); } } private void button2_Click(object sender, EventArgs e) { openFileDialog2.ShowDialog(); var lines = File.ReadAllLines(openFileDialog2.FileName); foreach (var line in lines) { listBox2.Items.Add(line); } var content1 = File.OpenText(openFileDialog1.FileName); var content2 = File.OpenText(openFileDialog2.FileName); ListBoxFileProduct( ref content1, content2); } private void ListBoxFileProduct( ref StreamReader content1, StreamReader content2) { var kurs = ""; ArrayList studentsList = new ArrayList(); var numerrofWord = 0; var studentname = ""; var filesWord = ""; while (true) { string pattern2 = @"([^""]*);(\d{4}-\d{2}-\d{2});(\d{4}-\d{2}-\d{2})"; var Line2 = content2.ReadLine(); if (Line2 == null ) break; Match match2 = Regex.Match(Line2, pattern2); kurs = match2.Groups[1].Value; var date1 = match2.Groups[2].Value; DateTime dt = Convert.ToDateTime(date1); var date2 = match2.Groups[3].Value; DateTime dt2 = Convert.ToDateTime(date2); var numberOfDays = (dt2 - dt).TotalDays; string pattern = @"(\w*)"; RegexOptions options = RegexOptions.Multiline; while (true) { var Line = content1.ReadLine(); if (Line == null) { content1 = File.OpenText(openFileDialog1.FileName); break; } foreach (Match m in Regex.Matches(Line, pattern, options)) { if (kurs == filesWord) { studentsList.Add(studentname); } filesWord = m.Value; if (filesWord == "C") { filesWord += "#"; } numerrofWord = m.Index; if (numerrofWord == 0) { studentname = filesWord; } } } numerrofWord = 0; var kursStudent = ""; foreach (object item in studentsList) { kursStudent += item.ToString() + ";"; } listBox3.Items.Add($"Kursen {kurs} pågår i " + $"{numberOfDays} dagar med följande deltagare:{kursStudent}"); studentsList.Clear(); } } private void SaveFileProduct(ref string output, ref StreamReader content1, StreamReader content2) { var kurs = ""; ArrayList studentsList = new ArrayList(); var numerrofWord = 0; var studentname = ""; var filesWord = ""; while (true) { string pattern2 = @"([^""]*);(\d{4}-\d{2}-\d{2});(\d{4}-\d{2}-\d{2})"; var Line2 = content2.ReadLine(); if (Line2 == null /*|| Line==null*/) break; Match match2 = Regex.Match(Line2, pattern2); kurs = match2.Groups[1].Value; var date1 = match2.Groups[2].Value; DateTime dt = Convert.ToDateTime(date1); var date2 = match2.Groups[3].Value; DateTime dt2 = Convert.ToDateTime(date2); var numberOfDays = (dt2 - dt).TotalDays; string pattern = @"(\w*)"; RegexOptions options = RegexOptions.Multiline; while (true) { var Line = content1.ReadLine(); if (Line == null) { content1 = File.OpenText(openFileDialog1.FileName); break; } foreach (Match m in Regex.Matches(Line, pattern, options)) { if (kurs == filesWord) { studentsList.Add(studentname); } filesWord = m.Value; if (filesWord == "C") { filesWord += "#"; } numerrofWord = m.Index; if (numerrofWord == 0) { studentname = filesWord; } } } numerrofWord = 0; var kursStudent = ""; foreach (object item in studentsList) { kursStudent += item.ToString() + ";"; } output += $"Kursen {kurs} pågår i " + $"{numberOfDays} dagar med följande deltagare:{kursStudent}{Environment.NewLine}"; studentsList.Clear(); } } private void button3_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(); string output = ""; var content1 = File.OpenText(openFileDialog1.FileName); var content2 = File.OpenText(openFileDialog2.FileName); SaveFileProduct(ref output, ref content1, content2); File.WriteAllText(saveFileDialog1.FileName, output); } } } <file_sep>/SIETest/UnitTest1.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SIELib; namespace SIETest { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var sut = new Class1(); sut.Räknare(); Assert.AreEqual("totalen av de belopp: 1822244",$"totalen av de belopp: { accounts.Sum(entry => entry.Value)}"); } } } //du har 497 rader //totalen av de belopp: 1822244<file_sep>/WindowsFormsApp6/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void button2_Click(object sender, EventArgs e) { openFileDialog2.ShowDialog(); } private void button3_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(); var streamReader = File.OpenText(openFileDialog1.FileName); var streamReader2 = File.OpenText(openFileDialog2.FileName); while (true) { var Line = streamReader.ReadLine(); if (Line == null ) break; var amount = decimal.Parse(Line, CultureInfo.InvariantCulture); //var Line2 = streamReader2.ReadLine(); //while (true) //{ for (int i = 0; i < 2; i++) { var Line2 = streamReader2.ReadLine(); var amount2 = decimal.Parse(Line2, CultureInfo.InvariantCulture); var totalGånger = amount * amount2; var totalToString = Convert.ToString(totalGånger); File.AppendAllText(saveFileDialog1.FileName, totalToString); } //var Line2 = streamReader2.ReadLine(); //if (Line2 == null && Line==null) // break; //var amount2 = decimal.Parse(Line2, CultureInfo.InvariantCulture); //var totalGånger = amount * amount2; //var totalToString = Convert.ToString(totalGånger); //File.AppendAllText(saveFileDialog1.FileName, totalToString); //} } //while (true) //{ // Line2 = streamReader.ReadLine(); // if (Line2 == null) // break; // var amount = decimal.Parse(Line, CultureInfo.InvariantCulture); // var amount2 = decimal.Parse(Line2, CultureInfo.InvariantCulture); // var totalGånger = amount * amount2; // var totalToString = Convert.ToString(totalGånger); // File.AppendAllText(saveFileDialog1.FileName, totalToString); //} //foreach (var entry in accounts.OrderBy(e => e.Key)) // Debug.WriteLine($"{entry.Key}{entry.Value.ToString("F2") }"); { } //Debug.WriteLine(accounts.Sum(entry => entry.Value)); } } } <file_sep>/MultiplierLib/ListHandler.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MultiplierLib { public class ListHandler { public List<string> List = new List<string>(); public void AddFiveStrings() { List.Add("Sharepoint är roligt"); List.Add("Jag är Sharepoint developer"); List.Add("jag kan javaScript"); List.Add("Jag kan HTML"); List.Add("Jag kan Css"); } public void RemoveThirdString() { List.Remove("jag kan javaScript"); } public void Sort() { List.Sort(); } } } <file_sep>/RäknaSistaSifro/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RäknaSistaSifro { class Program { static void Main(string[] args) { var finaly = 0; do { Console.WriteLine("Inter your person nr"); var personNr =Console.ReadLine(); int[] arr = { 2, 1, 2, 1, 2, 1, 2, 1, 2 }; var peronArr = personNr.ToArray().Select(ch => int.Parse(ch.ToString())).ToArray(); var total=0; var sut=0; for (int i = 0; i <= 8; i++) { sut = (peronArr[i]) * (arr[i]); if (sut > 9) { var sutToChar = Convert.ToString(sut); var sutToIntArray = sutToChar.ToArray().Select(ch => int.Parse(ch.ToString())).ToArray(); sut = (sutToIntArray[1]) + (sutToIntArray[0]); total += sut; } else { total += sut; } if (total <= 30) { finaly = 30 - total; } else if (total > 30 && total <= 40) { finaly = 40 - total; } else if (total > 40 && total <= 50) { finaly = 50 - total; } else if (total > 50 && total <= 60) { finaly = 60 - total; } else if (total > 60 && total <= 70) { finaly = 70 - total; } } Console.WriteLine("its your Answer {0}",finaly); } while (finaly>=0); } } } <file_sep>/SchoolCount/School.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolCount { class School { public List<Class> Classes { get; internal set; } = new List<Class>(); public int NumberOfStudents { get { return this.Classes.Sum(Class => Class.students); } } } } <file_sep>/Description.txt Uppgifter --------- - Använd C# Interactive för att testa en lista av strängar: var strings = new List<string>() { "Jag", "gillar", "att", "programmera" }; strings.RemoveAt(1); strings strings.Add("Mattias"); strings string.Join("-", s.ToArray()) Kopiera kod från: https://github.com/mattiasasplund/CSharp - Kopiera ListHandlerTests.cs från MultiplierTestsLib till ditt eget testprojekt, dessutom ListHandler.cs från MultiplierLib till ditt eget komponentprojekt. Ändra ListHandler.cs så att testerna går igenom. Följ din intuition genom att försöka förstå vad testerna begär av dig. - Använd C# Interactive för att testa datumhantering var birthDate = new DateTime(1971, 4, 5); var timeSpan = DateTime.Now - birthDate; $"I am {timeSpan.Days} days old" var timeSpanToNextBirthday = new DateTime(2018, 4, 5) - DateTime.Now; $"My next birthday will arrive in {timeSpanToNextBirthday.Days} days" - Kopiera DateHandlerTests.cs från MultiplierTestsLib till ditt eget testprojekt, dessutom DateHandler.cs från MultiplierLib till ditt eget komponentprojekt. Ändra DateHandler.cs så att testerna går igenom. Följ din intuition genom att försöka förstå vad testerna begär av dig.<file_sep>/OOPConsoleApp/Animal.cs using System; namespace OOPConsoleApp { internal class Animal { internal void Eat() { Console.WriteLine("Grumphs"); } } }<file_sep>/SchoolCount/Class.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolCount { class Class { public int students; public Class(int students) { this.students = students; } } } <file_sep>/ByggaHusLib/Window.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ByggaHusLib { public class Window { public bool IsOpen; public void Open() { IsOpen = true; } } } <file_sep>/ByggaHus/Fönster.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ByggaHus { class Fönster { } } <file_sep>/FakturaAppen/Program.cs using FakturaLibb; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FakturaAppen { class Program { static void Main(string[] args) { var fakturaSystem = new FakturaSystem(); Console.WriteLine("Enter name : "); var name = Console.ReadLine(); Console.WriteLine("Enter Id : "); var Id = Console.ReadLine(); var enPerson = fakturaSystem.SkapaPart(name, Id); var beställning = fakturaSystem.SkapaBeställning(enPerson); var teddy = fakturaSystem.SkapaProdukt("Fredriksson", 79M); var ponny = fakturaSystem.SkapaProdukt("Miniponny", 15000M); Console.WriteLine("Enter antal teddy : "); var antalTaddy = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter antal ponny : "); var antalPonny = Convert.ToInt32(Console.ReadLine()); try { beställning.NyRad(teddy, antalTaddy); beställning.NyRad(ponny, antalPonny); Console.WriteLine($"Beställningen är värd {beställning.Total}"); var faktura = beställning.GenereraFaktura(); Console.WriteLine(faktura); Console.ReadLine(); } catch (InvalidOperationException ex) { Console.WriteLine("Hoppsan. Försök igen lite senare."); } } } } <file_sep>/MultiplierTestsLib/MultiplierTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using MultiplierLib; namespace MultiplierTestsLib { [TestClass] public class MultiplierTests { [TestMethod] public void Simple() { // Arrange Multiplier myMultiplier = new Multiplier(); // Act var actual = myMultiplier.Simple(20, 20); // Assert Assert.AreEqual(400, actual); } [TestMethod] public void While() { // Arrange Multiplier myMultiplier = new Multiplier(); // Act var actual = myMultiplier.While(20, 20); // Assert Assert.AreEqual(400, actual); } } } <file_sep>/RegexConvert/ConvertString.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text.RegularExpressions; using EmployeeLib; namespace RegexConvert { [TestClass] public class ConvertString { [TestMethod] public void TestMethod1() { string input = @"""""""<NAME>"""" 46 35000.00 070-6186120"""; var sut = new Converter(); string actual = sut.EmployeeConverter(input); Assert.AreEqual("<NAME> (Lön: 35000,00 SEK) Telefon:070-6186120 Födelseår:1971",actual); } } } <file_sep>/PershonNumberApp6/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 PershonNumberLib; namespace PershonNumberApp6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } PersonnummerDigitFinder personNObj = new PersonnummerDigitFinder(); private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text.Length == 9) { personNObj.Proses(textBox1.Text); label1.Text = personNObj.LastDigit; } } } } <file_sep>/PersonNumberLib/FindLastNumber.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonNumberLib { public class FindLastNumber { } } <file_sep>/PracticeApp/Form1.cs using PracticLib; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace PracticeApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void SaveBt_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(); string name = NameTextBox.Text; string Phone = PhoneTextBox.Text; var personNr = pershonNrTimePicker.Value.ToString("yyyy-MM-dd"); string PershoInfo = PersonalInfo.Transform(name, Phone, personNr); File.AppendAllText(saveFileDialog1.FileName, PershoInfo); } private void canvertBt_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); saveFileDialog1.ShowDialog(); string content = File.ReadAllText(openFileDialog1.FileName); string test = PersonalInfo.Convert(content); File.AppendAllText(saveFileDialog1.FileName, test); } } } <file_sep>/FakturaLib/Product.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLib { public class Product { public Product(string name, decimal price) { this.Name = name; this.Price = price; } internal string Name; internal decimal Price; } } <file_sep>/Bokföring/Bokforing.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Bokföring { class Bokforing { static void Main(string[] args) { Console.WriteLine("Please add a path to the SIE-file:"); var theFile = Console.ReadLine(); // C:\Users\Amin\Documents\Visual Studio 2017\Projects\CSharp\MATTIAS00_SIE4 2015-09-01 - 2016-08-31.SE.txt string pattern = @"#TRANS (\d{4}) {} (-?\d*.\d*)"; var counter = 0; var content = File.ReadAllText(theFile); var reader = new StringReader(content); while (true) { var line = reader.ReadLine(); if (line == null) break; if (Regex.Match(line, pattern).Success) { counter++; } } var TransAccounts = new Dictionary<string, decimal>(); var streamReader = File.OpenText(theFile); while (true) { var line = streamReader.ReadLine(); if (line == null) break; var match = Regex.Match(line, pattern); if (match.Success) { var accountId = match.Groups[1].Value; var amount = decimal.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture); if (TransAccounts.ContainsKey(accountId)) { TransAccounts[accountId] += amount; } else TransAccounts[accountId] = amount; } } Console.WriteLine($"Amount #TRANS accounts in the file are {counter}."); Console.WriteLine(); foreach (var entry in TransAccounts.OrderBy(e => e.Key)) { Console.WriteLine($"{entry.Key} {entry.Value.ToString("F2")}"); } Console.WriteLine(); Console.WriteLine("Summan av alla konton är:"); Console.WriteLine(TransAccounts.Sum(e => e.Value)); Console.ReadLine(); } } }<file_sep>/FakturaLibb/FakturaSystem.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLibb { public class FakturaSystem { public Part SkapaPart(string namn, string juridisktId) { var enPerson = new Part { Namn = namn, JuridisktId = juridisktId }; return enPerson; } public Beställning SkapaBeställning(Part enPerson) { return new Beställning(enPerson); } public Produkt SkapaProdukt(string namn, decimal pris) { return new Produkt(namn, pris); } } } <file_sep>/FakturaLib/Faktura.cs using System; using System.Collections.Generic; using System.Text; namespace FakturaLib { public class Faktura { public string Street; public decimal Belopp; private Person kund; public Faktura() { } public Faktura(Person kund) { this.kund = kund; } public Person Kund { get; set; } } }
10d90845736d96ec0ab85b52e1fead67e8f33db7
[ "C#", "Text" ]
59
C#
Aminzare86/Csharp
6df38b5c3ba0874dd31e92d81a1add54472bcf99
645127fed8c05e7cef88c813c50b85c0ff37c99d
refs/heads/master
<repo_name>bhargavbks/CodeChallenges<file_sep>/WeatherApp/WeatherApp/Model/ForecastCellDataModel.swift import Foundation struct ForecastCellDataModel { let date: String let currentTemp: String let maxTemp: String let minTemp: String let weatherIcon: String let feelsLike: String let humidity: String init(with data: ForeCastData) { date = data.date currentTemp = data.temperature.temp.formatToTemperature() maxTemp = data.temperature.max.formatToTemperature() minTemp = data.temperature.min.formatToTemperature() feelsLike = data.temperature.feelsLike.formatToTemperature() humidity = "\(String(data.temperature.humidity))%" weatherIcon = data.weather[0].icon } } <file_sep>/WeatherApp/README.md # Weather App Challenge This is a application which shows 5 day forecast data in a table view. ## Build Project is created in Xcode 11 with Swift 5. This project will run in Xcode11. ## Time permitted If time permitted, I would like to build below functionalites 1. Handling error scenarios 2. Writing UI test and unit tests 3. Restructure the data model <file_sep>/WeatherApp/WeatherApp/Network/Services/NetworkService.swift import Foundation public final class NetworkService { // MARK: - Properites internal let session = URLSession.shared // MARK: - Class Constructors public static var shared = NetworkService() // MARK: - Methods func fetchWeatherData(success _success: @escaping (ForeCast) -> Void, failure _failure: @escaping (AppError) -> Void) { let success: (ForeCast) -> Void = { response in DispatchQueue.main.async { _success(response) } } let failure: (AppError) -> Void = { error in DispatchQueue.main.async{ _failure(error) } } guard let plistUrl = Bundle.main.url(forResource: "ServiceData", withExtension: "plist") else { let error = NSError(domain: "plistError", code: 1001, userInfo: nil) failure(AppError(error: error)) return } do { let data = try Data(contentsOf: plistUrl) let decoder = PropertyListDecoder() let value = try decoder.decode(ServiceModel.self, from: data) let queryParameters: HTTPParameters = [ "appid": value.appId, "q": "London,UK", "units": "metric", ] let request = try NetworkRequest.configureRequest(for: .forecast, parameters: queryParameters) session.dataTask(with: request){(data, response, error) -> Void in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode.isSuccessHTTPCode, let data = data else { if let error = error { failure(AppError(error: error)) } else { let error = NSError(domain: "dataformatError", code: 1003, userInfo: nil) failure(AppError(error: error)) } return } do { let responseData = try JSONDecoder().decode(ForeCast.self, from: data) success(responseData) } catch let error { failure(AppError(error: error)) } }.resume() } catch let error { failure(AppError(error: error)) } } } <file_sep>/WeatherApp/WeatherApp/View/ForecastTableViewCell.swift // // ForecastTableViewCell.swift // WeatherApp // // Created by <NAME> on 08/07/2020. // Copyright © 2020 TTF. All rights reserved. // import UIKit class ForecastTableViewCell: UITableViewCell { // MARK: - IBOutlets @IBOutlet weak var weatherImg: UIImageView! @IBOutlet weak var dateTime: UILabel! @IBOutlet weak var maxTemp: UILabel! @IBOutlet weak var minTemp: UILabel! @IBOutlet weak var feelsLikeTemp: UILabel! @IBOutlet weak var currentTemp: UILabel! @IBOutlet weak var humidity: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func prepareForReuse() { super.prepareForReuse() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - Methods func configure(with data: ForecastCellDataModel) { dateTime.text = data.date currentTemp.text = data.currentTemp maxTemp.text = data.maxTemp minTemp.text = data.minTemp feelsLikeTemp.text = data.feelsLike humidity.text = data.humidity weatherImg.image = UIImage(named: data.weatherIcon) } } <file_sep>/README.md # CodeChallenges <file_sep>/WeatherApp/WeatherApp/Network/Model/ServiceModel.swift import Foundation struct ServiceModel: Decodable { let baseUrl: String let appId: String } <file_sep>/WeatherApp/WeatherApp/Controller/WeatherViewController.swift import UIKit class WeatherViewController: UIViewController { // MARK: - Constants enum Constants { static let title: String = "Forecast" static let noOfSections: Int = 1 static let cellIdentifier: String = "forecast" } // MARK: - Properties let networkService = NetworkService.shared var forecastModel: ForeCast? // MARK: - IBOutlets @IBOutlet weak var forecastTableView: UITableView! { didSet { forecastTableView.dataSource = self } } // MARK: - IBAction // MARK: - View Load Methods override func viewDidLoad() { super.viewDidLoad() self.title = Constants.title let forecastCell = UINib.init(nibName: "ForecastTableViewCell", bundle: Bundle.main) forecastTableView.register(forecastCell, forCellReuseIdentifier: Constants.cellIdentifier) loadData() } // MARK: - Methods func loadData() { networkService.fetchWeatherData(success: { [weak self] foreCastData in print(foreCastData) guard let strongSelf = self else { return } strongSelf.forecastModel = foreCastData strongSelf.forecastTableView.reloadData() }, failure: { error in print(error) }) } } extension WeatherViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Constants.noOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let forecastData = forecastModel else { return 0 } return forecastData.list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier) as? ForecastTableViewCell, let forecastData = forecastModel else { fatalError("Problem creating forecast cell") } let cellDataModel = ForecastCellDataModel(with: forecastData.list[indexPath.row]) cell.configure(with: cellDataModel) return cell } } <file_sep>/WeatherApp/WeatherApp/Network/HTTP/URLEncoder.swift import Foundation public struct URLEncoder { /// Encode and set the parameters of a url request static func encodeParameters(for urlRequest: inout URLRequest, with parameters: HTTPParameters) throws { if parameters == nil { return } guard let url = urlRequest.url, let unwrappedParameters = parameters else { throw NSError(domain: "MissingUrl", code: 1002, userInfo: nil) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !unwrappedParameters.isEmpty { urlComponents.queryItems = [URLQueryItem]() for (key,value) in unwrappedParameters { let queryItem = URLQueryItem(name: key, value: "\(value)") urlComponents.queryItems?.append(queryItem) } urlRequest.url = urlComponents.url } } /// Set the addition http headers of the request static func setHeaders(for urlRequest: inout URLRequest, with headers: HTTPHeaders) throws { if headers == nil { return } guard let unwrappedHeaders = headers else { throw NSError(domain: "missingHeaders", code: 1004, userInfo: nil) } for (key, value) in unwrappedHeaders{ urlRequest.setValue(value as? String, forHTTPHeaderField: key) } } } <file_sep>/WeatherApp/WeatherApp/Model/ForeCast.swift import Foundation public struct ForeCast: Codable { let cod: String let message: Int let cnt: Int let list: [ForeCastData] let city: City } struct ForeCastData: Codable { let dt: Int let temperature: Temperature let weather: [Weather] let clouds: Clouds let wind: Wind let rain: Rain? let sys: Sys let date: String private enum CodingKeys: String, CodingKey { case dt case temperature = "main" case weather, clouds, wind, rain, sys case date = "dt_txt" } } struct Temperature: Codable { let temp, feelsLike, min, max: Double let pressure, seaLevel, groundLevel, humidity: Int let tempKf: Double private enum CodingKeys: String, CodingKey { case temp case feelsLike = "feels_like" case min = "temp_min" case max = "temp_max" case pressure case seaLevel = "sea_level" case groundLevel = "grnd_level" case humidity case tempKf = "temp_kf" } } struct Weather: Codable { let id: Int let main: String let description: String let icon: String } struct Clouds: Codable { let all: Int } struct Wind: Codable { let speed: Double let deg: Int } struct Rain: Codable { let rain: Double? private enum CodingKeys: String, CodingKey { case rain = "3h" } } struct Sys: Codable { let pod: String } struct City: Codable { let id: Int let name: String let coord: Coordinates let country: String let population: Int let timezone: Int let sunrise: Int let sunset: Int } struct Coordinates: Codable { let lat: Double let lon: Double } <file_sep>/WeatherApp/WeatherApp/Network/HTTP/NetworkRequest.swift import Foundation public typealias HTTPParameters = [String: Any]? public typealias HTTPHeaders = [String: Any]? public enum UrlPath: String { case forecast = "forecast" } public enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } struct NetworkRequest { static func configureRequest(for path: UrlPath, parameters: HTTPParameters? = nil, body: Data? = nil, method: HTTPMethod = .get) throws -> URLRequest { guard let plistUrl = Bundle.main.url(forResource: "ServiceData", withExtension: "plist") else { throw NSError(domain: "plistError", code: 1001, userInfo: nil) } //do { let data = try Data(contentsOf: plistUrl) let decoder = PropertyListDecoder() let value = try decoder.decode(ServiceModel.self, from: data) guard let url = URL(string: "\(value.baseUrl)\(path.rawValue)") else { throw NSError(domain: "MissingUrl", code: 1002, userInfo: nil) } var request = URLRequest(url: url) let basicHeaders = [ "Content-Type": "application/json", "Accept": "application/json" ] try configureParametersAndHeaders(parameters: parameters, headers: basicHeaders, request: &request) return request // } catch let error { // print(error) // } } static func configureParametersAndHeaders(parameters: HTTPParameters?, headers: HTTPHeaders?, request: inout URLRequest) throws { do { if let headers = headers, let parameters = parameters { try URLEncoder.encodeParameters(for: &request, with: parameters) try URLEncoder.setHeaders(for: &request, with: headers) } } catch { throw NSError(domain: "Url encoding failed", code: 1002, userInfo: nil) } } } <file_sep>/WeatherApp/WeatherApp/Network/Model/NetworkError.swift import Foundation enum AppError: Int, Error { case badRequest = 400 case unauthorised = 401 case forbidden = 403 case requestTimeOut = 408 case internalServerError = 500 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeOut = 504 case plistError = 1001 case missingUrl = 1002 case dataformatError = 1003 case missingHeaders = 1004 case unknown init(error: Error) { let nsError = error as NSError self = AppError(rawValue: nsError.code) ?? .unknown } var localizedDescription: String { switch self { case .badRequest: return "Please check the request you made" case .forbidden: return "Please check the request" case .unauthorised: return "Please authenticate and try again" case .requestTimeOut: return "Request timedout. Please try after some time" case .internalServerError: return "Problem with server" case .badGateway: return "Please check with backend team" case .gatewayTimeOut: return "Gateway timed out. Please check with backend team" case .serviceUnavailable: return "Service unavailable. Please report" default: return "Problem with data" } } } <file_sep>/WeatherApp/WeatherApp/Resources/Extensions/Measurement+extension.swift import Foundation extension Double { func formatToTemperature(with unit: UnitTemperature = .celsius) -> String { let measurement = Measurement(value: self, unit: unit) let measurementFormatter = MeasurementFormatter() measurementFormatter.unitStyle = .short measurementFormatter.numberFormatter.maximumFractionDigits = 0 measurementFormatter.unitOptions = .temperatureWithoutUnit return measurementFormatter.string(from: measurement) } }
eece9f8a12fb678193d1052739eeb4c80b42accc
[ "Swift", "Markdown" ]
12
Swift
bhargavbks/CodeChallenges
78447632e559258a514270f898fe75af121947af
fd3e36fef77aa63541bff978b63b11d0f2728852
refs/heads/master
<repo_name>navohu/creativity_hub<file_sep>/README.md # creativity_hub Website which showcase the projects of UCL research studies in the fields of Deep Learning and Neural Networks. <file_sep>/scripts/vis.js var ymin = 0; var ymax = 30; var xmin = 0; var xmax = 300; var positions = []; var Graph; function initialiseGraph(){ ymin = 0; ymax = 30; xmin = 0; xmax = 300; d3.select('#visualisation').selectAll("*").remove(); d3.selectAll("path.line").remove(); positions = []; // can be used to graph loss, or accuract over time Graph = d3.select('#visualisation') .attr('width', '100%') .attr('height', 500), WIDTH = $("#visualisation").parent().width(), HEIGHT = 500, MARGINS = { top: 20, right: 20, bottom: 20, left: 20 }, xRange = d3.scaleLinear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([xmin, xmax]), yRange = d3.scaleLinear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([ymin, ymax]), xAxis = d3.axisBottom() .scale(xRange) .ticks(5), yAxis = d3.axisLeft() .scale(yRange); // Graph.classed("svg-container", true) // .append("svg") // .attr("preserveAspectRatio", "xMinYMin meet") // .attr("viewBox", "0 0 600 400") // .classed("svg-content-responsive", true); Graph.append('svg:g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')') .call(xAxis) .append("text") .attr('x', WIDTH - 2*MARGINS.right) .attr('y', 0) .attr('stroke', '#a94442') .style("text-anchor", "left") .text('Tick iteration'); Graph.append('svg:g') .attr('class', 'y axis') .attr('transform', 'translate(' + (MARGINS.left) + ',0)') .call(yAxis) .append('text') .attr('x', MARGINS.left) .attr('y', MARGINS.top) .attr('stroke', '#a94442') .style("text-anchor", "middle") .text('Median perplexity'); } function updateVisual(step, y){ d3.select('#visualisation').selectAll("*").remove(); Graph = d3.select('#visualisation') .attr('width', '100%') .attr('height', 500), WIDTH = $("#visualisation").parent().width(), HEIGHT = 500, MARGINS = { top: 20, right: 20, bottom: 20, left: 20 }, xRange = d3.scaleLinear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([xmin, getMaxXDomain(step)]), yRange = d3.scaleLinear().range([HEIGHT - MARGINS.bottom, MARGINS.top]).domain([getMaxYDomain(y), getMinYDomain(y)]), xAxis = d3.axisBottom() .scale(xRange) .ticks(5), yAxis = d3.axisLeft() .scale(yRange); var transformY = Graph.append("g") .attr('class', 'y axis') .attr('transform', 'translate(' + (MARGINS.left) + ',0)') .call(yAxis) .append('text') .attr('x', MARGINS.left) .attr('y', MARGINS.top) .attr('stroke', '#a94442') .style("text-anchor", "middle") .text('Median perplexity'); var transformX = Graph.append("g") .attr('class', 'x axis') .attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')') .call(xAxis) .append("text") .attr('x', WIDTH - 2*MARGINS.right) .attr('y', 0) .attr('stroke', '#a94442') .style("text-anchor", "left") .text('Tick iteration'); // console.log("Step: " + positions.step + "\n y: " + positions.y); positions.push({step: step, y: y}); var lineFunc = d3.line() .x(function(d){ return xRange(d.step);}) .y(function(d){ return yRange(d.y)}); Graph.append('path') .attr('class', 'line') .attr('stroke', 'blue') .attr('stroke-width', 2) .attr('fill', 'none') .attr('d', lineFunc(positions)); } function getMinYDomain(y){ if(ymin<y) { ymin = y*1.1; return ymin; } else return ymin; } function getMaxYDomain(y){ if(ymax>y){ ymax = y*0.8; return ymax; } else return ymax; } function getMaxXDomain(step){ if(step > xmax){ xmax *= 2; return xmax; } else return xmax; }
278b8c978b422677e3e86560876827ee3fdfa1d7
[ "Markdown", "JavaScript" ]
2
Markdown
navohu/creativity_hub
1ded1a7775d167245784e620ea5ee1606f6d46a7
d6f504a612ef244016961ac086ccbcbddba3396e
refs/heads/master
<file_sep>#!/bin/bash #LOG = "/media/usb" #check for internet connectivity test=google.com echo "testing access to $test" if nc -zw1 $test 443 && echo |openssl s_client -connect $test:443 2>&1 |awk ' handshake && $1 == "Verification" { if ($2=="OK") exit; exit 1 } $1 $2 == "SSLhandshake" { handshake = 1 }' then #internet access confirmed update apt-get echo "$test available, installing packages" sudo apt-get -y update #TODO: install/upgrade missing packages and save them to drive repository else #no internet connection, confirm install from usb drive read -r -p "$test unavailable, install from usb? [y/N] " response if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]] then #TODO find usb mount point and cp stored .deb files to /var/cache/apt/archive #TODO add argument to specify version of .deb archive to cp? #for now assume usb is mounted at /media/usb echo DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "deb file:/media/usb/AirDojo/archives/base-v1 ./" >> /etc/apt/sources.list #if [ -d "$archive" ]; then # sudo cp -rf "$archive/." "/var/cache/apt/archive/" #fi #archive=/media/usb/AirDojo/archives/apt-base/*.deb #for f in $archive #do # echo "Caching $f" # sudo dpkg -i $f #done #sudo dpkg -i /media/usb/AirDojo/archives/base-v1/*.deb apt-get update for package in `cat /media/usb/AirDojo/archives/base-v1/package_names` do echo " " echo "===============================================" echo "installing $package" echo "+++++++++++++++++++++++++++++++++++++++++++++++" apt-get install -y $package done apt-cache dump | grep -oP 'Package: \K.*' | sort -n | while read -r line do apt-get install -y $line done #sudo apt-get -f install #dpkg -I /var/cache/apt/archive/usbmount_0.0.22_all.deb | grep Depends | sed 's/.*://' else #no intenet connection and refusal to install from usb, exit script echo "Please connect C.H.I.P to internet with the command: 'sudo nmcli device wifi connect '(your wifi network name/SSID)' password '(<PASSWORD>)' ifname wlan0' or your method of choice. And try again" exit 2 fi fi sudo apt-get -fy upgrade sudo apt-get -fy install dnsmasq-base sudo apt-get -fy install git zip unzip sudo apt-get -fy install usbmount sudo apt-get -fy install nodejs <file_sep> #cd /usr/local/mydebs #dpkg-scanpackages . /dev/null | gzip -9c > Packages.gz <file_sep>#!/bin/bash #dmasqaccesspoint #networksetup sudo apt-get install dnsmasq cat dmasqaccesspoint > /etc/dnsmasq.d/access_point.conf cat interfaces > /etc/network/interfaces sudo ifup wlan1 ip addr show wlan1 sudo /etc/init.d/dnsmasq restart cat hostapd > /etc/hostapd.conf sudo hostapd /etc/hostapd.conf cat service > /lib/systemd/system/hostapd-systemd.service sudo update-rc.d hostapd disable sudo systemctl daemon-reload sudo systemctl enable hostapd-systemd sudo systemctl start hostapd-systemd systemctl status hostapd-systemd
03ce310589c6c6664092f4be6612e99df1ef6378
[ "Shell" ]
3
Shell
CoffeeGears/Air_Dojo
5a10b2c966535c9cb26b3cffd9d78137a9e3919d
10d82f9a5f43e7f98a41a2d8585668f49800802b
refs/heads/master
<repo_name>ColorCoinK/springcloud-learning<file_sep>/eureka-token-server/src/main/java/com/learning/utils/JwtUtil.java package com.learning.utils; import com.learning.entity.dto.UserDto; import com.learning.enumerate.ParseToken; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @ClassName JwtUtil * @Description <br/> JSON Web Token 生成、解析、刷新工具类 * @Author Dew * @Date * @Version 1.0 **/ public class JwtUtil { /** * token 加密算法 HS256 **/ private final static SignatureAlgorithm ENCRYPT_KEY = SignatureAlgorithm.HS256; /** * 该JWT 所面向的用户 **/ private final static String SUBJECT = "dew"; /** * 私钥 **/ private final static String SECRET_KEY = "secretkey"; /** * @param uid 用户id * @param name 用户名 * @param duration 有效时长(unix时间戳) * @return java.lang.String * @Title createJws * @Description * @Param **/ public static String createJws(Long uid, String name, String password, long duration) { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); // 自定义token携带的参数值 Map<String, Object> claims = new HashMap<>(); claims.put("uid", uid); claims.put("user_name", name); // claims.put("password", <PASSWORD>); JwtBuilder builder = Jwts.builder() // 该JWT 所面向的用户 .setSubject(SUBJECT) // token 携带的参数 .setClaims(claims) // token创建时间,unix时间戳格式 .setIssuedAt(now) .signWith(ENCRYPT_KEY, SECRET_KEY); if (duration >= 0) { // 设置最大有效时间,unix时间戳 long expirationMills = nowMillis + duration; Date expirationTime = new Date(expirationMills); //expire 指定 token 的声明周期,unix 时间戳格式 builder.setExpiration(expirationTime); } return builder.compact(); } /** * @return java.lang.Object * @Title analysisToken * @Description 解析 Token 内容信息 * @Param **/ public static Object analysisToken(String token, ParseToken type) { try { // 解析 token 中携带的信息 Claims claims = parseJWs(token); long now = System.currentTimeMillis(); // token 失效时间(设置的过期时间为 java.util.Date) Date expDate = claims.get("exp", Date.class); long exp = expDate.getTime(); // 用户编号 Long uid = claims.get("uid", Long.class); // 登录名 String userName = claims.get("user_name", String.class); // 1.token 过期 if (exp < now) { throw new JwtException("Token 过期"); } // 2.在有效期内,刷新 token switch (type) { case UID: return uid; case USER_DTO: UserDto userDto = new UserDto(token, uid, userName); exp = now + new UserDto().getExpritaion(); userDto.setExpritaion(exp); return userDto; case USER_NAME: return userName; default: break; } } catch (JwtException e) { throw new JwtException(e.getMessage()); } catch (Exception exception) { throw new RuntimeException("token解析错误"); } return false; } /** * @return io.jsonwebtoken.Claims * @Title parseJWs * @Description 解析 token 字符串 * @Param **/ static Claims parseJWs(String token) throws JwtException { // 解析 token 中携带的信息 Claims claims = Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); return claims; } }<file_sep>/eureka-server/READMIN.md # 基于 Eureka 搭建高可用(双节点服务注册中心) > 添加`pom`依赖 ```xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.SR5</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> ``` > 版本说明 * 本项目是一个基于 SpringBoot(1.5.19.RELEASE)、SpringCloud(Edgware.SR5)、Eureka 的服务注册中心 ## 配置文件 > `application.yml` 单个 `Eureka` 服务注册中心 > `application-colony.yml` 双节点注册中心,实现双向注册从而提高可用性详细可以看<a href="http://www.ityouknow.com/springcloud/2017/05/10/springcloud-eureka.html">注册中心Eureka</a> 1. 默认使用 `application.yml` 配置文件; 2. 使用`application-conlony.yml` 配置文件时,需要指定激活的配置项.(例如启动`server-1`,需运行`java -jar xx.jar --spring.profiles.active=server-1`)<file_sep>/eureka-provider/src/main/java/com/learning/controller/BookController.java package com.learning.controller; import com.learning.entity.Book; import com.learning.repository.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class BookController { @Autowired private BookRepository bookRepository; @GetMapping("/{id}") public Book findById(@PathVariable Long id) { return this.bookRepository.findOne(id); } }<file_sep>/eureka-token-server/HELP.md # Getting Started ### Guides The following guides illustrates how to use certain features concretely: * [Messaging with Redis](https://spring.io/guides/gs/messaging-redis/) * [Validating Form Input](https://spring.io/guides/gs/validating-form-input/) <file_sep>/eureka-provider/src/main/resources/data.sql INSERT INTO tbl_book (id, name, price) VALUES (1, 'Spring Boot - Spring Data JPA with Hibernate and H2 Web Console', 0.0); INSERT INTO tbl_book (id, name, price) VALUES (2, 'Spring Boot - Spring Data JPA with Hibernate and H2 Web Console 2', 1.0); INSERT INTO tbl_book (id, name, price) VALUES (3, 'Spring Boot - Spring Data JPA with Hibernate and H2 Web Console 3', 2.0); INSERT INTO tbl_book (id, name, price) VALUES (4, 'Spring Boot - Spring Data JPA with Hibernate and H2 Web Console 4', 3.0); insert into t_user(id, name, age) values(1,'JSON',29); insert into t_user(id, name, age) values(2,'Alibaba',25); insert into t_user(id, name, age) values(3,'Apache',30); insert into t_user(id, name, age) values(4,'GitHub',20); insert into t_user(id, name, age) values(5,'Sun',18);<file_sep>/eureka-token-server/src/main/java/com/learning/repository/UserRepository.java package com.learning.repository; import com.learning.entity.UserPO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * @Title 用户数据库操作类 * @ClassName UserRepository * @Description TODO * @Author sanss * @Date 2019/2/22 15:11 * @Version 1.0 */ @Repository public interface UserRepository extends JpaRepository<UserPO, Long> { /** * @Title findByNameAndPassword * @Description 登录验证 * @Param * @param name 登录名 * @param password 密码 * @return com.learning.entity.Account **/ UserPO findByNameAndPassword(String name, String password); }<file_sep>/eureka-token-server/src/main/resources/data.sql insert into tbl_account (id,name,age,sex,password,role) values (1001,'admin',18,'男','1','ROLE_ADMIN'); insert into tbl_account (id,name,age,sex,password,role) values (1002,'zy',25,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1003,'lb',18,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1004,'lk',22,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1005,'zj',18,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1006,'lc',21,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1007,'wdd',18,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1008,'ln',18,'男','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1009,'gy',20,'女','1','ROLE_USER'); insert into tbl_account (id,name,age,sex,password,role) values (1010,'dew',35,'男','1','ROLE_USER');<file_sep>/eureka-token-server/src/main/java/com/learning/entity/dto/UserDto.java package com.learning.entity.dto; import com.learning.entity.UserPO; import lombok.Data; /** * @Title token 刷新时间数据传输实体类 * @ClassName UserDo * @Description TODO * @Author sanss * @Date 2019/2/22 16:24 * @Version 1.0 */ @Data public class UserDto extends UserPO { /** * 有效时长(unix 时间戳) **/ private Long expritaion; private String token; public UserDto() { this.expritaion = (long) 1000 * 60 * 10; } public UserDto(String token, Long id, String name) { this.token = token; this.setId(id); this.setName(name); } }<file_sep>/eureka-provider/src/main/resources/schema.sql drop table if exists tbl_book; create table tbl_book( id number(12) primary key not null, name varchar not null, price decimal not null ); create table t_user( id number(12) primary key not null, name varchar not null, age int not null ); -- DELETE FROM tbl_book;<file_sep>/eureka-token-server/src/main/java/com/learning/entity/UserPO.java package com.learning.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import lombok.ToString; /** * @Title 用户 —— 数据库映射实体类 * @ClassName Account * @Description tbl_account * @Author sanss * @Date 2019/2/22 13:57 * @Version 1.0 */ @Entity @Data @ToString @Table(name = "tbl_account") public class UserPO { @Id @GeneratedValue private Long id; /** * 姓名 **/ private String name; /** * 年龄 **/ private Integer age; /** * 性别 **/ private String sex; /** * 登录密码 **/ private String password; /** * 角色名称 **/ private String role; }<file_sep>/eureka-token-server/src/main/resources/schema.sql drop table if exists tbl_account; create table tbl_account( id number(12) primary key not null , name varchar not null, age int(2) not null , sex char(2) not null , password varchar(80) not null , role varchar(10) not null );<file_sep>/eureka-provider/src/main/java/com/learning/controller/OfflineController.java package com.learning.controller; import com.netflix.discovery.DiscoveryManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class OfflineController { @Autowired private DiscoveryClient discoveryClient; @RequestMapping(value = "offline",method = RequestMethod.GET) public void offLine(){ DiscoveryManager.getInstance().shutdownComponent(); } }
aa17870ad4250924ab9397d34bb4f500a7b3b3be
[ "Markdown", "Java", "SQL" ]
12
Java
ColorCoinK/springcloud-learning
7129711da1d983e07b204f1c6e0fd3b70e149051
e11e3b40aca79a0078869309322e54f9ef9914df
refs/heads/master
<repo_name>mikeevmm/YGG<file_sep>/ygg/src/cli.js const USAGE = `Usage: $ ygg [options] <input file path> <output file path>`; const HELP = `YGG (Yet-another Grammar Grammar) Compile a YGG grammar into a generator file. ${USAGE} Options: --overwrite=<overwrite> Overwrite the output file if it exists (default: false). --encoding=<encoding> Specify an encoding for the input file (default: utf-8). --help Display this text. --version Show the current version.`; function cli() { const arg = require('arg'); const fs = require('fs'); const ygg = require('../ygg'); const args = arg({ '--overwrite': Boolean, '--encoding': String, '--help': Boolean, '--version': Boolean, '-v': '--version', '-V': '--version', '-h': '--help', }); if (args['--version']) { const version = require('root-require')('package.json').version; console.log(`YGG (Yet-another Grammar Grammar) ${version}`); return; } if (args['--help']) { console.log(HELP); return; } const arg_count = args._.length; if (arg_count != 2) { console.log(USAGE); return; } const [infile, outfile] = args._; if (!fs.existsSync(infile)) { console.log(`Input file '${infile}' does not exist.`); return; } if (!args['--overwrite'] && fs.existsSync(outfile)) { console.log(`Output file '${outfile}' already exists.`); return; } let encoding = 'utf-8'; if (args['--encoding']) encoding = args['--encoding']; const grammar = fs.readFileSync(infile, encoding); try { ygg.compile(grammar, outfile); } catch(err) { // Stop YGG errors as these have been reported. if (!err.ygg) throw err; } } module.exports = {cli};<file_sep>/ygg/test/test.js const {expect} = require('chai'); describe('Parser', function() { const parser = require('../src/parser'); it('create a stream', function() { parser.Stream('Some text data.'); }); it('eof', function() { const empty = ''; const stream = parser.Stream(empty); expect(parser.eof(stream)).to.be.true; }); it('peek', function() { const char = 'x'; const stream = parser.Stream(char); expect(parser.peek(stream)).to.be.equal(char); }); it('consume', function() { const char = 'y'; let stream = parser.Stream(char); ({consumed, stream} = parser.consume(stream)); expect(consumed).to.be.equal(char); }); it('last', function() { const char = 'z'; let stream = parser.Stream(char); ({stream} = parser.consume(stream)); expect(parser.last(stream)).to.be.equal(char[0]); }); it('match', function() { const char = 'w'; const not_char = 'x'; let stream = parser.Stream(char); ({matches, stream} = parser.match(stream, not_char)); expect(matches).to.be.false; ({matches, stream} = parser.match(stream, char)); expect(matches).to.be.true; }); it('any', function() { const char = 'u'; const not_one_of = ['x', 'y', 'z']; let stream = parser.Stream(char); ({matches, stream} = parser.any(stream, not_one_of)); expect(matches).to.be.false; const one_of = not_one_of.concat([char]); ({matches, stream} = parser.any(stream, one_of)); expect(matches).to.be.true; }); it('whileMatch', function() { const text = 'xxxxY'; let stream = parser.Stream(text); stream = parser.whileMatch(stream, 'x'); ({matches, stream} = parser.match(stream, 'Y')); expect(matches).to.be.true; }); it('whileAny', function() { const do_match = ['x', 'y', 'z']; const stop_at = 'w'; const text = do_match.concat([stop_at]).join(''); let stream = parser.Stream(text); ({content, stream} = parser.whileAny(stream, do_match)); expect(content).to.be.equal(do_match.join('')); ({matches, stream} = parser.match(stream, stop_at)); expect(matches).to.be.true; }); it('whileCondition', function() { const isNumber = (char) => /[0-9]/.test(char); const text = '01234x'; let stream = parser.Stream(text); ({content, stream} = parser.whileCondition(stream, isNumber)); expect(content).to.be.equal('01234'); ({matches, stream} = parser.match(stream, 'x')); expect(matches).to.be.true; }); it('until', function() { const n = 10; const text = 'x'.repeat(n).concat('yzx'); let stream = parser.Stream(text); ({content, stream} = parser.until(stream, 'y')); expect(content).to.be.equal('x'.repeat(n)); ({matches, stream} = parser.match(stream, 'z')); expect(matches).to.be.true; }); it('matchStr', function() { const text = 'abcabcdef'; let stream = parser.Stream(text); ({matches, stream} = parser.matchStr(stream, 'abc')); expect(matches).to.be.true; ({matches, stream} = parser.matchStr(stream, 'def')); expect(matches).to.be.false; ({matches, stream} = parser.matchStr(stream, 'abc')); expect(matches).to.be.true; ({matches, stream} = parser.matchStr(stream, 'def')); expect(matches).to.be.true; }); it('matchAnyStr', function() { const text = 'abcabcdef'; const any = ['abc', 'def']; let stream = parser.Stream(text); ({matches, stream} = parser.matchAnyStr(stream, any)); expect(matches).to.be.true; ({matches, stream} = parser.matchAnyStr(stream, any)); expect(matches).to.be.true; ({matches, stream} = parser.matchAnyStr(stream, any)); expect(matches).to.be.true; }); }); describe('Well-formed Input', function() { const ygg = require('../ygg'); it('Simple string', function() { const interpreter = ygg.interpret('("Hello world!")'); interpreter(''); }); it('Concatenation', function() { const interpreter = ygg.interpret('("Hello " "world!")'); expect(interpreter('')).to.be.equal('Hello world!') }); it('Assignment', function() { const interpreter = ygg.interpret('(= hello "Hello world!")'); expect(interpreter('')).to.be.equal(''); }); it('Identifier use', function() { const interpreter = ygg.interpret('(= hello "hewwo" hello " world!")'); expect(interpreter('Yes')).to.equal('hewwo world!'); }); it('Nested expressions', function() { const interpreter = ygg.interpret('("Hello " ("there " ("General Grievous.")))'); expect(interpreter('')).to.be.equal('Hello there General Grievous.'); }); it('Choose', function() { const interpreter = ygg.interpret('("Hello " |("Michael" "James" "Jones"))'); expect(interpreter('')).to.match(/Hello (?:Michael|James|Jones)/); }); it('Optional', function() { const interpreter = ygg.interpret('("Hewwo " (? "owo"))'); for (let i = 0; i < 10; i++) expect(interpreter('')).to.match(/Hewwo (?:owo)?/); }); it('Regex match', function() { const interpreter = ygg.interpret('(& "[Yy](?:es)?" "yes" "no")'); expect(interpreter('Yes')).to.equal('yes'); expect(interpreter('yes')).to.equal('yes'); expect(interpreter('y')).to.equal('yes'); expect(interpreter('No')).to.equal('no'); expect(interpreter('')).to.equal('no'); expect(interpreter('Proteus')).to.equal('no'); }); it('Ignore whitespace', function() { const interpreter = ygg.interpret(` ("Hello" \t " this" " is whitespace.")`); expect(interpreter('')).to.equal('Hello this is whitespace.'); }); it('Complicated example', function() { const interpreter = ygg.interpret(` ( = name |("James" "Jones" "Michael") "Hello there " name ", it's " |("lovely" "very nice" "wonderful") " to meet you. " |( ("Care to join me " |("for a drink" "for dinner") "?") "I've heard much about you." ) ) `); // Using the `parser` module to check the output, so if that fails // so does this. const parser = require('../src/parser'); for (let i = 0; i < 10; ++i) { const text = interpreter(''); let stream = parser.Stream(text); ({matches, stream} = parser.matchStr(stream, 'Hello there ')); if (!matches) throw text; ({matches, stream} = parser.matchAnyStr(stream, ['James', 'Jones', 'Michael'])); if (!matches) throw text; ({matches, stream} = parser.matchStr(stream, ', it\'s ')); if (!matches) throw text; ({matches, stream} = parser.matchAnyStr(stream, ['lovely', 'very nice', 'wonderful'])); if (!matches) throw text; ({matches, stream} = parser.matchStr(stream, ' to meet you. ')); if (parser.peek(stream) === 'C') { ({matches, stream} = parser.matchStr(stream, 'Care to join me ')); if (!matches) throw text; ({matches, stream} = parser.matchAnyStr(stream, ['for a drink', 'for dinner'])); if (!matches) throw text; ({matches, stream} = parser.matchStr(stream, '?')); if (!matches) throw text; } else if (parser.peek(stream) === 'I') { ({matches, stream} = parser.matchStr(stream, 'I\'ve heard much about you.')); if (!matches) throw text; } else { throw text; } } }); }); describe('Malformed Input', function() { const ygg = require('../ygg'); it('No global statement', function() { expect(() => ygg.interpret('"Hello!"')).to.throw(); }); it('Undefined identifier', function() { expect(() => { const interpreter = ygg.interpret('(literal)'); interpreter(''); }).to.throw(); }); it('Invalid regex', function() { expect(() => { const interpreter = ygg.interpret('(& "(" "Yes" "No")'); interpreter(''); }).to.throw(); }); it('Expect literal start', function() { expect(() => { const interpreter = ygg.interpret('(& id "yes" "no")'); interpreter(''); }).to.throw(); }); it('Unclosed literal', function() { expect(() => { const interpreter = ygg.interpret('(")'); interpreter(''); }).to.throw(); }); it('Expect identifier', function() { expect(() => { const interpreter = ygg.interpret('(= "bad assign" "yes" "no")'); interpreter(''); }).to.throw(); }); it('Expect operator/statements', function() { expect(() => { const interpreter = ygg.interpret('(. "bad operator")'); interpreter(''); }).to.throw(); }); it('Unclosed statements', function() { expect(() => { const interpreter = ygg.interpret('(()'); interpreter(''); }).to.throw(); }); });<file_sep>/ygg/README.md # Yet-another Grammar Grammar (YGG) YGG is a [generative grammar][0] metasyntax interpreter and compiler, made with bots in mind. [Tutorial on Gemini (Web proxy)](https://miguelmurca.flounder.online/gemlog/2021-05-18bot.gmi) ## Example ``` ( = name |("James" "Jones" "Michael") "Hello there " name ", it's " |("lovely" "very nice" "wonderful") " to meet you. " |( ("Care to join me " |("for a drink" "for dinner") "?") "I've heard much about you." ) ) ``` generates ``` Hello there Jones, it's lovely to meet you. I've heard much about you. Hello there Michael, it's wonderful to meet you. I've heard much about you. Hello there James, it's very nice to meet you. Care to join me for dinner? ... ``` ## Quick Start ### For command line usage: ``` bash npm install --global @miguelmurca/ygg ygg --help ``` after compiling to a file (for example `mine.js`), ``` javascript const { generate } = require('./mine.js'); console.log(generate('Some input')); ``` ### For programmatic usage: ``` bash npm install @miguelmurca/ygg ``` and then ``` javascript const ygg = require('@miguelmurca/ygg'); const GRAMMAR = `( "Hello world!" )`; // Your grammar here const interpreter = ygg.interpret(GRAMMAR); console.log(interpreter('Some input.')); ``` ## What? `ygg` plays 3 separate roles. First, it's a definition of a metasyntax notation (like, for example, [BNF][1]). What this means is that it defines a way for you to define generative grammars (i.e., acceptable sentences). You can find more information about this under [syntax](#syntax). Secondly, `ygg` is a command-line utility for "compiling" files defining grammars into javascript files that expose a generating function. This means you can pass in a file with your grammar to `ygg` on the command line, and produce a javascript file you can use to make, e.g., your Telegram bot. See the [CLI](#cli) section for more information. Finally, `ygg` is an npm package, which you can call upon programmatically. You can parse and/or compile grammars on the fly with it. See the [npm package](#npm-package) section for more information. ## Why? I often make joke bots in Telegram or Twitter. Every so often, or whenever someone messages them, they tweet out or reply with a dynamically generated sentence which has something to do with whatever the bot's about. It's not hard to write code to generate these texts, but it can be hard to iterate over the code, and keep it readable. I wrote `ygg` to reduce the amount of boilerplate code I have to write for each bot, and to ease the iteration process. ## Syntax `ygg` uses a [Polish notation][2]-like syntax: * `"<literal expression>"` is reduced to the text itself, which can be delimited by `"` or `'`; * `( <expression> <expression> ... )` is reduced to the concatenated expressions; * `? <optional expression>` is reduced to either the expression or nothing (with equal likelihood); * `| (<option 1> <option 2> ...)` is reduced to one of the options (with equal likelihood); * `<identifier>` reduces to value of the identifier (which can be made up of numbers and letters); * `= <identifier> <expression>` attributes expression to the identifier, and reduces to nothing; * `& "<regex>" <expression> <expression>` reduces to first/second expression if regex matches/doesn't match the input. A `ygg` grammar specification, then, is just one big grouped expression, reducing to a string: ``` ( ... ) ``` ## CLI Supposing `grammar.ygg` is a text file containing the grammar, ``` bash ygg grammar.ygg generator.js ``` will produce a javascript file named `generator.js` . This file exposes a single function, `generate` , which takes in the user input as a string argument, and returns a string in the defined grammar. ## `npm` Package `ygg` can be used as a module to do things on the fly. For this, the `ygg` package exposes two functions, `compile` and `interpret` . ``` javascript compile(grammar: String, output_file: String) -> undefined ``` `compile` exposes the CLI behaviour; given a string of a grammar, it will write the compiled generator into the specified output file (specified by its name). ``` javascript interpret(grammar: String) -> ((String) => String) ``` `interpret` will take in the grammar as a string and return a function that generates members of the grammar for the provided input. ## License This tool is licensed under an MIT license. See LICENSE for details. ## Support 💕 If you liked `ygg` , consider [buying me a coffee](https://www.paypal.me/miguelmurca/2.50). [0]: https://en.wikipedia.org/wiki/Generative_grammar [1]: https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form [2]: https://en.wikipedia.org/wiki/Polish_notation <file_sep>/ygg/src/parser.js /** * This file provides utility for consuming plain source text in a tokenized * fashion. **/ const Stream = (content) => { return { content: content, pos: 0 } }; const eof = (stream) => (stream.pos >= stream.content.length); const peek = (stream) => { if (eof(stream)) return ''; return stream.content[stream.pos]; }; const consume = (stream) => { if (eof(stream)) return ''; const consumed = peek(stream); stream.pos++; return {consumed, stream}; }; const last = (stream, offset=1) => { const i = (stream.pos - offset); if (i < 0 || i >= stream.content.length) return ''; return stream.content[i]; }; const match = (stream, chr) => { if (eof(stream)) return {matches: false, stream}; const next = stream.content[stream.pos]; if (next == '') return {matches: false, stream}; const matches = (next == chr); if (matches) stream.pos++; return {matches, stream}; }; const any = (stream, any_of) => { if (eof(stream)) return {matches: false, stream}; const next = stream.content[stream.pos]; const matches = any_of.includes(next); if (matches) stream.pos++; return {matches, stream}; }; const whileMatch = (stream, chr) => { let matches = true; while (!eof(stream) && matches) { ({matches, stream} = match(stream, chr)); } return stream; }; const whileAny = (stream, any_of) => { let matches; let content = []; while (!eof(stream)) { ({matches, stream} = any(stream, any_of)); if (!matches) break; content.push(last(stream)); } content = content.join(''); return {content, stream}; }; const whileCondition = (stream, callable) => { let content = []; while (!eof(stream)) { const next = peek(stream); if (callable(next)) { ({consumed, stream} = consume(stream)); content.push(consumed); } else { break; } } content = content.join(''); return {content, stream}; }; const until = (stream, chr) => { let content = []; while (!eof(stream)) { ({consumed, stream} = consume(stream)); if (consumed == chr) break; content.push(consumed); } content = content.join(''); return {content, stream}; }; const matchStr = (stream, str) => { const checkpoint = stream.pos; for (const i in str) { const try_match = str[i]; ({matches, stream} = match(stream, try_match)); if (!matches) { stream.pos = checkpoint; return {matches: false, stream}; } } return {matches: true, stream}; }; const matchAnyStr = (stream, any_of) => { for (const i in any_of) { const str = any_of[i]; ({matches, stream} = matchStr(stream, str)); if (matches) { return {matches: true, stream}; } } return {matches: false, stream}; }; module.exports = { Stream, eof, peek, consume, last, match, any, whileMatch, whileAny, whileCondition, until, matchStr, matchAnyStr, }; <file_sep>/ygg/src/interpreter.js /** * This file provides a function `fold` that is able to fold an AST-ized grammar * into a member of that grammar. **/ const errors = require('./errors'); const foldDefine = (define, memory, input) => { [value, memory, input] = fold(define.statement, memory, input); memory[define.identifier.identifier] = value; return ['', memory, input]; }; const foldChoose = (choose, memory, input) => { const choices = choose.possibles.statements; const choice = choices[Math.floor(Math.random() * choices.length)]; return fold(choice, memory, input); }; const foldOptional = (optional, memory, input) => { if (Math.random() < 0.5) { return fold(optional.maybe, memory, input); } else { return ['', memory, input]; } }; const foldRegex = (regex, memory, input) => { ([literal_value, memory, input] = fold(regex.literal, memory, input)); let regexp; try { regexp = new RegExp(literal_value); } catch (err) { if (err instanceof SyntaxError) { throw errors.InterpreterRegexError(literal_value, err, regex.pos); } else { throw err; } } const matches = regexp.test(input); if (matches) { return fold(regex.left, memory, input); } else { return fold(regex.right, memory, input); } }; const foldIdentifier = (identifier, memory, input) => { identifier = identifier.identifier if (!(identifier in memory)) { throw errors.InterpreterUnknownIdentifierError(identifier, identifier.pos); } return fold(memory[identifier], memory, input); }; const foldLiteral = (literal, memory, input) => { return [literal.literal, memory, input]; }; const foldStatements = (statements, memory, input) => { const folds = []; for (const i in statements.statements) { const statement = statements.statements[i]; ([folded, memory, input] = fold(statement, memory, input)); folds.push(folded); } return [folds.join(''), memory, input]; }; const fold = (node, memory, input) => { if ((typeof node) === 'string') { return [node, memory, input]; } let folder; switch (node.type) { case 'Define': folder = foldDefine; break; case 'Choose': folder = foldChoose; break; case 'Optional': folder = foldOptional; break; case 'Identifier': folder = foldIdentifier; break; case 'Literal': folder = foldLiteral; break; case 'Statements': folder = foldStatements; break; case 'Regex': folder = foldRegex; break; default: throw `Unhandled node type '${node.type}'`; } return folder(node, memory, input); }; module.exports = {fold}; <file_sep>/ygg/src/ast.js /** * This file takes in plain source text for the grammar and transforms it into * an Abstract Syntax Tree. **/ const parser = require('./parser'); const errors = require('./errors'); /** Tokens **/ const Define = (identifier, statement, pos) => { return {type: 'Define', identifier, statement, pos}; }; const Choose = (possibles, pos) => { return { type: 'Choose', possibles, pos } }; const Optional = (maybe, pos) => { return { type: 'Optional', maybe, pos } }; const Identifier = (identifier, pos) => { return { type: 'Identifier', identifier, pos } }; const Regex = (literal, left, right, pos) => { return { type: 'Regex', literal, left, right, pos } }; const Literal = (literal, pos) => { return { type: 'Literal', literal, pos } }; const Statements = (statements, pos) => { return { type: 'Statements', statements, pos } }; /** Grammar literals **/ const WHITESPACE = [' ', '\t', '\n', '\r', '\v', '\f']; const isAlphaNumeric = (chr) => { const code = chr.charCodeAt(0); if (!(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } return true; }; const OP_DEFINE = '='; const OP_CHOOSE = '|'; const OP_OPTIONAL = '?'; const OP_REGEX = '&'; const OPERATORS = [OP_DEFINE, OP_CHOOSE, OP_OPTIONAL, OP_REGEX]; const LITERAL_DELIMITERS = ['"', '\'']; /** Parsing **/ const consumeWhitespace = (stream) => { ({content, stream} = parser.whileAny(stream, WHITESPACE)); return stream; }; const parseLiteral = (stream) => { const pos = stream.pos; ({matches, stream} = parser.any(stream, LITERAL_DELIMITERS)); if (!matches) { throw errors.AstExpectLiteralStartError(pos); } const delimiter = parser.last(stream); const total_content = []; while (true) { ({content, stream} = parser.until(stream, delimiter)); total_content.push(content); if (parser.eof(stream)) { throw errors.AstLiteralUnexpectedEOFError(pos); } else { if (parser.last(stream, 2) === '\\') { total_content.push(delimiter); } else { break; } } } return {literal: Literal(total_content.join(''), pos), stream}; }; const parseIdentifier = (stream) => { const pos = stream.pos; ({content, stream} = parser.whileCondition(stream, isAlphaNumeric)); if (content.length == 0) throw errors.AstExpectIdentifier(pos); return {identifier: Identifier(content, pos), stream}; }; const parseDefine = (stream) => { const pos = stream.pos; let identifier; ({identifier, stream} = parseIdentifier(stream)); stream = consumeWhitespace(stream); let statement; ({statement, stream} = parseStatement(stream)); return {define: Define(identifier, statement, pos), stream}; }; const parseChoose = (stream) => { const pos = stream.pos; stream = consumeWhitespace(stream); ({statements, stream} = parseStatements(stream)); return {choose: Choose(statements, pos), stream}; }; const parseOptional = (stream) => { const pos = stream.pos; ({statement, stream} = parseStatement(stream)); return {optional: Optional(statement, pos), stream}; }; const parseRegex = (stream) => { const pos = stream.pos; let literal; ({literal, stream} = parseLiteral(stream)); stream = consumeWhitespace(stream); ({statement, stream} = parseStatement(stream)); const left = statement; stream = consumeWhitespace(stream); ({statement, stream} = parseStatement(stream)); const right = statement; const regex = Regex(literal, left, right, pos); return {regex, stream}; }; const parseOperator = (stream) => { for (const i in OPERATORS) { const operator = OPERATORS[i]; ({matches, stream} = parser.matchStr(stream, operator)); if (matches) { return {operator, stream}; } } throw new errors.AstExpectOperator(stream.pos); }; const parseOperation = (stream) => { ({operator, stream} = parseOperator(stream)); stream = consumeWhitespace(stream); let statement; switch (operator) { case OP_DEFINE: ({define, stream} = parseDefine(stream)); statement = define; break; case OP_CHOOSE: ({choose, stream} = parseChoose(stream)); statement = choose; break; case OP_OPTIONAL: ({optional, stream} = parseOptional(stream)); statement = optional; break; case OP_REGEX: ({regex, stream} = parseRegex(stream)); statement = regex; break; default: throw new Error(`Unimplemented operator '${operator}'!`); } return {statement, stream}; }; const parseStatement = (stream) => { let statement; const next_char = parser.peek(stream); if (next_char == '(') { ({statements, stream} = parseStatements(stream)); statement = statements; } else { if (LITERAL_DELIMITERS.includes(next_char)) { ({literal, stream} = parseLiteral(stream)); statement = literal; } else { if (isAlphaNumeric(next_char)) { ({identifier, stream} = parseIdentifier(stream)); statement = identifier; } else { // Backtrack to be able to provide better errors const backtrack = stream.pos; ({matches} = parser.matchAnyStr(stream, OPERATORS)); if (matches) { stream.pos = backtrack; ({statement, stream} = parseOperation(stream)); } else { throw errors.AstExpectStatement(stream.pos); } } } } return {statement, stream}; }; const parseStatements = (stream) => { const start_pos = stream.pos; ({matches, stream} = parser.match(stream, '(')); if (!matches) { throw errors.AstExpectStatements(stream.pos); } stream = consumeWhitespace(stream); const statements = []; while (true) { if (parser.eof(stream)) { throw errors.AstUnclosedStatements(start_pos); } ({matches, stream} = parser.match(stream, ')')); if (matches) { break; } ({statement, stream} = parseStatement(stream)); statements.push(statement); stream = consumeWhitespace(stream); } return {statements: Statements(statements, stream.pos), stream}; }; const astize = (grammar) => { let stream = parser.Stream(grammar); stream = consumeWhitespace(stream); ({statements} = parseStatements(stream)); return statements; }; module.exports = { astize, Define, Choose, Optional, Identifier, Literal, Statements, }; <file_sep>/ygg/src/errors.js /** * This file provides objects for parsing and interpreting error reporting. */ const InterpreterUnknownIdentifierError = (identifier, pos) => { return {ygg: true, type: 'InterpreterUnknownIdentifierError', identifier, pos}; }; const InterpreterRegexError = (literal, regex_error, pos) => { return {ygg: true, type: 'InterpreterRegexError', literal, regex_error, pos}; }; const AstExpectLiteralStartError = (pos) => { return {ygg: true, type: 'AstExpectLiteralStartError', pos}; }; const AstLiteralUnexpectedEOFError = (start_pos) => { return {ygg: true, type: 'AstLiteralUnexpectedEOFError', start_pos}; }; const AstExpectIdentifier = (pos) => { return {ygg: true, type: 'AstExpectIdentifier', pos}; }; const AstExpectOperator = (pos) => { return {ygg: true, type: 'AstExpectOperator', pos}; }; const AstExpectStatement = (pos) => { return {ygg: true, type: 'AstExpectStatement', pos}; }; const AstExpectStatements = (pos) => { return {ygg: true, type: 'AstExpectStatements', pos}; }; const AstUnclosedStatements = (start_pos) => { return {ygg: true, type: 'AstUnclosedStatements', start_pos}; }; const printAt = (source, pos) => { // 0 indexed lines! To be consistent with pos. const line_idx = source.slice(0, pos).split('\n').length - 1; let col; if (line_idx == 0) { col = pos; } else { col = pos - source.slice(0, pos).lastIndexOf('\n') } const line_end_idx = source.slice(pos).indexOf('\n'); let line; if (line_end_idx === -1) { line = source.slice(line_idx); } else { line = source.slice(line_idx, line_end_idx - line_idx); } console.error(`Line ${line_idx}, column ${col},`) console.error('| ', line); console.error('| ', [' '.repeat(col), '^ Here'].join('')); }; const prettyPrint = (source, err) => { switch (err.type) { case 'InterpreterUnknownIdentifierError': console.error(`Identifier '${err.identifier}' used before definition.`); printAt(source, err.pos); console.error('Hint: You need to define this value first, with'); console.error(` = ${err.identifier} <value>`); break; case 'InterpreterRegexError': console.error(err.regex_error.message); printAt(source, err.pos); break; case 'AstExpectLiteralStartError': console.error('Expected the start of a literal, with " or \'.'); printAt(source, err.pos); break; case 'AstLiteralUnexpectedEOFError': console.error( 'Literal started, but not ended (found end of file instead).'); printAt(source, err.start_pos); break; case 'AstExpectIdentifier': console.error('Expected an identifier (numbers and letters) here.'); printAt(source, err.pos); break; case 'AstExpectOperator': console.error('Expected an operator (one of "=", "|", "&", "?") here.'); printAt(source, err.pos); break; case 'AstExpectStatement': console.error( 'Expected some statement (literal, operation, identifier, group of statements) here.'); printAt(source, err.pos); break; case 'AstExpectStatements': console.error('Expected a bracketed group of statements here.'); printAt(source, err.pos); break; case 'AstUnclosedStatements': console.error( 'Bracketed group of statements was started, but never closed (found end of file instead).'); printAt(source, err.start_pos); break; default: // Either not implemented or another type of error if ('type' in err) { console.warn('Possibly unimplemented error type ', err.type); } throw err; } }; module.exports = { InterpreterUnknownIdentifierError, InterpreterRegexError, AstExpectLiteralStartError, AstLiteralUnexpectedEOFError, AstExpectIdentifier, AstExpectOperator, AstExpectStatement, AstExpectStatements, AstUnclosedStatements, prettyPrint };<file_sep>/ygg/src/wrangler.js /** * This module semi-compiles an AST into a javascript module, exposing a * `generate(input)` function. */ const {astize} = require('./ast'); function Wrangler() { return { source: '', defines: {}, returnConstant: function(value) { return {type: 'Constant', value}; }, returnMangle: function(value) { return {type: 'Mangled', value}; }, getMangled: function() { // Fairly HACKy but it's unlikely to have colliding mangled names. return `_${Math.floor(Math.random() * 1000000000000000)}`; }, registerDecl: function(declaration) { this.source += declaration + '\n'; }, foldLiteral: function(literal) { return this.returnConstant(literal.literal); }, foldIdentifier: function(identifier) { if (identifier in this.defines) { return this.defines[identifier.identifier]; } else { throw 'Trying to fold identifier before initialization.'; } }, foldDefine: function(define) { if (define.statement.type == 'Constant') { const folded = this.returnConstant(define.statement.literal); this.defines[define.identifier.identifier] = folded; return folded; } else { // Define the body, so that identifier can point at body const mangled_body = this.returnMangle(this.fold(define.statement)); this.defines[define.identifier.identifier] = mangled_body; return mangled_body; } }, foldChoose: function(choose) { // Define each of the choices const folded_choices = []; for (const i in choose.possibles.statements) { const possible = choose.possibles.statements[i]; folded_choices.push(this.fold(possible)); } // The body is a random choice of these const choice_mangled = this.getMangled(); let declaration = `const ${choice_mangled} = (input) => { ` declaration += 'const choices = ['; for (const i in folded_choices) { const {type, value} = folded_choices[i]; if (i > 0) { declaration += ', '; } if (type == 'Constant') { // Folded is a string declaration += `"${value}"`; } else { // Folded is a mangled name declaration += `${value}`; } } declaration += ']; ' + 'const choice = choices[Math.floor(Math.random()*choices.length)]; ' + 'if ((typeof choice) === \'string\') { return choice; } else { return choice(input); }' + '};'; this.registerDecl(declaration); return this.returnMangle(choice_mangled); }, foldOptional: function(optional) { // Define body const body = this.fold(optional.maybe); const mangled_name = this.getMangled(); let declaration = `const ${ mangled_name} = (input) => { if (Math.random() < 0.5) { return `; if (body.type === 'Constant') { declaration += `"${body.value}"`; } else { const mangled_body = body.value; declaration += `${mangled_body}(input)`; } declaration += '; } return "";};'; this.registerDecl(declaration); return this.returnMangle(mangled_name); }, foldStatements: function(statements) { if (statements.statements.length == 0) return this.returnConstant(''); const folded_statements = []; for (const i in statements.statements) { const statement = statements.statements[i]; const folded = this.fold(statement); if (folded.type === 'Constant' && folded_statements.length > 0 && folded_statements[i - 1].type === 'Constant') { folded_statements[i - 1].value += folded.value; } else { folded_statements.push(folded); } } if (folded_statements.length == 1) { if (folded_statements[0].type === 'Constant') { return this.returnConstant(folded_statements[0].value); } else { return this.returnMangle(folded_statements[0].value); } } const mangled_name = this.getMangled(); let declaration = `const ${mangled_name} = (input) => { return `; for (const i in folded_statements) { const folded = folded_statements[i]; if (i > 0) declaration += ' + '; if (folded.type === 'Constant') { declaration += `"${folded.value}"`; } else { declaration += `${folded.value}(input)`; } } declaration += '; };'; this.registerDecl(declaration); return this.returnMangle(mangled_name); }, foldRegex: function(regex) { // Fold left and right expressions const folded_left = this.fold(regex.left); const folded_right = this.fold(regex.right); const mangled_name = this.getMangled(); let declaration = `const ${mangled_name} = (input) => { if (/${ regex.literal.literal}/.test(input)) { `; if (folded_left.type === 'Constant') { declaration += `return "${folded_left.value}"`; } else { declaration += `return ${folded_left.value}(input)`; } declaration += '; } else { '; if (folded_right.type === 'Constant') { declaration += `return "${folded_right.value}"`; } else { declaration += `return ${folded_right.value}(input)`; } declaration += '; }};'; this.registerDecl(declaration); return this.returnMangle(mangled_name); }, fold: function(node) { switch (node.type) { case 'Literal': return (this.foldLiteral)(node); case 'Identifier': return (this.foldIdentifier)(node); case 'Define': return (this.foldDefine)(node); case 'Choose': return (this.foldChoose)(node); case 'Optional': return (this.foldOptional)(node); case 'Statements': return (this.foldStatements)(node); case 'Regex': return (this.foldRegex)(node); default: throw new Error(`Unhandled node type '${node.type}'`); } }, wrangle: function(grammar) { const root = astize(grammar); const folded_root = this.fold(root); if (folded_root.type === 'Constant') { this.registerDecl( `module.exports = { generate: () => "${folded_root.value}" };`); } else { this.registerDecl( `module.exports = { generate: ${folded_root.value} };`); } } }; }; module.exports = { Wrangler };
5917661341977808e2fd3ba56b2741c80805e881
[ "JavaScript", "Markdown" ]
8
JavaScript
mikeevmm/YGG
ab0970609c09e93c1a8dcd13ad4e6618e76f8deb
6cf1c600919a4e1fa23e60a074c8934532f92b86
refs/heads/master
<file_sep>import xarray as xr #import netCDF4 import json import pandas as pd import numpy as np import pytz import pyproj import os import benchmark from datetime import datetime, timedelta from dispel4py.workflow_graph import WorkflowGraph from dispel4py.provenance import * from dispel4py.base import create_iterative_chain, ConsumerPE, IterativePE, SimpleFunctionPE class ReadCSV(GenericPE): def __init__(self): GenericPE.__init__(self) self._add_input('input') self._add_output('csv_output') self._add_output('csv_file') def _process(self,inputs): self.log('Reading CSV') csvFile = inputs['input'][0] csvMeta = inputs['csv_desc'][0] headerText = self.readHeaderLines(csvFile) self.invalidDateTime = np.datetime64('4000-01-01') # TODO: if needed port the json handling method self.metaCSVdict = self.readJson(csvMeta) delimiter = self.metaCSVdict['csvSeparator'] columnsList = [] columnsList.append(self.metaCSVdict['columnDate']) columnsList.append(self.metaCSVdict['columnHour']) columnsList.append(self.metaCSVdict['columnMinute']) columnsList.append(self.metaCSVdict['columnX']) columnsList.append(self.metaCSVdict['columnY']) self.dataUnsortedStr = np.recfromtxt(csvFile, skip_header=self.numHeaderLines, comments="#", dtype="|S300", delimiter=delimiter) self.dataColumns = self.dataUnsortedStr[:, columnsList ] rowCounter = 0 queryDataArray = [] for oneRow in self.dataColumns: (utcTimeStr, utcTime) = self.decodeDateTime(dateStr=oneRow[0], hourStr=oneRow[1], minuteStr=oneRow[2]) if utcTimeStr==None: # None means INVALID request! dataRow = [rowCounter, self.invalidDateTime, "INVALID", float(oneRow[3]), float(oneRow[4])] # store [id, utc-time, utc-time-str, X-coord, Y-coord ] queryDataArray.append(dataRow) else: dataRow = [rowCounter, np.datetime64(utcTime), utcTimeStr, float(oneRow[3]), float(oneRow[4])] # store [id, utc-time, utc-time-str, X-coord, Y-coord ] queryDataArray.append(dataRow) rowCounter += 1 # Translate the python list to a 2 dimensional numpy array of [ [id, utc-time, X-coord, Y-coord], ... ] queryDataNPA = np.array(queryDataArray) self.timeUnits = "" # self.metaData.variables['time'].units self.dateTimeArray = queryDataNPA[:, 1] # remove invalid dateTime records from the array indexDelete = np.where(self.dateTimeArray == self.invalidDateTime) # reserved for "INVALID" self.dateTimeArrayClean = np.delete(self.dateTimeArray, indexDelete) # np.datetime64 => datetime; The date-time must be in UTC self.minDateTime = np.min(self.dateTimeArrayClean).astype(datetime.datetime).replace(tzinfo=pytz.UTC) self.maxDateTime = np.max(self.dateTimeArrayClean).astype(datetime.datetime).replace(tzinfo=pytz.UTC) fmt = '%Y-%m-%d %H:%M:%S %Z' self.minDateTime_str = self.minDateTime.strftime(fmt) self.maxDateTime_str = self.maxDateTime.strftime(fmt) queryDataNPAdt = queryDataNPA # create sorted 2-dimensional array self.queryDataNPAdt = queryDataNPAdt self.projFuncDefstring = self.metaCSVdict['projString'] self.projectionFunction = pyproj.Proj(self.projFuncDefstring) # 2-dimensional numpy array [ [id, utc-time, X-coord, Y-coord ], .. ] sorted by utc time xcoords = queryDataNPAdt[:, 3] # still a 1-dimensional numpy array of strings ycoords = queryDataNPAdt[:, 4] # still a 1-dimensional numpy array of strings (longitudes,latitudes) = self.unproject2LongitudeLatitudes(xcoords, ycoords) lonLatStacked = np.vstack((longitudes,latitudes)).T # print lonLatStacked # Determine the bounding box. self.llbox_west = np.min(longitudes) self.llbox_east = np.max(longitudes) self.llbox_north = np.max(latitudes) self.llbox_south = np.min(latitudes) self.queryDataNPAdtsLL = np.vstack((queryDataNPAdt[:, 0], queryDataNPAdt[:, 1], longitudes, latitudes)).T # self.log(self.queryDataNPAdtsLL) self.write('csv_file', csvFile) self.write('csv_output', self.queryDataNPAdtsLL) def readHeaderLines(self, fileName): self.numHeaderLines = 1 headerText = "" n = self.numHeaderLines ftxt = open(fileName,'rU') while n>0: ln = ftxt.readline() if not ln: break headerText += ln.rstrip('\n') n -= 1 ftxt.close() return headerText def readJson(self, fileName): with open(fileName) as json_file: data = json.load(json_file) return data def decodeDateTime(self, dateStr, hourStr, minuteStr): if self.metaCSVdict['dateFormat'] == "%d%b%y": givenDate = datetime.datetime.strptime(dateStr, "%d%b%y") if self.metaCSVdict['hourFormat'] == "hourInterval": try: if '-' in hourStr: hour = float(hourStr.split('-')[0]) else: hour = float(hourStr[:3]) except: if self.autoResolve_hour>0: hour = self.autoResolve_hour else: try: minute = int(minuteStr) self.log('WARNING: could not extract (hour) from: "(%s)"' %(hourStr) ) except: self.log('WARNING: could not extract (hour & minute) from: "(%s,%s)"' %(hourStr, minuteStr)) return None,None # this mean INVALID request try: minute = int(minuteStr) except: if self.autoResolve_minute>0: minute = self.autoResolve_minute else: self.log('WARNING: could not extract minute from: "%s"' %(minuteStr) ) return None, None # this mean INVALID request localTime = givenDate + timedelta(hours=hour, minutes=minute) (utcTime, datetime_in_utc_str, datetime_with_tz_str) = self.convertLocalDateTime2Utc(localTime, zone=self.metaCSVdict['timeZone']) fmt = '%Y-%m-%d %H:%M:%S %Z' utcTimeStr = utcTime.strftime(fmt) return (utcTimeStr, utcTime) def convertLocalDateTime2Utc(self,datetime_without_tz, zone): fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' local_tz = pytz.timezone(zone) needToDecide = False try: datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=None) # No daylight saving time except pytz.exceptions.AmbiguousTimeError: needToDecide = True except pytz.exceptions.NonExistentTimeError: needToDecide = True if needToDecide: datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=False) datetime_in_utc = datetime_with_tz.astimezone(pytz.utc) datetime_with_tz_str = datetime_with_tz.strftime(fmt) datetime_in_utc_str = datetime_in_utc.strftime(fmt) return (datetime_in_utc, datetime_in_utc_str, datetime_with_tz_str) def unproject2LongitudeLatitudes(self, xcoords, ycoords): LL = self.projectionFunction(xcoords, ycoords, inverse=True) longitudes = LL[0] latitudes = LL[1] return (longitudes, latitudes) # tuple, vector class ReadNETCDF(GenericPE): def __init__(self): GenericPE.__init__(self) self._add_input('input') self._add_output('netcdf_out') def _process(self,inputs): self.log('Reading NetCDF') netcdfFile = inputs['input'][0] fmt = '%Y-%m-%d %H:%M:%S %Z' #open NetCDF dataset with xarray ds = xr.open_dataset(netcdfFile) #Time variables dt = ds['time'] #date-time DataArray timeDim = dt.shape[0] minDateTimeArray = np.min(dt) #returns minDate in a DataArray maxDateTimeArray = np.max(dt) minDateTime = minDateTimeArray.values #gets the value out of the DataArray maxDateTime = maxDateTimeArray.values minDateTime_conv = pd.to_datetime(minDateTime) #converts numpy datetime64 to datetime (better for readability) # minDataTime_str = minDateTime_conv.strftime(fmt) maxDateTime_conv = pd.to_datetime(maxDateTime) # maxDataTime_str = maxDateTime_conv.strftime(fmt) timeDelta = np.timedelta64(dt[1].values - dt[0].values, 'm') #time delta between consecutive measurements in minutes #Spatial variables dx = ds['x'] dy = ds['y'] xDim = dx.shape[0] yDim = dy.shape[0] gridSize = xDim * yDim xAxis = dx.data[:] yAxis = dy.data[:] self.xcoords, self.ycoords = np.meshgrid(xAxis, yAxis) self.projFuncDefstring = ds['projection'].proj4_params self.projectionFunction = pyproj.Proj(self.projFuncDefstring) (self.longitudes,self.latitudes) = self.unproject2LongitudeLatitudes(self.xcoords, self.ycoords) self.lonLatStacked = np.hstack((self.longitudes.reshape(gridSize,1),self.latitudes.reshape(gridSize,1))) self.llbox_west = np.min(self.longitudes) self.llbox_east = np.max(self.longitudes) self.llbox_north = np.max(self.latitudes) self.llbox_south = np.min(self.latitudes) ds.__setitem__('lonLatStacked', (['locations', 'coordinates'], self.lonLatStacked)) self.write('netcdf_out', ds) def unproject2LongitudeLatitudes(self, xcoords, ycoords): LL = self.projectionFunction(xcoords, ycoords, inverse=True) longitudes = LL[0] latitudes = LL[1] return longitudes, latitudes # tuple, vector class ProcessData(GenericPE): def __init__(self): GenericPE.__init__(self) self._add_input('csvData', grouping=[1]) self._add_input('netcdfData', grouping=[1]) self._add_output('output') self.csv=[] self.netcdf=[] def _process(self,inputs): self.log('Processing Data') # function used for getting the distance between 2 points geoTransfWGS84 = pyproj.Geod(ellps='WGS84') self.geoTransf = geoTransfWGS84 if 'csvData' in inputs.keys(): self.csv.append(inputs['csvData']) if 'netcdfData' in inputs.keys(): self.netcdf.append(inputs['netcdfData']) if (len(self.csv)>0 and len(self.netcdf)>0): self.csvData = self.csv.pop(0) self.netcdfData = self.netcdf.pop(0) self.dateTimeArray = self.netcdfData['time'].values dx = self.netcdfData['x'] self.xDim = dx.shape[0] variableName = 'precipitation_amount' valueList = [] for timeLonLat in self.csvData: idn = timeLonLat[0] utcTime = timeLonLat[1] lon = timeLonLat[2] lat = timeLonLat[3] value = self.GetValue_time_lon_lat(variableName, utcTime, lon, lat) valueList.append(value) valueArray = np.array(valueList) processedData = np.hstack((self.csvData, valueArray.reshape(valueArray.shape[0], 1))) self.write('output', processedData) def GetValue_time_lon_lat(self, variableName, utcTime, lon, lat): closestDateTimeIndex = self.FindClosestDateTimeIndex(utcTime) minDistanceDataIndex = self.FindClosestLonLatPointIndex(lon, lat) dataValue = self.GetDataAtIndex(closestDateTimeIndex, minDistanceDataIndex, variableName=variableName) return dataValue def FindClosestDateTimeIndex(self, time): closestTime = self.FindClosestDateTime(time, self.dateTimeArray) closestTimeIndex = np.where(self.dateTimeArray == closestTime)[0][0] return closestTimeIndex def FindClosestDateTime(self, givenDateTime, dateTimeList): pivot = np.datetime64(givenDateTime) result = min(dateTimeList, key=lambda x: abs(x - pivot)) return result def FindClosestLonLatPointIndex(self, lon, lat): self.givenLon = lon self.givenLat = lat idx = 0 distArray = np.zeros(self.netcdfData['lonLatStacked'].shape[0]) coordinatesArray = self.netcdfData['lonLatStacked'].values for tupleLL in coordinatesArray: dist = self.Distance2pointsInLonLat(lon, lat, tupleLL[0], tupleLL[1]) distArray[idx] = dist idx +=1 minDist = np.min(distArray) minDistIndex = np.where(distArray == minDist)[0][0] return minDistIndex def Distance2pointsInLonLat(self, lng1,lat1,lng2,lat2): #global geoTransfWGS84 #geoTransfWGS84 az12,az21,dist = self.geoTransf.inv(lng1,lat1,lng2,lat2) return dist def GetDataAtIndex(self, timeIndex, dataIndex, variableName='precipitation_amount'): idX = dataIndex % self.xDim idY = dataIndex / self.xDim # variableFound = self.GetVariable(variableName) # if variableFound: # dataValue = variableFound[timeIndex][idY][idX] # return dataValue # else: # return None # 'image1_image_data' holds the 'precipitation_amount' data valueDataArray = self.netcdfData['image1_image_data'][timeIndex][idY][idX] dataValue = valueDataArray.values.item(0) return dataValue #needs to be adapted to xarray def GetVariable(self, variableName): keylist = self.metaData.variables.keys() variableFound = None for k in keylist: try: if self.metaData.variables[k].standard_name == variableName: # self.metaData.variables['image1_image_data'].standard_name == variableName .. variableFound = self.metaData.variables[k] except: pass return variableFound class StoreData(GenericPE): def __init__(self): GenericPE.__init__(self) self._add_input('wrangler_output') self._add_input('csv_file') self.csv = False self.wrangler = False def _process(self,inputs): self.log('Storing Data') outputLocation = "output/wrangled_data.csv" parameterList = ["utc-time", "longitude", "latitude", "precipitation_amount"] if 'csv_file' in inputs.keys(): csvFile = inputs['csv_file'] self.csvHeader = self.readHeaderLines(csvFile) self.csvContent = np.recfromtxt(csvFile, skip_header=1, comments="#", dtype="|S300", delimiter=',') self.csv = True if 'wrangler_output' in inputs.keys(): self.wranglerResults = inputs['wrangler_output'] self.wrangler = True if self.csv and self.wrangler: for item in parameterList: self.csvHeader += ',%s' %item finalStack = np.hstack((self.csvContent, self.wranglerResults[:,1:])) np.savetxt(outputLocation, finalStack, fmt='%s', delimiter=',', header=self.csvHeader) def readHeaderLines(self, fileName): self.numHeaderLines = 1 headerText = "" n = self.numHeaderLines ftxt = open(fileName, 'rU') while n > 0: ln = ftxt.readline() if not ln: break headerText += ln.rstrip('\n') n -= 1 ftxt.close() return headerText def createWorkflow(): read_csv = ReadCSV() read_csv.name = 'CSV' read_netcdf = ReadNETCDF() read_netcdf.name = 'NETCDF' compute = ProcessData() store = StoreData() store.name = 'STORE' graph = WorkflowGraph() graph.connect(read_csv, 'csv_output', compute, 'csvData') graph.connect(read_netcdf, 'netcdf_out', compute, 'netcdfData') graph.connect(read_csv, 'csv_file', store, 'csv_file') graph.connect(compute, 'output', store, 'wrangler_output') return graph workflow_graph = createWorkflow() # from dispel4py.visualisation import display # display(workflow_graph) # csv with 10 lines: 'data/accident_data_10.csv' # csv with 100 lines: 'data/accident_data_100.csv' input_data = {'CSV': [{'input': ['data/accident_data_100.csv'], 'csv_desc': ['data/metaDataCsv.json']}], 'NETCDF': [{'input': ['http://opendap.knmi.nl/knmi/thredds/dodsC/DATALAB/hackathon/radarFull2006.nc']}]} def runWorkflow(): print input_data # Launch in simple process result = simple_process.process_and_return(workflow_graph, input_data) print "\n RESULT: "+str(result) class BenchmarkWrangler(benchmark.Benchmark): each = 50 # allows for differing number of runs def test_dispel4py_wrangler(self): runWorkflow() benchmark.main(format="markdown", numberFormat="%.4g") <file_sep># wrangler Data Wrangler implementation using dispel4py
f74f48161604263c26aa4b27d66bf1742ae0b9da
[ "Markdown", "Python" ]
2
Python
AndreiFrunze/wrangler
076a07de00fc966dcf18ca6b6a6e804be5245ed9
50921bc6e3817f8a43d30ebc0a9e5d402a739e46
refs/heads/master
<file_sep>#!/bin/sh # get up to date sudo dnf -y upgrade # enable rpmfusion free/nonfree sudo dnf install https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm sudo dnf install -y rpmfusion-free-release-tainted sudo dnf install -y libdvdcss sudo dnf install -y rpmfusion-nonfree-release-tainted sudo dnf install -y *-firmware sudo dnf -y groupupdate core sudo dnf -y groupupdate multimedia --setop="install_weak_deps=False" --exclude=PackageKit-gstreamer-plugin sudo dnf -y groupupdate sound-and-video # install apps via terminal sudo dnf install -y gnome-tweak-tool sudo dnf install gstreamer1-{plugin-crystalhd,ffmpeg,plugins-{good,ugly,bad{,-free,-nonfree,-freeworld,-extras}{,-extras}}} libmpg123 lame-libs --setopt=strict=0 -y sudo dnf -y install unzip p7zip p7zip-plugins unrar sudo dnf -y install gparted sudo dnf copr enable dawid/better_fonts sudo dnf install -y fontconfig-enhanced-defaults fontconfig-font-replacements <file_sep>#!/usr/bin/env python3 from enum import Enum import sys import os class CONSTANTS(Enum): EXTENSION = 'qcow2' SIZE = 30 MEMORY = 2048 class QEMU: def __init__(self, name): self.name=name self.relative_drive_path = '{name}.{extension}'.format(name=name, extension=CONSTANTS.EXTENSION.value) self.absolute_drive_path = os.path.join(os.getcwd(), self.relative_drive_path) pass def create_img(self, size='30G'): os.system(""" qemu-img create -f {extension} {name}.{extension} {size}G """.format( name=self.name, extension=CONSTANTS.EXTENSION.value, size=CONSTANTS.SIZE.value )) def execute_img(self, cdrom_path=None): command = """ qemu-system-x86_64 \ -device intel-hda -device hda-duplex \ -cpu host \ -enable-kvm \ -smp 2 \ -m {memory} \ -net user \ -nic user \ -drive file={drive_path},media=disk \ """.format( memory=CONSTANTS.MEMORY.value, drive_path=self.absolute_drive_path, ) if cdrom_path: print('CDROM IS NOT EMPTY: {}'.format(cdrom_path)) command += """ -cdrom {cdrom_path} \ """.format(cdrom_path=cdrom_path) else: print('CDROM IS EMPTY') print(command) os.system(command) if __name__ == '__main__': qemu = QEMU(name=sys.argv[2]) if sys.argv[1] == 'create': qemu.create_img() elif sys.argv[1] == 'execute': arg_cdrom_path = None if '--cdrom' in sys.argv: arg_cdrom_path = sys.argv[4] qemu.execute_img(cdrom_path=arg_cdrom_path) <file_sep>#!/bin/sh # install oh-my-zsh sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" # clone plugins git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting # add plugins to ~/.zshrc # plugins = ( [plugins...] zsh-autosuggestions zsh-history-substring-search zsh-syntax-highlighting) # Note: make sure zsh-syntax-highlighting is the last one in the above list. # fix background theme issues # ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=white' source ~/.zshrc <file_sep>#!/usr/bin/env python3 import os, sys class App: def take_values(self): mail = input('==> enter your mail: ') cmd = 'ssh-keygen -t rsa -b 4096 -C "'+mail+'"' os.system(cmd) def check_sshagent(self): print('==> CHECK SSH AGENT') os.system('eval "$(ssh-agent -s)"') def add_ssh(self): print("==> ADDING SSH") os.system('ssh-add ~/.ssh/id_rsa') def print_pub(self): print("==> ID RSA PUB") os.system('cat ~/.ssh/id_rsa.pub') def check_git(self): print("==> CHECK GIT") os.system('ssh -T git@github.com') def main(self): self.take_values() self.check_sshagent() self.add_ssh() self.print_pub() self.check_git() if sys.platform == 'linux' and __name__ == '__main__': app = App() app.main() <file_sep>#!/bin/sh # ubuntu xenial (16.04) - post install # # maybe it's useless for your ubuntu # but i think it's quite useful for me # update system sudo apt update && sudo apt -y upgrade # install restricted extras sudo apt -y install ubuntu-restricted-extras # install apps sudo apt -y install vlc tlp tlp-rdw bleachbit unity-tweak-tools # start tlp sudo tlp start # minimise on click gsettings set org.compiz.unityshell:/org/compiz/profiles/unity/plugins/unityshell/ launcher-minimize-window true # remove amazon shitty stuff sudo apt -y purge ubuntu-web-launchers sudo apt -y purge ubuntu-webapps-common sudo rm /usr/share/applications/ubuntu-amazon-default.desktop sudo rm /usr/share/unity-webapps/userscripts/unity-webapps-amazon/Amazon.user.js sudo rm /usr/share/unity-webapps/userscripts/unity-webapps-amazon/manifest.json # brave browser sudo apt -y install apt-transport-https curl curl -s https://brave-browser-apt-release.s3.brave.com/brave-core.asc | sudo apt-key --keyring /etc/apt/trusted.gpg.d/brave-browser-release.gpg add - echo "deb [arch=amd64] https://brave-browser-apt-release.s3.brave.com/ stable main" | sudo tee /etc/apt/sources.list.d/brave-browser-release.list sudo apt update sudo apt -y install brave-browser # install keepassxc sudo add-apt-repository ppa:phoerious/keepassxc sudo apt update sudo apt -y install keepassxc <file_sep>#!/bin/sh gsettings set org.gnome.desktop.wm.preferences action-middle-click-titlebar 'minimize' gsettings set org.gnome.desktop.wm.preferences resize-with-right-button true <file_sep>#!/bin/sh SELECTED="$(xclip -o)" FILE="$HOME/.local/share/bookmarks" check_bookmarks () { if ! [ -e $FILE ]; then touch $FILE echo "Created: $FILE." fi } new_bookmark () { if ! grep -qF "$SELECTED" "$FILE"; then echo "$SELECTED" >> "$FILE" echo "New bookmark: '$SELECTED' added." else echo "It already exists ('$SELECTED')." fi } check_bookmarks new_bookmark <file_sep>#!/bin/sh qemu-system-x86_64 \ -enable-kvm \ -m 1024 \ -net user,smb=/home/admarmn/Belgeler/VMShare/ \ -nic user \ -drive file=/home/admarmn/Belgeler/win8.1-qemu/windows8-1.qcow2,media=disk \ -cdrom /home/admarmn/Masaüstü/Win8.1_Turkish_x64.iso \ # INSTALLATION COMMAND #qemu-img create -f qcow2 windows8-1.qcow2 20G # DISABLED #-nic user,model=virtio \ #-drive file=/home/admarmn/Belgeler/win8.1-qemu/windows8-1.qcow2,media=disk,if=virtio \ <file_sep>#!/usr/bin/env python3 import os cmds = [ 'xrandr --newmode "1600x900_60.00" 119.00 1600 1696 1864 2128 900 901 904 932 -HSync +Vsync', 'xrandr --addmode Virtual1 "1600x900_60.00"', 'xrandr --output Virtual1 --mode "1600x900_60.00"' ] for cmd in cmds os.system(cmd) <file_sep>#!/usr/bin/env python3 import os, sys passwd_download_url = 'https://drive.google.com/u/0/uc?id=1oLlH1hNfrDq6qRsAs4nOlLLvcHYDMaRI&export=download' def main(): if os.path.exists('/usr/bin/chromium'): os.system('chromium ' + passwd_download_url) else: print("couldn't find the chromium browser") main() <file_sep>#!/usr/bin/env python3 import os, sys # ./dconf.py --dump settings.ini # ./dconf.py --load settings.ini class dconfy: ini_path = "" def init(self, path): self.ini_path = path return def dump(self): os.system("dconf dump / > " + self.ini_path) return def load(self): os.system("dconf load / < " + self.ini_path) return def main(): option = sys.argv[1] path = sys.argv[2] dc = dconfy() dc.init(path) if option == "--dump": dc.dump() elif option == "--load": dc.load(); else: print("unexpected params!") try: main() except: print("\n") print("true usage\n==========") print(" -> ./dconf.py --dump <*.ini>") print(" -> ./dconf.py --load <*.ini>") print("\n") main() <file_sep>#!/usr/bin/env python3 import os, sys def print_err(msg=None): print('\t\t[egit ERR_!]') if msg != None: print('==> %r' % msg) else: print('\tan error occured') class MainApplication: username = 'lovisestdeus' repository = None folder = None method = 'https' def __init__(self): if len(sys.argv) > 1: self.repository = str(sys.argv[1]) if len(sys.argv) > 2: if sys.argv[2] == 'ssh' or sys.argv[2] == 'https': if sys.argv[2] == 'https': self.method = 'https' elif sys.argv[2] == 'ssh': self.method = 'ssh' self.folder = self.repository else: self.folder = str(sys.argv[2]) if len(sys.argv) > 3: if sys.argv[3] == 'https': self.method = 'https' elif sys.argv[3] == 'ssh': self.method = 'ssh' else: self.folder = self.repository def print_info(self): print('\n\n\t\t\t[egit - EasyGiT]') print("\t\t[Method: %r] from %r 's %r repo to %r folder\n\n" % (str(self.method.upper()), str(self.username), str(self.repository), str(self.folder))) def clone(self): if self.method == 'https': os.system("git clone https://github.com/%r/%r %r" % (str(self.username), str(self.repository), str(self.folder))) if self.method == 'ssh': os.system("git clone git@github.com:%r/%r %r" % (str(self.username), str(self.repository), str(self.folder))) if sys.platform == 'linux' and \ __name__ == '__main__': app = MainApplication() if app.repository == None: print_err("you didn't enter the repo's name") else: app.print_info() app.clone()
cdbb03fbd52b724eb22d5151b932705c6601af0f
[ "Python", "Shell" ]
12
Shell
adewww/scripts
3842b62338ee469eea149d3af4813cff12eeb664
eaf20ede5558ba85c023e22bf084c22152d2e818
refs/heads/master
<file_sep>import React, { useContext } from 'react'; import { ChartDataContext } from '../context/ChartData.context'; import Bars from './Bars.component'; const BarChart = () => { const { data, hasPositiveValues, chartHeight } = useContext(ChartDataContext); let chartStyle = { height: chartHeight + '%' }; return ( <div className="bar-chart tile-container"> <div className={`bar-chart-container ${!hasPositiveValues ? 'only-negatives' : ''}`}> <div style={chartStyle} className="bar-chart-content"> <ChartScale/> <Bars/> </div> </div> </div> ); } const ChartScale = () => { const { scale } = useContext(ChartDataContext); return ( <div className="bar-chart-scale"> <div className="bar-chart-x-axis"></div> {scale.map((item, i) => ( <div key={i} className="bar-chart-scale-value" style={{bottom: item.height +'px'}}> <span> {item.value} </span> </div> ))} </div> ) } export default BarChart;<file_sep>import React, { useContext } from 'react'; import { ChartDataContext } from '../context/ChartData.context'; const Header = () => { return ( <div className="header"> <div className="logo"> <div className="logo-icon"> <div className="logo-icon-north"> <div className="logo-icon-bar logo-icon-bar-1"></div> <div className="logo-icon-bar logo-icon-bar-2"></div> <div className="logo-icon-bar logo-icon-bar-3"></div> <div className="logo-icon-bar logo-icon-bar-4"></div> <div className="logo-icon-bar logo-icon-bar-5"></div> <div className="logo-icon-bar logo-icon-bar-6"></div> <div className="logo-icon-bar logo-icon-bar-7"></div> </div> <div className="logo-icon-south"> <div className="logo-icon-bar logo-icon-bar-1"></div> <div className="logo-icon-bar logo-icon-bar-2"></div> <div className="logo-icon-bar logo-icon-bar-3"></div> <div className="logo-icon-bar logo-icon-bar-4"></div> <div className="logo-icon-bar logo-icon-bar-5"></div> <div className="logo-icon-bar logo-icon-bar-6"></div> <div className="logo-icon-bar logo-icon-bar-7"></div> </div> </div> <div className="logo-text"> elechart </div> </div> </div> ); } export default Header; // const { data } = useContext(ChartDataContext); // return ( // <div> // {data.map(item => { // return ( // <div key={item.id}>{`${item.name} ${item.value}`}</div> // ) // })} // </div> // );<file_sep>import React, {useContext} from 'react'; import { ChartDataContext } from '../context/ChartData.context'; const Info = () => { const { minValue, maxValue, avgValue } = useContext(ChartDataContext); return ( <div className="info tile-container"> <div className="info__indicator"> <span className="info__indicator-title">Average</span> <span className="info__indicator-value"> {avgValue} </span> </div> <div className="info__indicator"> <span className="info__indicator-title">Min</span> <span className="info__indicator-value"> {minValue} </span> </div> <div className="info__indicator"> <span className="info__indicator-title">Max</span> <span className="info__indicator-value"> {maxValue} </span> </div> </div> ) } export default Info;<file_sep>import React from 'react'; import './style/Default.style.scss'; import ChartDataContextProvider from './context/ChartData.context'; import Header from './components/Header.component'; import DataForm from './components/DataForm.component'; import BarChart from './components/BarChart.component'; import Legend from './components/Legend.component'; import Modal from './components/Modal.component'; import Info from './components/Info.component'; function App() { return ( <div className="app"> <ChartDataContextProvider> <div className="app-container"> <Header/> <div className="container"> <DataForm/> <div className="main-content"> <div className="row"> <div className="column col-xl-8"> <BarChart/> <Info/> </div> <div className="column col-xl-4"> <Legend/> </div> </div> </div> </div> </div> <Modal/> </ChartDataContextProvider> </div> ); } export default App; <file_sep>import React, { useContext } from 'react'; import { ChartDataContext } from '../context/ChartData.context'; const Modal = () => { const {modalState, ToggleModalState} = useContext(ChartDataContext); return ( modalState ? <div className="modal"> <div className="modal-mask" onClick={() => ToggleModalState()}> </div> <div className="modal-container"> <RemoveValueModal/> </div> </div> : null ); } const RemoveValueModal = () => { const { RemoveData, ToggleModalState, currentItem } = useContext(ChartDataContext); const removeValueText = "Are you sure you want to remove this value?"; return ( <div className="modal-remove-value"> <p>{removeValueText}</p> <div className="modal-button-box"> <button className="button-secondary button-default modal-button-cancel" onClick={() => ToggleModalState()}>Cancel</button> <button className="button-primary button-default modal-button-remove" onClick={() => RemoveData(currentItem)}>Remove</button> </div> </div> ) } export default Modal;<file_sep>import React, { useContext, useState } from 'react'; import { ChartDataContext } from '../context/ChartData.context'; const Bars = () => { const { data, maxValue, indexValue, hasPositiveValues, barHover, HighlightBar } = useContext(ChartDataContext); // const [ isHover, setIsHover ] = useState('') let setBarHeight = (value) => { let barHeight = (value / (hasPositiveValues ? maxValue : indexValue)) * 100; return barHeight + '%'; } let handleMouseOver = (id) => { HighlightBar(id); } let handleMouseOut = () => { HighlightBar(''); } return ( <div className="bar-chart-bars"> {data.map((item, i) => { return ( <div key={i} className="bar-container"> <div className={`bar ${item.value < 0 ? 'negative' : ''}`} style={{height: `${setBarHeight(Math.abs(item.value))}`}} onMouseOver={() => handleMouseOver(item.id)} onMouseOut={handleMouseOut} > <span className="bar-value-label"> {item.value} </span> </div> </div> ) })} </div> ); } export default Bars;<file_sep>export const DefaultState = [ { name: 'data1', value: 15, id: 1 }, { name: 'data3', value: 28, id: 2 }, { name: 'data1', value: -21, id: 3 }, { name: 'data3', value: 33, id: 4 }, { name: 'data1', value: 18, id: 5 }, { name: 'data3', value: 22, id: 6 }, { name: 'data1', value: -15, id: 7 }, { name: 'data3 very long value nam to test how it will behave', value: -30, id: 8 }, { name: 'data1', value: 30, id: 9 }, { name: 'data3', value: 33, id: 10 }, { name: 'data1', value: 18, id: 11 }, { name: 'data3', value: 22, id: 12 } ]<file_sep>import React, { useContext, useState, useRef, useEffect, Fragment } from 'react'; import { ChartDataContext } from '../context/ChartData.context'; const useComponentVisible = (initial) => { const { currentItem, GetCurrentItem} = useContext(ChartDataContext); const [isEditable, setIsEditable] = useState(initial); const ref = useRef(null); const handleClickOutside = async (event) => { if (ref.current && !ref.current.contains(event.target)) { setIsEditable(false); setTimeout(() => { GetCurrentItem(''); }) console.log('Clicked Outside') } }; useEffect(() => { if(isEditable) { document.addEventListener('click', handleClickOutside, true) return () => { document.removeEventListener('click', handleClickOutside, true); }; } }); return {ref, isEditable, setIsEditable}; } const Legend = () => { const { ref, isEditable, setIsEditable } = useComponentVisible(false); const { data, ToggleModalState, UpdateData, currentItem, GetCurrentItem, barHover, HighlightBar } = useContext(ChartDataContext); const [name, setName] = useState(''); const [value, setValue] = useState(''); const addEditClass = (id, name, value) => { GetCurrentItem(id); setName(name); setValue(value); setIsEditable(true); } const acceptChanges = (e, id) => { e.preventDefault(); UpdateData(id, name, value); GetCurrentItem(''); } let handleMouseOver = (id) => { HighlightBar(id); } let handleMouseOut = () => { HighlightBar(''); } return ( <div className="legend tile-container"> <ul ref={ref} className="legend-container"> {data.map(item => { return ( <li key={item.id} id={item.id} className={`legend-item ${currentItem === item.id ? 'legend-item-editable' : ''} ${barHover === item.id ? 'hovered' : ''}`} // onClick={currentItem !== item.id && !isEditable ? () => addEditClass(item.id, item.name, item.value) : null} onMouseOver={() => handleMouseOver(item.id)} onMouseOut={handleMouseOut} > {currentItem !== item.id ? ( <div className="legend-item-data" onClick={() => addEditClass(item.id, item.name, item.value)} > <div className="legend-item-data-name">{item.name}</div> <div className="legend-item-data-value">{item.value}</div> </div> ) : ( <form className="legend-item-form" onSubmit={(e) => acceptChanges(e, item.id)}> <div className="legend-item-form-name"> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="legend-item-form-value"> <input type="number" value={value} onChange={(e) => setValue(parseInt(e.target.value))} /> </div> <div className="toolbar-container"> <button type="submit" className="button-icon button-accept"><span>v</span></button> <button type="button" className="button-icon button-remove" onClick={() => ToggleModalState(item.id)}><span>x</span></button> </div> </form> )} {/* )} */} </li> ) })} </ul> </div> ); } // const DropdownList = (props) => { // return ( // <div className="dropdown-container"> // {props.children} // </div> // ) // } export default Legend;<file_sep>import { v4 as uuid } from 'uuid'; import { DefaultState } from './DefaultState'; export const reducer = (state = DefaultState, action) => { const newState = {...state}; switch (action.type) { case "ADD_DATA": console.log(state.data); return { ...state, data: state.data.concat( { name: action.name, value: action.value, id: uuid() } ) } break; case "REMOVE_DATA": return { ...state, data: state.data.filter(item => { return item.id !== action.id; }), showRemovePrompt: false, idToProcess: '' } break; case "OPEN_MODAL": return { ...state, showRemovePrompt: true, idToProcess: action.id } break; default: return newState; break; } }
741f01086a8d2f6f6a241e123ea068acd9a2f632
[ "JavaScript" ]
9
JavaScript
thewalczi/elechart
a1cb800df1416fa78c0603624d91d4dec8244c00
38c46208e3c327fead1088bb975ce2941c498ae0
refs/heads/master
<repo_name>blader445/Quick-Bluetooth-commands-Windows-10<file_sep>/bts.py import mouse mouse.move(72,817, absolute=True, duration=0.1) mouse.click(button='left') mouse.move(156,819, absolute=True, duration=0.2) mouse.click(button='right') mouse.move(186,914, absolute=True, duration=0.1) mouse.click()<file_sep>/README.md # Quick-Bluetooth-commands-Windows-10 Speed up your workflow using Bluetooth on Windows with these 2 scripts. - Requirements : - Install Python /!\ (tested on 3.8.5) - This scripts use Python and a module called mouse. - Make sure to have both installed otherwise it will not work. - It should work on every full HD screen with windows 10 and the taskbar that don't hide automatically. - Quick start : 1. Start by using these two commands : - In Git Bash : $ git clone https://github.com/blader445/Quick-Bluetooth-commands-Windows-10.git - In Powershell or whatever therminal you use in your IDE : pip install mouse 2. Add the folder that has been created to your PATH in system variables. 3. Press Win + R and type "bts" to send a file via Bluetooth Or type "btr" to receive a file via Bluetooth 4. Enjoy 😉
64a8fa01aa93ca9e45e910297703d971fe22648d
[ "Markdown", "Python" ]
2
Python
blader445/Quick-Bluetooth-commands-Windows-10
1393b859a8accdf5ffb55c24ca6485ca00456647
839a1d49e958ebabd92f37b70b809b94be34979c
refs/heads/master
<file_sep>import React, { Component } from 'react' function NumbersList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}>{number}</li> ); return ( <div> <ul>{listItems}</ul> </div> ) } export class Numbers extends Component { render() { const itemsNumber = [1, 2, 3, 4, 5]; return ( <div> <NumbersList numbers={itemsNumber} /> </div> ) } } export default Numbers; <file_sep>import './App.css'; import { LoginControl, Page } from './components/Body'; import Forms from './components/Forms'; import Numbers from './components/Numbers.jsx'; import Reservation from './components/Reservation'; import * as Title from './components/Title'; function App() { // const name = '<NAME>'; const element = ( <div> <Page /> {/* <Title.Saludo name={name} /> */} <Title.Hora /> <Title.ButtonGreeting name='Pepe' /> <hr /> <LoginControl /> <hr /> <Numbers /> <hr></hr> <Forms /> <hr></hr> <Reservation /> </div> ); return element; } export default App; <file_sep>import React from "react"; function Saludo(props) { if (props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) return ( <div> <h1> Hello {props.name}</h1> <UserGreeting /> </div> ); else return <Greeting /> } else return <h1> Hello Stranger!</h1> } function UserGreeting(props) { return <h1>Wellcome Back!</h1>; } function Greeting(props) { return <h1>Please sign up.</h1>; } function FormattedDate(props) { return <h2>Son las {props.date.toLocaleTimeString()}</h2>; } class ButtonGreeting extends React.Component { constructor(props) { super(props); this.state = { show: false, name: props.name } } greeting() { this.setState({ show: !this.state.show }) } render() { return ( <div> <button onClick={() => this.greeting()}>Saludo</button> <div style={{ display: this.state.show ? 'block' : 'none' }}>Hola {this.props.name}</div> </div> ); } } class Hora extends React.Component { constructor(props) { super(props); this.state = { date: new Date() }; } tick() { this.setState({ date: new Date() }) } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } render() { return ( <div> <FormattedDate date={this.state.date} /> </div> ); } } export { Saludo, Hora, ButtonGreeting };
e2599ef9d100a8e280fdfd6e7094b1bb9d5674ac
[ "JavaScript" ]
3
JavaScript
jfcaballerop/react-oficial-doc
a00748d7ffd57a311341e121854e35c246611f79
7b88a85711fc5efbdd3b4e67519235554274bef9
refs/heads/main
<repo_name>JE-FH/solitaireSortJS<file_sep>/solitaireSort.js /* Hearts: 1, Diamonds: 2, Clubs: 3, Spades: 4 TODO: Make: isAce shifter lowerChecker finish checker redBlackChecker */ function solitaireSort(deck){ let first = 0, second = 2, third = 5, fourth = 9, fith = 14, sixth = 20, seventh = 27; let Hearts = 0, Diamonds = 0, Clubs = 0, Spades = 0; }
445f0ec2660cc3b0a7d85359322d4c43b2dd9a89
[ "JavaScript" ]
1
JavaScript
JE-FH/solitaireSortJS
37f4150edba4d3f7f590ae9588f4677538662a2a
6be29ed5509b670dedfca4621d6d3c58de8fdcec