mfTraining.cpp 33.5 KB
Newer Older
T
tmbdev 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/******************************************************************************
**	Filename:	mfTraining.c
**	Purpose:	Separates training pages into files for each character.
**				Strips from files only the features and there parameters of
				the feature type mf.
**	Author:		Dan Johnson
**	Revisment:	Christy Russon
**	Environment: HPUX 6.5
**	Library:     HPUX 6.5
**	History:     Fri Aug 18 08:53:50 1989, DSJ, Created.
**		     5/25/90, DSJ, Adapted to multiple feature types.
**				Tuesday, May 17, 1998 Changes made to make feature specific and
**				simplify structures. First step in simplifying training process.
**
 **	(c) Copyright Hewlett-Packard Company, 1988.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
******************************************************************************/
/**----------------------------------------------------------------------------
					Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "oldlist.h"
#include "efio.h"
#include "emalloc.h"
#include "featdefs.h"
33
#include "tessopt.h"
T
tmbdev 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46
#include "ocrfeatures.h"
#include "general.h"
#include "clusttool.h"
#include "cluster.h"
#include "protos.h"
#include "minmax.h"
#include "debug.h"
#include "const.h"
#include "mergenf.h"
#include "name2char.h"
#include "intproto.h"
#include "variables.h"
#include "freelist.h"
47 48 49
#include "efio.h"
#include "danerror.h"
#include "globals.h"
T
tmbdev 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

#include <string.h>
#include <stdio.h>
#include <math.h>

#define MAXNAMESIZE	80
#define MAX_NUM_SAMPLES	10000
#define PROGRAM_FEATURE_TYPE "mf"
#define MINSD (1.0f / 128.0f)

int	row_number;						/* cjn: fixes link problem */

typedef struct
{
  char		*Label;
  LIST		List;
}
LABELEDLISTNODE, *LABELEDLIST;

typedef struct
{
	char* Label;
	int	NumMerged[MAX_NUM_PROTOS];
	CLASS_TYPE Class;
}MERGE_CLASS_NODE;
typedef MERGE_CLASS_NODE* MERGE_CLASS;

#define round(x,frag)(floor(x/frag+.5)*frag)

/**----------------------------------------------------------------------------
					Public Function Prototypes
----------------------------------------------------------------------------**/
int main (
     int	argc,
     char	**argv);

/**----------------------------------------------------------------------------
					Private Function Prototypes
----------------------------------------------------------------------------**/
void ParseArguments(
int	argc,
char	**argv);

char *GetNextFilename ();

LIST ReadTrainingSamples (
     FILE	*File);

LABELEDLIST FindList (
     LIST	List,
     char	*Label);

MERGE_CLASS FindClass (
     LIST	List,
     char	*Label);

LABELEDLIST NewLabeledList (
     char	*Label);

MERGE_CLASS NewLabeledClass (
     char	*Label);

void WriteTrainingSamples (
     char	*Directory,
     LIST	CharList);

void WriteClusteredTrainingSamples (
     char	*Directory,
     LIST	ProtoList,
	 CLUSTERER *Clusterer,
	 LABELEDLIST CharSample);
/**/
void WriteMergedTrainingSamples(
    char	*Directory,
	LIST ClassList);

void WriteMicrofeat(
    char	*Directory,
	LIST	ClassList);

void WriteProtos(
	FILE* File,
	MERGE_CLASS MergeClass);

void WriteConfigs(
	FILE* File,
	CLASS_TYPE Class);

void FreeTrainingSamples (
     LIST	CharList);

void FreeLabeledClassList (
     LIST	ClassList);

void FreeLabeledList (
     LABELEDLIST	LabeledList);

CLUSTERER *SetUpForClustering(
     LABELEDLIST	CharSample);
/*
PARAMDESC *ConvertToPARAMDESC(
	PARAM_DESC* Param_Desc,
	int N);
*/
LIST RemoveInsignificantProtos(
	LIST ProtoList,
	BOOL8 KeepSigProtos,
	BOOL8 KeepInsigProtos,
	int N);

void CleanUpUnusedData(
	LIST ProtoList);

void Normalize (
   float  *Values);

void SetUpForFloat2Int(
	LIST LabeledClassList);

169
void WritePFFMTable(INT_TEMPLATES Templates, const char* filename);
T
tmbdev 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

//--------------Global Data Definitions and Declarations--------------
static char FontName[MAXNAMESIZE];
// globals used for parsing command line arguments
static char	*Directory = NULL;
static int	MaxNumSamples = MAX_NUM_SAMPLES;
static int	Argc;
static char	**Argv;

// globals used to control what information is saved in the output file
static BOOL8		ShowAllSamples = FALSE;
static BOOL8		ShowSignificantProtos = TRUE;
static BOOL8		ShowInsignificantProtos = FALSE;

// global variable to hold configuration parameters to control clustering
// -M 0.40   -B 0.05   -I 1.0   -C 1e-6.
static CLUSTERCONFIG Config =
{ elliptical, 0.40, 0.05, 1.0, 1e-6 };

static FLOAT32 RoundingAccuracy = 0.0;

191 192 193
// The unicharset used during mftraining
static UNICHARSET unicharset_mftraining;

T
tmbdev 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/*----------------------------------------------------------------------------
						Public Code
-----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
int main (
     int	argc,
     char	**argv)

/*
**	Parameters:
**		argc	number of command line arguments
**		argv	array of command line arguments
**	Globals: none
**	Operation:
**		This program reads in a text file consisting of feature
**		samples from a training page in the following format:
**
**			FontName CharName NumberOfFeatureTypes(N)
**			   FeatureTypeName1 NumberOfFeatures(M)
**			      Feature1
**			      ...
**			      FeatureM
**			   FeatureTypeName2 NumberOfFeatures(M)
**			      Feature1
**			      ...
**			      FeatureM
**			   ...
**			   FeatureTypeNameN NumberOfFeatures(M)
**			      Feature1
**			      ...
**			      FeatureM
**			FontName CharName ...
**
**		The result of this program is a binary inttemp file used by
**		the OCR engine.
**	Return: none
**	Exceptions: none
**	History:	Fri Aug 18 08:56:17 1989, DSJ, Created.
**				Mon May 18 1998, Christy Russson, Revistion started.
*/

{
	char	*PageName;
	FILE	*TrainingPage;
	FILE	*OutFile;
	LIST	CharList;
	CLUSTERER	*Clusterer = NULL;
	LIST		ProtoList = NIL;
	LABELEDLIST CharSample;
	PROTOTYPE	*Prototype;
	LIST   	ClassList = NIL;
	int		Cid, Pid;
	PROTO		Proto;
	PROTO_STRUCT	DummyProto;
	BIT_VECTOR	Config2;
	MERGE_CLASS	MergeClass;
	INT_TEMPLATES	IntTemplates;
	LIST pCharList, pProtoList;
	char Filename[MAXNAMESIZE];

254 255 256 257 258
        // Clean the unichar set
        unicharset_mftraining.clear();
        // Space character needed to represent NIL classification
        unicharset_mftraining.unichar_insert(" ");

T
tmbdev 已提交
259 260 261 262 263
	ParseArguments (argc, argv);
	InitFastTrainerVars ();
	InitSubfeatureVars ();
	while ((PageName = GetNextFilename()) != NULL)
	{
264
		printf ("Reading %s ...\n", PageName);
T
tmbdev 已提交
265 266 267 268 269 270 271 272
		TrainingPage = Efopen (PageName, "r");
		CharList = ReadTrainingSamples (TrainingPage);
		fclose (TrainingPage);
		//WriteTrainingSamples (Directory, CharList);
		pCharList = CharList;
		iterate(pCharList)
		{
			//Cluster
273
			CharSample = (LABELEDLIST) first_node (pCharList);
274
// 			printf ("\nClustering %s ...", CharSample->Label);
T
tmbdev 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
			Clusterer = SetUpForClustering(CharSample);
			ProtoList = ClusterSamples(Clusterer, &Config);
			//WriteClusteredTrainingSamples (Directory, ProtoList, Clusterer, CharSample);
			CleanUpUnusedData(ProtoList);

			//Merge
			ProtoList = RemoveInsignificantProtos(ProtoList, ShowSignificantProtos,
				ShowInsignificantProtos, Clusterer->SampleSize);
			FreeClusterer(Clusterer);
			MergeClass = FindClass (ClassList, CharSample->Label);
			if (MergeClass == NULL)
			{
				MergeClass = NewLabeledClass (CharSample->Label);
				ClassList = push (ClassList, MergeClass);
			}
			Cid = AddConfigToClass(MergeClass->Class);
			pProtoList = ProtoList;
			iterate (pProtoList)
			{
294
				Prototype = (PROTOTYPE *) first_node (pProtoList);
T
tmbdev 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

				// see if proto can be approximated by existing proto
				Pid = FindClosestExistingProto (MergeClass->Class, MergeClass->NumMerged, Prototype);
				if (Pid == NO_PROTO)
				{
					Pid = AddProtoToClass (MergeClass->Class);
					Proto = ProtoIn (MergeClass->Class, Pid);
					MakeNewFromOld (Proto, Prototype);
					MergeClass->NumMerged[Pid] = 1;
				}
				else
				{
					MakeNewFromOld (&DummyProto, Prototype);
					ComputeMergedProto (ProtoIn (MergeClass->Class, Pid), &DummyProto,
						(FLOAT32) MergeClass->NumMerged[Pid], 1.0,
						ProtoIn (MergeClass->Class, Pid));
					MergeClass->NumMerged[Pid] ++;
				}
				Config2 = ConfigIn (MergeClass->Class, Cid);
				AddProtoToConfig (Pid, Config2);
			}
			FreeProtoList (&ProtoList);
		}
		FreeTrainingSamples (CharList);
	}
	//WriteMergedTrainingSamples(Directory,ClassList);
	WriteMicrofeat(Directory, ClassList);
	InitIntProtoVars ();
	InitPrototypes ();
	SetUpForFloat2Int(ClassList);
325
	IntTemplates = CreateIntTemplates(TrainingData, unicharset_mftraining);
T
tmbdev 已提交
326 327 328 329 330 331 332 333 334 335 336 337
	strcpy (Filename, "");
	if (Directory != NULL)
	{
		strcat (Filename, Directory);
		strcat (Filename, "/");
	}
	strcat (Filename, "inttemp");
#ifdef __UNIX__
	OutFile = Efopen (Filename, "w");
#else
	OutFile = Efopen (Filename, "wb");
#endif
338
	WriteIntTemplates(OutFile, IntTemplates, unicharset_mftraining);
T
tmbdev 已提交
339
	fclose (OutFile);
340 341 342 343 344 345 346 347 348 349
	strcpy (Filename, "");
	if (Directory != NULL)
	{
		strcat (Filename, Directory);
		strcat (Filename, "/");
	}
	strcat (Filename, "pffmtable");
        // Now create pffmtable.
        WritePFFMTable(IntTemplates, Filename);
	printf ("Done!\n"); /**/
T
tmbdev 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
	FreeLabeledClassList (ClassList);
  return 0;
}	/* main */


/**----------------------------------------------------------------------------
							Private Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
void ParseArguments(
int	argc,
char	**argv)

/*
**	Parameters:
**		argc	number of command line arguments to parse
**		argv	command line arguments
**	Globals:
**		ShowAllSamples		flag controlling samples display
**		ShowSignificantProtos	flag controlling proto display
**		ShowInsignificantProtos	flag controlling proto display
**		Config			current clustering parameters
372
**		tessoptarg, tessoptind		defined by tessopt sys call
T
tmbdev 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
**		Argc, Argv		global copies of argc and argv
**	Operation:
**		This routine parses the command line arguments that were
**		passed to the program.  The legal arguments are:
**			-d		"turn off display of samples"
**			-p		"turn off significant protos"
**			-n		"turn off insignificant proto"
**			-S [ spherical | elliptical | mixed | automatic ]
**			-M MinSamples	"min samples per prototype (%)"
**			-B MaxIllegal	"max illegal chars per cluster (%)"
**			-I Independence	"0 to 1"
**			-C Confidence	"1e-200 to 1.0"
**			-D Directory
**			-N MaxNumSamples
**			-R RoundingAccuracy
**	Return: none
**	Exceptions: Illegal options terminate the program.
**	History: 7/24/89, DSJ, Created.
*/

{
	int		Option;
	int		ParametersRead;
	BOOL8		Error;

	Error = FALSE;
	Argc = argc;
	Argv = argv;
401
	while (( Option = tessopt( argc, argv, "R:N:D:C:I:M:B:S:d:n:p" )) != EOF )
T
tmbdev 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414
	{
		switch ( Option )
		{
		case 'n':
			ShowInsignificantProtos = FALSE;
			break;
		case 'p':
			ShowSignificantProtos = FALSE;
			break;
		case 'd':
			ShowAllSamples = FALSE;
			break;
		case 'C':
415
			ParametersRead = sscanf( tessoptarg, "%lf", &(Config.Confidence) );
T
tmbdev 已提交
416 417 418 419 420
			if ( ParametersRead != 1 ) Error = TRUE;
			else if ( Config.Confidence > 1 ) Config.Confidence = 1;
			else if ( Config.Confidence < 0 ) Config.Confidence = 0;
			break;
		case 'I':
421
			ParametersRead = sscanf( tessoptarg, "%f", &(Config.Independence) );
T
tmbdev 已提交
422 423 424 425 426
			if ( ParametersRead != 1 ) Error = TRUE;
			else if ( Config.Independence > 1 ) Config.Independence = 1;
			else if ( Config.Independence < 0 ) Config.Independence = 0;
			break;
		case 'M':
427
			ParametersRead = sscanf( tessoptarg, "%f", &(Config.MinSamples) );
T
tmbdev 已提交
428 429 430 431 432
			if ( ParametersRead != 1 ) Error = TRUE;
			else if ( Config.MinSamples > 1 ) Config.MinSamples = 1;
			else if ( Config.MinSamples < 0 ) Config.MinSamples = 0;
			break;
		case 'B':
433
			ParametersRead = sscanf( tessoptarg, "%f", &(Config.MaxIllegal) );
T
tmbdev 已提交
434 435 436 437 438
			if ( ParametersRead != 1 ) Error = TRUE;
			else if ( Config.MaxIllegal > 1 ) Config.MaxIllegal = 1;
			else if ( Config.MaxIllegal < 0 ) Config.MaxIllegal = 0;
			break;
		case 'R':
439
			ParametersRead = sscanf( tessoptarg, "%f", &RoundingAccuracy );
T
tmbdev 已提交
440 441 442 443 444
			if ( ParametersRead != 1 ) Error = TRUE;
			else if ( RoundingAccuracy > 0.01 ) RoundingAccuracy = 0.01;
			else if ( RoundingAccuracy < 0.0 ) RoundingAccuracy = 0.0;
			break;
		case 'S':
445
			switch ( tessoptarg[0] )
T
tmbdev 已提交
446 447 448 449 450 451 452 453 454
			{
			case 's': Config.ProtoStyle = spherical; break;
			case 'e': Config.ProtoStyle = elliptical; break;
			case 'm': Config.ProtoStyle = mixed; break;
			case 'a': Config.ProtoStyle = automatic; break;
			default: Error = TRUE;
			}
			break;
			case 'D':
455
				Directory = tessoptarg;
T
tmbdev 已提交
456 457
				break;
			case 'N':
458
				if (sscanf (tessoptarg, "%d", &MaxNumSamples) != 1 ||
T
tmbdev 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
					MaxNumSamples <= 0)
					Error = TRUE;
				break;
			case '?':
				Error = TRUE;
				break;
		}
		if ( Error )
		{
			fprintf (stderr, "usage: %s [-D] [-P] [-N]\n", argv[0] );
			fprintf (stderr, "\t[-S ProtoStyle]\n");
			fprintf (stderr, "\t[-M MinSamples] [-B MaxBad] [-I Independence] [-C Confidence]\n" );
			fprintf (stderr, "\t[-d directory] [-n MaxNumSamples] [ TrainingPage ... ]\n");
			exit (2);
		}
	}
}	// ParseArguments

/*---------------------------------------------------------------------------*/
char *GetNextFilename ()
/*
**	Parameters: none
**	Globals:
482
**		tessoptind			defined by tessopt sys call
T
tmbdev 已提交
483 484 485 486 487 488 489 490 491 492 493 494
**		Argc, Argv		global copies of argc and argv
**	Operation:
**		This routine returns the next command line argument.  If
**		there are no remaining command line arguments, it returns
**		NULL.  This routine should only be called after all option
**		arguments have been parsed and removed with ParseArguments.
**	Return: Next command line argument or NULL.
**	Exceptions: none
**	History: Fri Aug 18 09:34:12 1989, DSJ, Created.
*/

{
495 496
	if (tessoptind < Argc)
		return (Argv [tessoptind++]);
T
tmbdev 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	else
		return (NULL);

}	/* GetNextFilename */

/*---------------------------------------------------------------------------*/
LIST ReadTrainingSamples (
     FILE	*File)

/*
**	Parameters:
**		File		open text file to read samples from
**	Globals: none
**	Operation:
**		This routine reads training samples from a file and
**		places them into a data structure which organizes the
**		samples by FontName and CharName.  It then returns this
**		data structure.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 13:11:39 1989, DSJ, Created.
**			 Tue May 17 1998 simplifications to structure, illiminated
**				font, and feature specification levels of structure.
*/

{
523 524 525
	char			unichar[UNICHAR_LEN + 1];
	LABELEDLIST             CharSample;
        FEATURE_SET             FeatureSamples;
T
tmbdev 已提交
526 527 528 529
	LIST			TrainingSamples = NIL;
	CHAR_DESC		CharDesc;
	int			Type, i;

530 531 532 533 534 535 536 537 538 539
	while (fscanf (File, "%s %s", FontName, unichar) == 2) {
          if (!unicharset_mftraining.contains_unichar(unichar)) {
            unicharset_mftraining.unichar_insert(unichar);
            if (unicharset_mftraining.size() > MAX_NUM_CLASSES) {
              cprintf("Error: Size of unicharset of mftraining is "
                      "greater than MAX_NUM_CLASSES\n");
              exit(1);
            }
          }
		CharSample = FindList (TrainingSamples, unichar);
T
tmbdev 已提交
540
		if (CharSample == NULL) {
541
			CharSample = NewLabeledList (unichar);
T
tmbdev 已提交
542 543 544 545 546
			TrainingSamples = push (TrainingSamples, CharSample);
		}
		CharDesc = ReadCharDescription (File);
		Type = ShortNameToFeatureType(PROGRAM_FEATURE_TYPE);
		FeatureSamples = FeaturesOfType(CharDesc, Type);
547 548 549 550 551
                for (int feature = 0; feature < FeatureSamples->NumFeatures; ++feature) {
                  FEATURE f = FeatureSamples->Features[feature];
                  for (int dim =0; dim < f->Type->NumParams; ++dim)
                    f->Params[dim] += UniformRandomNumber(-MINSD, MINSD);
                }
T
tmbdev 已提交
552 553
		CharSample->List = push (CharSample->List, FeatureSamples);
		for (i = 0; i < NumFeatureSetsIn (CharDesc); i++)
554 555
                  if (Type != i)
                    FreeFeatureSet (FeaturesOfType (CharDesc, i));
T
tmbdev 已提交
556
		free (CharDesc);
557
        }
T
tmbdev 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
	return (TrainingSamples);

}	/* ReadTrainingSamples */

/*---------------------------------------------------------------------------*/
LABELEDLIST FindList (
     LIST	List,
     char	*Label)

/*
**	Parameters:
**		List		list to search
**		Label		label to search for
**	Globals: none
**	Operation:
**		This routine searches thru a list of labeled lists to find
**		a list with the specified label.  If a matching labeled list
**		cannot be found, NULL is returned.
**	Return: Labeled list with the specified Label or NULL.
**	Exceptions: none
**	History: Fri Aug 18 15:57:41 1989, DSJ, Created.
*/

{
	LABELEDLIST	LabeledList;

	iterate (List)
    {
586
		LabeledList = (LABELEDLIST) first_node (List);
T
tmbdev 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
		if (strcmp (LabeledList->Label, Label) == 0)
			return (LabeledList);
    }
	return (NULL);

}	/* FindList */

/*----------------------------------------------------------------------------*/
MERGE_CLASS FindClass (
     LIST	List,
     char	*Label)
{
	MERGE_CLASS	MergeClass;

	iterate (List)
    {
603
		MergeClass = (MERGE_CLASS) first_node (List);
T
tmbdev 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
		if (strcmp (MergeClass->Label, Label) == 0)
			return (MergeClass);
    }
	return (NULL);

}	/* FindClass */

/*---------------------------------------------------------------------------*/
LABELEDLIST NewLabeledList (
     char	*Label)

/*
**	Parameters:
**		Label	label for new list
**	Globals: none
**	Operation:
**		This routine allocates a new, empty labeled list and gives
**		it the specified label.
**	Return: New, empty labeled list.
**	Exceptions: none
**	History: Fri Aug 18 16:08:46 1989, DSJ, Created.
*/

{
	LABELEDLIST	LabeledList;

	LabeledList = (LABELEDLIST) Emalloc (sizeof (LABELEDLISTNODE));
	LabeledList->Label = (char*)Emalloc (strlen (Label)+1);
	strcpy (LabeledList->Label, Label);
	LabeledList->List = NIL;
	return (LabeledList);

}	/* NewLabeledList */

/*---------------------------------------------------------------------------*/
MERGE_CLASS NewLabeledClass (
     char	*Label)
{
	MERGE_CLASS	MergeClass;

	MergeClass = (MERGE_CLASS) Emalloc (sizeof (MERGE_CLASS_NODE));
	MergeClass->Label = (char*)Emalloc (strlen (Label)+1);
	strcpy (MergeClass->Label, Label);
	MergeClass->Class = NewClass (MAX_NUM_PROTOS, MAX_NUM_CONFIGS);
	return (MergeClass);

}	/* NewLabeledClass */

/*---------------------------------------------------------------------------*/
void WriteTrainingSamples (
     char	*Directory,
     LIST	CharList)

/*
**	Parameters:
**		Directory	directory to place sample files into
**		FontList	list of fonts used in the training samples
**	Globals:
**		MaxNumSamples	max number of samples per class to write
**	Operation:
**		This routine writes the specified samples into files which
**		are organized according to the font name and character name
**		of the samples.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 16:17:06 1989, DSJ, Created.
*/

{
	LABELEDLIST	CharSample;
	FEATURE_SET	FeatureSet;
	LIST		FeatureList;
	FILE		*File;
	char		Filename[MAXNAMESIZE];
	int		NumSamples;

	iterate (CharList)		// iterate thru all of the fonts
	{
682
		CharSample = (LABELEDLIST) first_node (CharList);
T
tmbdev 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

		// construct the full pathname for the current samples file
		strcpy (Filename, "");
		if (Directory != NULL)
		{
			strcat (Filename, Directory);
			strcat (Filename, "/");
		}
		strcat (Filename, FontName);
		strcat (Filename, "/");
		strcat (Filename, CharSample->Label);
		strcat (Filename, ".");
		strcat (Filename, PROGRAM_FEATURE_TYPE);
		printf ("\nWriting %s ...", Filename);

		/* if file does not exist, create a new one with an appropriate
		header; otherwise append samples to the existing file */
		File = fopen (Filename, "r");
		if (File == NULL)
		{
			File = Efopen (Filename, "w");
			WriteOldParamDesc
				(File, DefinitionOf (ShortNameToFeatureType (PROGRAM_FEATURE_TYPE)));
		}
		else
		{
			fclose (File);
			File = Efopen (Filename, "a");
		}

		// append samples onto the file
		FeatureList = CharSample->List;
		NumSamples = 0;
		iterate (FeatureList)
		{
			if (NumSamples >= MaxNumSamples) break;

720
			FeatureSet = (FEATURE_SET) first_node (FeatureList);
T
tmbdev 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
			WriteFeatureSet (File, FeatureSet);
			NumSamples++;
		}
		fclose (File);
	}
}	/* WriteTrainingSamples */


/*----------------------------------------------------------------------------*/
void WriteClusteredTrainingSamples (
     char	*Directory,
     LIST	ProtoList,
	 CLUSTERER *Clusterer,
	 LABELEDLIST CharSample)

/*
**	Parameters:
**		Directory	directory to place sample files into
**	Globals:
**		MaxNumSamples	max number of samples per class to write
**	Operation:
**		This routine writes the specified samples into files which
**		are organized according to the font name and character name
**		of the samples.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 16:17:06 1989, DSJ, Created.
*/

{
	FILE		*File;
	char		Filename[MAXNAMESIZE];

	strcpy (Filename, "");
	if (Directory != NULL)
	{
		strcat (Filename, Directory);
		strcat (Filename, "/");
	}
	strcat (Filename, FontName);
	strcat (Filename, "/");
	strcat (Filename, CharSample->Label);
	strcat (Filename, ".");
	strcat (Filename, PROGRAM_FEATURE_TYPE);
	strcat (Filename, ".p");
	printf ("\nWriting %s ...", Filename);
	File = Efopen (Filename, "w");
	WriteProtoList(File, Clusterer->SampleSize, Clusterer->ParamDesc,
		ProtoList, ShowSignificantProtos, ShowInsignificantProtos);
	fclose (File);

}	/* WriteClusteredTrainingSamples */

/*---------------------------------------------------------------------------*/
void WriteMergedTrainingSamples(
    char	*Directory,
	LIST ClassList)

{
	FILE		*File;
	char		Filename[MAXNAMESIZE];
	MERGE_CLASS MergeClass;

	iterate (ClassList)
	{
786
		MergeClass = (MERGE_CLASS) first_node (ClassList);
T
tmbdev 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
		strcpy (Filename, "");
		if (Directory != NULL)
		{
			strcat (Filename, Directory);
			strcat (Filename, "/");
		}
		strcat (Filename, "Merged/");
		strcat (Filename, MergeClass->Label);
		strcat (Filename, PROTO_SUFFIX);
		printf ("\nWriting Merged %s ...", Filename);
		File = Efopen (Filename, "w");
		WriteOldProtoFile (File, MergeClass->Class);
		fclose (File);

		strcpy (Filename, "");
		if (Directory != NULL)
		{
			strcat (Filename, Directory);
			strcat (Filename, "/");
		}
		strcat (Filename, "Merged/");
		strcat (Filename, MergeClass->Label);
		strcat (Filename, CONFIG_SUFFIX);
		printf ("\nWriting Merged %s ...", Filename);
		File = Efopen (Filename, "w");
		WriteOldConfigFile (File, MergeClass->Class);
		fclose (File);
	}

}	// WriteMergedTrainingSamples

/*--------------------------------------------------------------------------*/
void WriteMicrofeat(
    char	*Directory,
	LIST	ClassList)

{
	FILE		*File;
	char		Filename[MAXNAMESIZE];
	MERGE_CLASS MergeClass;

	strcpy (Filename, "");
	if (Directory != NULL)
	{
		strcat (Filename, Directory);
		strcat (Filename, "/");
	}
	strcat (Filename, "Microfeat");
	File = Efopen (Filename, "w");
	printf ("\nWriting Merged %s ...", Filename);
	iterate(ClassList)
	{
839
		MergeClass = (MERGE_CLASS) first_node (ClassList);
T
tmbdev 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
		WriteProtos(File, MergeClass);
		WriteConfigs(File, MergeClass->Class);
	}
	fclose (File);
} // WriteMicrofeat

/*---------------------------------------------------------------------------*/
void WriteProtos(
	FILE* File,
	MERGE_CLASS MergeClass)
{
	float Values[3];
	int i;
	PROTO Proto;

855
	fprintf(File, "%s\n", MergeClass->Label);
T
tmbdev 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
	fprintf(File, "%d\n", NumProtosIn(MergeClass->Class));
	for(i=0; i < NumProtosIn(MergeClass->Class); i++)
	{
		Proto = ProtoIn(MergeClass->Class,i);
		fprintf(File, "\t%8.4f %8.4f %8.4f %8.4f ", ProtoX(Proto), ProtoY(Proto),
			ProtoLength(Proto), ProtoAngle(Proto));
		Values[0] = ProtoX(Proto);
		Values[1] = ProtoY(Proto);
		Values[2] = ProtoAngle(Proto);
		Normalize(Values);
		fprintf(File, "%8.4f %8.4f %8.4f\n", Values[0], Values[1], Values[2]);
	}
} // WriteProtos

/*----------------------------------------------------------------------------*/
void WriteConfigs(
	FILE* File,
	CLASS_TYPE Class)
{
	BIT_VECTOR Config;
	int i, j, WordsPerConfig;

	WordsPerConfig = WordsInVectorOfSize(NumProtosIn(Class));
	fprintf(File, "%d %d\n", NumConfigsIn(Class),WordsPerConfig);
	for(i=0; i < NumConfigsIn(Class); i++)
	{
		Config = ConfigIn(Class,i);
		for(j=0; j < WordsPerConfig; j++)
			fprintf(File, "%08x ", Config[j]);
		fprintf(File, "\n");
	}
	fprintf(File, "\n");
} // WriteConfigs

/*---------------------------------------------------------------------------*/
void FreeTrainingSamples (
     LIST	CharList)

/*
**	Parameters:
**		FontList	list of all fonts in document
**	Globals: none
**	Operation:
**		This routine deallocates all of the space allocated to
**		the specified list of training samples.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 17:44:27 1989, DSJ, Created.
*/

{
	LABELEDLIST	CharSample;
	FEATURE_SET	FeatureSet;
	LIST		FeatureList;


912
// 	printf ("FreeTrainingSamples...\n");
T
tmbdev 已提交
913 914
	iterate (CharList) 		/* iterate thru all of the fonts */
	{
915
		CharSample = (LABELEDLIST) first_node (CharList);
T
tmbdev 已提交
916 917 918
		FeatureList = CharSample->List;
		iterate (FeatureList)	/* iterate thru all of the classes */
		{
919
			FeatureSet = (FEATURE_SET) first_node (FeatureList);
T
tmbdev 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
			FreeFeatureSet (FeatureSet);
		}
		FreeLabeledList (CharSample);
	}
	destroy (CharList);

}	/* FreeTrainingSamples */

/*-----------------------------------------------------------------------------*/
void FreeLabeledClassList (
     LIST	ClassList)

/*
**	Parameters:
**		FontList	list of all fonts in document
**	Globals: none
**	Operation:
**		This routine deallocates all of the space allocated to
**		the specified list of training samples.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 17:44:27 1989, DSJ, Created.
*/

{
	MERGE_CLASS	MergeClass;

	iterate (ClassList) 		/* iterate thru all of the fonts */
	{
949
		MergeClass = (MERGE_CLASS) first_node (ClassList);
T
tmbdev 已提交
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
		free (MergeClass->Label);
		FreeClass(MergeClass->Class);
		free (MergeClass);
	}
	destroy (ClassList);

}	/* FreeLabeledClassList */

/*---------------------------------------------------------------------------*/
void FreeLabeledList (
     LABELEDLIST	LabeledList)

/*
**	Parameters:
**		LabeledList	labeled list to be freed
**	Globals: none
**	Operation:
**		This routine deallocates all of the memory consumed by
**		a labeled list.  It does not free any memory which may be
**		consumed by the items in the list.
**	Return: none
**	Exceptions: none
**	History: Fri Aug 18 17:52:45 1989, DSJ, Created.
*/

{
	destroy (LabeledList->List);
	free (LabeledList->Label);
	free (LabeledList);

}	/* FreeLabeledList */

/*---------------------------------------------------------------------------*/
CLUSTERER *SetUpForClustering(
     LABELEDLIST	CharSample)

/*
**	Parameters:
**		CharSample: LABELEDLIST that holds all the feature information for a
**		given character.
**	Globals:
**		None
**	Operation:
**		This routine reads samples from a LABELEDLIST and enters
**		those samples into a clusterer data structure.  This
**		data structure is then returned to the caller.
**	Return:
**		Pointer to new clusterer data structure.
**	Exceptions:
**		None
**	History:
**		8/16/89, DSJ, Created.
*/

{
	UINT16	N;
	int		i, j;
	FLOAT32	*Sample = NULL;
	CLUSTERER	*Clusterer;
	INT32		CharID;
	LIST FeatureList = NULL;
	FEATURE_SET FeatureSet = NULL;
	FEATURE_DESC FeatureDesc = NULL;
//	PARAM_DESC* ParamDesc;

	FeatureDesc = DefinitionOf(ShortNameToFeatureType(PROGRAM_FEATURE_TYPE));
	N = FeatureDesc->NumParams;
//	ParamDesc = ConvertToPARAMDESC(FeatureDesc->ParamDesc, N);
	Clusterer = MakeClusterer(N,FeatureDesc->ParamDesc);
//	free(ParamDesc);

	FeatureList = CharSample->List;
	CharID = 0;
	iterate(FeatureList)
	{
		if (CharID >= MaxNumSamples) break;

1027
		FeatureSet = (FEATURE_SET) first_node (FeatureList);
T
tmbdev 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
		for (i=0; i < FeatureSet->MaxNumFeatures; i++)
		{
			if (Sample == NULL)
				Sample = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
			for (j=0; j < N; j++)
				if (RoundingAccuracy != 0.0)
					Sample[j] = round(FeatureSet->Features[i]->Params[j], RoundingAccuracy);
				else
					Sample[j] = FeatureSet->Features[i]->Params[j];
				MakeSample (Clusterer, Sample, CharID);
		}
		CharID++;
	}
	if ( Sample != NULL ) free( Sample );
	return( Clusterer );

}	/* SetUpForClustering */

/*------------------------------------------------------------------------*/
LIST RemoveInsignificantProtos(
	LIST ProtoList,
	BOOL8 KeepSigProtos,
	BOOL8 KeepInsigProtos,
	int N)

{
	LIST NewProtoList = NIL;
	LIST pProtoList;
	PROTOTYPE* Proto;
	PROTOTYPE* NewProto;
	int i;

	pProtoList = ProtoList;
	iterate(pProtoList)
	{
1063
		Proto = (PROTOTYPE *) first_node (pProtoList);
T
tmbdev 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
		if ((Proto->Significant && KeepSigProtos) ||
			(!Proto->Significant && KeepInsigProtos))
		{
			NewProto = (PROTOTYPE *)Emalloc(sizeof(PROTOTYPE));

			NewProto->Mean = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
			NewProto->Significant = Proto->Significant;
			NewProto->Style = Proto->Style;
			NewProto->NumSamples = Proto->NumSamples;
			NewProto->Cluster = NULL;
			NewProto->Distrib = NULL;

			for (i=0; i < N; i++)
				NewProto->Mean[i] = Proto->Mean[i];
			if (Proto->Variance.Elliptical != NULL)
			{
				NewProto->Variance.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
				for (i=0; i < N; i++)
					NewProto->Variance.Elliptical[i] = Proto->Variance.Elliptical[i];
			}
			else
				NewProto->Variance.Elliptical = NULL;
			//---------------------------------------------
			if (Proto->Magnitude.Elliptical != NULL)
			{
				NewProto->Magnitude.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
				for (i=0; i < N; i++)
					NewProto->Magnitude.Elliptical[i] = Proto->Magnitude.Elliptical[i];
			}
			else
				NewProto->Magnitude.Elliptical = NULL;
			//------------------------------------------------
			if (Proto->Weight.Elliptical != NULL)
			{
				NewProto->Weight.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
				for (i=0; i < N; i++)
					NewProto->Weight.Elliptical[i] = Proto->Weight.Elliptical[i];
			}
			else
				NewProto->Weight.Elliptical = NULL;

			NewProto->TotalMagnitude = Proto->TotalMagnitude;
			NewProto->LogMagnitude = Proto->LogMagnitude;
			NewProtoList = push_last(NewProtoList, NewProto);
		}
	}
	//FreeProtoList (ProtoList);
	return (NewProtoList);
}	/* RemoveInsignificantProtos */
/*-----------------------------------------------------------------------------*/
void CleanUpUnusedData(
	LIST ProtoList)
{
	PROTOTYPE* Prototype;

	iterate(ProtoList)
	{
1121
		Prototype = (PROTOTYPE *) first_node (ProtoList);
T
tmbdev 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
		if(Prototype->Variance.Elliptical != NULL)
		{
			memfree(Prototype->Variance.Elliptical);
			Prototype->Variance.Elliptical = NULL;
		}
		if(Prototype->Magnitude.Elliptical != NULL)
		{
			memfree(Prototype->Magnitude.Elliptical);
			Prototype->Magnitude.Elliptical = NULL;
		}
		if(Prototype->Weight.Elliptical != NULL)
		{
			memfree(Prototype->Weight.Elliptical);
			Prototype->Weight.Elliptical = NULL;
		}
	}
}

/*--------------------------------------------------------------------------*/
void Normalize (
   float  *Values)
{
	register float Slope;
	register float Intercept;
	register float Normalizer;

	Slope      = tan (Values [2] * 2 * PI);
	Intercept  = Values [1] - Slope * Values [0];
	Normalizer = 1 / sqrt (Slope * Slope + 1.0);

	Values [0] = Slope * Normalizer;
	Values [1] = - Normalizer;
	Values [2] = Intercept * Normalizer;
} // Normalize

/** SetUpForFloat2Int **************************************************/
void SetUpForFloat2Int(
	LIST LabeledClassList)
{
	MERGE_CLASS	MergeClass;
	CLASS_TYPE		Class;
	int				NumProtos;
	int				NumConfigs;
	int				NumWords;
	int				i, j;
	float			Values[3];
	PROTO			NewProto;
	PROTO			OldProto;
	BIT_VECTOR		NewConfig;
	BIT_VECTOR		OldConfig;

1173
// 	printf("Float2Int ...\n");
T
tmbdev 已提交
1174 1175 1176

	iterate(LabeledClassList)
	{
1177
		MergeClass = (MERGE_CLASS) first_node (LabeledClassList);
1178 1179
		Class = &TrainingData[unicharset_mftraining.unichar_to_id(
                                          MergeClass->Label)];
T
tmbdev 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		NumProtos = NumProtosIn(MergeClass->Class);
		NumConfigs = NumConfigsIn(MergeClass->Class);

		NumProtosIn(Class) = NumProtos;
		Class->MaxNumProtos = NumProtos;
		Class->Prototypes = (PROTO) Emalloc (sizeof(PROTO_STRUCT) * NumProtos);
		for(i=0; i < NumProtos; i++)
		{
			NewProto = ProtoIn(Class, i);
			OldProto = ProtoIn(MergeClass->Class, i);
			Values[0] = ProtoX(OldProto);
			Values[1] = ProtoY(OldProto);
			Values[2] = ProtoAngle(OldProto);
			Normalize(Values);
			ProtoX(NewProto) = ProtoX(OldProto);
			ProtoY(NewProto) = ProtoY(OldProto);
			ProtoLength(NewProto) = ProtoLength(OldProto);
			ProtoAngle(NewProto) = ProtoAngle(OldProto);
			CoefficientA(NewProto) = Values[0];
			CoefficientB(NewProto) = Values[1];
			CoefficientC(NewProto) = Values[2];
		}

		NumConfigsIn(Class) = NumConfigs;
		Class->MaxNumConfigs = NumConfigs;
		Class->Configurations = (BIT_VECTOR*) Emalloc (sizeof(BIT_VECTOR) * NumConfigs);
		NumWords = WordsInVectorOfSize(NumProtos);
		for(i=0; i < NumConfigs; i++)
		{
			NewConfig = NewBitVector(NumProtos);
			OldConfig = ConfigIn(MergeClass->Class, i);
			for(j=0; j < NumWords; j++)
				NewConfig[j] = OldConfig[j];
			ConfigIn(Class, i) = NewConfig;
		}
	}
} // SetUpForFloat2Int
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

/*--------------------------------------------------------------------------*/
void WritePFFMTable(INT_TEMPLATES Templates, const char* filename) {
  FILE* fp = Efopen(filename, "wb");
  /* then write out each class */
  for (int i = 0; i < NumClassesIn (Templates); i++) {
    int MaxLength = 0;
    INT_CLASS Class = ClassForIndex (Templates, i);
    for (int ConfigId = 0; ConfigId < NumIntConfigsIn (Class); ConfigId++) {
      if (LengthForConfigId (Class, ConfigId) > MaxLength)
        MaxLength = LengthForConfigId (Class, ConfigId);
    }
    fprintf(fp, "%s %d\n", unicharset_mftraining.id_to_unichar(
                ClassIdForIndex(Templates, i)), MaxLength);
  }
  fclose(fp);
} // WritePFFMTable