The class performs token processing in strings
Inheritance: IEnumerator
Exemplo n.º 1
0
		/// <summary> Extracts selected fields from a message.  
		/// 
		/// </summary>
		/// <param name="theMessageText">an unparsed message from which to get fields 
		/// </param>
		/// <param name="thePathSpecs">Terser-like paths to fields in the message.  See documentation
		/// for Terser.  These paths are identical except that they start with the segment
		/// name (search flags and group names are to be omitted as they are not relevant 
		/// with unparsed ER7 messages).  
		/// </param>
		/// <returns> field values corresponding to the given paths
		/// </returns>
		/// <throws>  HL7Exception </throws>
		public static System.String[] getFields(System.String theMessageText, System.String[] thePathSpecs)
		{
			NuGenDatumPath[] paths = new NuGenDatumPath[thePathSpecs.Length];
			for (int i = 0; i < thePathSpecs.Length; i++)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePathSpecs[i], "-", false);
				System.String segSpec = tok.NextToken();
				tok = new SupportClass.Tokenizer(segSpec, "()", false);
				System.String segName = tok.NextToken();
				if (segName.Length != 3)
				{
					throw new NuGenHL7Exception("In field path, " + segName + " is not a valid segment name");
				}
				int segRep = 0;
				if (tok.HasMoreTokens())
				{
					System.String rep = tok.NextToken();
					try
					{
						segRep = System.Int32.Parse(rep);
					}
					catch (System.FormatException e)
					{
						throw new NuGenHL7Exception("In field path, segment rep" + rep + " is not valid", e);
					}
				}
				
				int[] indices = Terser.getIndices(thePathSpecs[i]);
				paths[i] = new NuGenDatumPath();
				paths[i].add(segName).add(segRep);
				paths[i].add(indices[0]).add(indices[1]).add(indices[2]).add(indices[3]);
			}
			return getFields(theMessageText, paths);
		}
		/// <summary> Reads given "property file" and sets system properties accordingly.  In the property file,
		/// there should be one property per line.  A line should consist of 1) the fully qualified property name,
		/// 2) one or more tabs, and 3) the value (everything after the first group of tabs and before any subsequent
		/// groups will be considered "the value").
		/// Lines in the file are consdidered comments if they begin with "%".
		/// </summary>
		public static void  loadProperties(System.String propertyFileName)
		{
			
			//open stream from given property file
			System.IO.StreamReader in_Renamed = null;
			in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).CurrentEncoding);
			
			System.String line, key, value_Renamed, delim = "\t";
			SupportClass.Tokenizer tok;
			while ((line = in_Renamed.ReadLine()) != null)
			{
				//ignore comments
				if (!line.StartsWith("%"))
				{
					key = null; value_Renamed = null;
					
					//get property key and value
					tok = new SupportClass.Tokenizer(line, delim, false);
					if (tok.HasMoreTokens())
						key = tok.NextToken();
					if (tok.HasMoreTokens())
						value_Renamed = tok.NextToken();
				}
			}
			in_Renamed.Close();
		}
Exemplo n.º 3
0
		} //end method
		
		/// <summary> Checks a code for an exact match, and using certain sequences where some 
		/// characters are wildcards (e.g. HL7nnnn).  If the pattern contains one of 
		/// " or ", " OR ", or "," each operand is checked.
		/// </summary>
		private bool checkCode(System.String code, System.String pattern)
		{
			bool match = false;
			//mod by Neal acharya - Do full match on with the pattern.  If code matches pattern then return true
			//else parse pattern to look for wildcard characters
			if (code.Equals(pattern))
			{
				match = true;
			}
			//end if 
			else
			{
				if (pattern.IndexOf(' ') >= 0 || pattern.IndexOf(',') >= 0)
				{
					SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pattern, ", ", false);
					while (tok.HasMoreTokens() && !match)
					{
						System.String t = tok.NextToken();
						if (!t.ToUpper().Equals("or".ToUpper()))
							match = checkCode(code, t);
					} //end while
				}
				//end if
				else
				{
					if (code.Equals(pattern))
					{
						match = true;
					}
				} //end else
			} //end else 
			return match;
		} //end method
		/// <summary> <p>A convenience method for binding applications to an <code>ApplicationRouter</code>
		/// Information about bindings is read from a file at a specified URL.  Each line in the 
		/// file should have the following format (entries TAB delimited):</p>
		/// 
		/// <p>message_type &#009; trigger_event &#009; processing_id &#009; version_id &#009; app_class</p>
		/// 
		/// <p>Note that the first four fields can be the wildcard "*", which means any.</p>
		/// 
		/// <p>For example, if you write an Application called org.yourorganiztion.ADTProcessor
		/// that processes several types of ADT messages, and another called 
		/// org.yourorganization.ResultProcessor that processes result messages, you might have a 
		/// file that looks like this: </p>
		/// 
		/// <p>ADT &#009; * &#009; * &#009; * &#009; org.yourorganization.ADTProcessor<br>
		/// ORU &#009; R01 &#009; * &#009; * &#009; org.yourorganization.ResultProcessor</p>
		/// 
		/// <p>Each class listed in this file must implement either Genetibase.NuGenHL7.app.Application or 
		/// Genetibase.NuGenHL7.protocol.ReceivingApplication, and must have a zero-argument constructor.</p>
		/// 
		/// </summary>
		/// <param name="theRouter">the <code>ApplicationRouter</code> on which to make the binding
		/// </param>
		/// <param name="theSource">a URL pointing to the bindings file 
		/// </param>
		public static void  loadApplications(NuGenApplicationRouter theRouter, System.Uri theSource)
		{
			
			if (theSource == null)
			{
				throw new NuGenHL7Exception("Can't load application bindings: the given URL is null");
			}
			
			System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).CurrentEncoding);
			System.String line = null;
			while ((line = in_Renamed.ReadLine()) != null)
			{
				//parse application registration information 
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(line, "\t", false);
				System.String type = null, event_Renamed = null, procId = null, verId = null, className = null;
				
				if (tok.HasMoreTokens())
				{
					//skip blank lines 
					try
					{
						type = tok.NextToken();
						event_Renamed = tok.NextToken();
						procId = tok.NextToken();
						verId = tok.NextToken();
						className = tok.NextToken();
					}
					catch (System.ArgumentOutOfRangeException)
					{
						throw new NuGenHL7Exception("Can't register applications from " + theSource.ToString() + ". The line '" + line + "' is not of the form: message_type [tab] trigger_event " + "[tab] processing ID [tab] version ID [tab] application_class. " + "*** NOTE TWO NEW FIELDS AS OF HAPI 0.5 ****. ", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
					}
					
					System.Type appClass = System.Type.GetType(className); //may throw ClassNotFoundException 
					System.Object appObject = System.Activator.CreateInstance(appClass);
					NuGenReceivingApplication app = null;
					if (appObject is NuGenReceivingApplication)
					{
						app = (NuGenReceivingApplication) appObject;
					}
					else if (appObject is Application)
					{
						app = new NuGenAppWrapper((Application) appObject);
					}
					else
					{
						throw new NuGenHL7Exception("The specified class, " + appClass.FullName + ", doesn't implement Application or ReceivingApplication.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
					}
					
					Genetibase.NuGenHL7.protocol.AppRoutingData rd = new NuGenAppRoutingDataImpl(type, event_Renamed, procId, verId);
					theRouter.bindApplication(rd, app);
				}
			}
		}
Exemplo n.º 5
0
		public FileExtFilter(System.String descroot, System.String suffixes)
		{
			//UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'"
			exts = new List<String>();
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(suffixes, ";");
			while (tok.HasMoreTokens())
				exts.Add(tok.NextToken());
			
			descr = descroot + " (";
			for (int n = 0; n < exts.Count; n++)
				descr = descr + (n > 0?" ":"") + "*" + exts[n];
			descr = descr + ")";
		}
Exemplo n.º 6
0
	/// <summary>
	/// Load a properties file from the templatePath defined in the
	/// generator. As the templatePath can contains multiple paths,
	/// it will cycle through them to find the file. The first file
	/// that can be successfully loaded is considered. (kind of
	/// like the java classpath), it is done to clone the Velocity
	/// process of loading templates.
	/// </summary>
	/// <param name="propertiesFile">the properties file to load. It must be
	/// a relative pathname.
	/// </param>
	/// <returns>a properties instance loaded with the properties from
	/// the file. If no file can be found it returns an empty instance.
	/// </returns>
	protected internal virtual ExtendedProperties loadFromTemplatePath(System.String propertiesFile) {
	    ExtendedProperties properties = new ExtendedProperties();
	    System.String templatePath = Generator.Instance.TemplatePath;

	    // We might have something like the following:
	    //
	    // #set ($dbprops = $properties.load("$generator.templatePath/path/props")
	    //
	    // as we have in Torque but we want people to start using
	    //
	    // #set ($dbprops = $properties.load("path/props")
	    //
	    // so that everything works from the filesystem or from
	    // a JAR. So the actual Generator.getTemplatePath()
	    // is not deprecated but it's use in templates
	    // should be.
	    SupportClass.Tokenizer st = new SupportClass.Tokenizer(templatePath, ",");
	    while (st.HasMoreTokens()) {
		System.String templateDir = st.NextToken();
		try {
		    // If the properties file is being pulled from the
		    // file system and someone is using the method whereby
		    // the properties file is assumed to be in the template
		    // path and they are simply using:
		    //
		    // #set ($dbprops = $properties.load("props") (1)
		    //
		    // than we have to tack on the templatePath in order
		    // for the properties file to be found. We want (1)
		    // to work whether the generation is being run from
		    // the file system or from a JAR file.
		    System.String fullPath = propertiesFile;

		    // FIXME probably not that clever since there could be
		    // a mix of file separators and the test will fail :-(
		    if (!fullPath.StartsWith(templateDir)) {
			fullPath = templateDir + "\\" + propertiesFile;
		    }

		    properties.Load(new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
		    // first pick wins, we don't need to go further since
		    // we found a valid file.
		    break;
		} catch (System.Exception) {
		    // do nothing
		}
	    }
	    return properties;
	}
		/// <param name="theScope">must be in the form type^event (ie message type and trigger event separated
		/// by a carat)
		/// </param>
		public override bool appliesToScope(System.String theScope)
		{			
			if (!Regex.IsMatch(theScope, ".*\\^.*"))
			{
				throw new System.ArgumentException("arg theScope must be of the form type^event");
			}
			
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(theScope, delim, false);
			System.String itemType = tok.NextToken();
			System.String itemEvent = tok.NextToken();

            throw new Exception("This method is invalid");
			
			//return applies;
		}
Exemplo n.º 8
0
		/// <summary> Encodes the given message and compares it to the given string.  Any differences
		/// are noted in the file [hapi.home]/parse_check.txt.  Ignores extra field delimiters.
		/// </summary>
		public static void  checkParse(System.String originalMessageText, Message parsedMessage, Parser parser)
		{
			System.String newMessageText = parser.encode(parsedMessage);
			
			
			if (!originalMessageText.Equals(newMessageText))
			{
				//check each segment
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(originalMessageText, "\r");
				System.Collections.ArrayList one = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						one.Add(seg);
				}
				tok = new SupportClass.Tokenizer(newMessageText, "\r");
				System.Collections.ArrayList two = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						two.Add(stripExtraDelimiters(seg, seg[3]));
				}
				
				if (one.Count != two.Count)
				{
				}
				else
				{
					//check each segment
					for (int i = 0; i < one.Count; i++)
					{
						System.String origSeg = (System.String) one[i];
						System.String newSeg = (System.String) two[i];
						if (!origSeg.Equals(newSeg))
						{
						}
					}
				}
			}
			else
			{
			}
			
		}
Exemplo n.º 9
0
        /// <summary> Splits the given composite string into an array of components using the given
        /// delimiter.
        /// </summary>
        public static String[] Split(String composite, String delim)
        {
            ArrayList components = new ArrayList();

            //defend against evil nulls
            if (composite == null)
            {
                composite = "";
            }
            if (delim == null)
            {
                delim = "";
            }

            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(composite, delim, true);
            bool previousTokenWasDelim = true;

            while (tok.HasMoreTokens())
            {
                String thisTok = tok.NextToken();
                if (thisTok.Equals(delim))
                {
                    if (previousTokenWasDelim)
                    {
                        components.Add(null);
                    }
                    previousTokenWasDelim = true;
                }
                else
                {
                    components.Add(thisTok);
                    previousTokenWasDelim = false;
                }
            }

            String[] ret = new String[components.Count];
            for (int i = 0; i < components.Count; i++)
            {
                ret[i] = ((String)components[i]);
            }

            return(ret);
        }
Exemplo n.º 10
0
        private System.String[] getMSHFields(SupportClass.Tokenizer tok, char fieldSep)
        {
            System.String[] result = new System.String[21];
            result[0] = System.Convert.ToString(fieldSep);
            System.String token = null;
            int           field = 1;

            while (tok.HasMoreTokens() && (token = tok.NextToken())[0] != ourSegmentSeparator)
            {
                if (token[0] == fieldSep)
                {
                    field++;
                }
                else
                {
                    result[field] = token;
                }
            }
            return(result);
        }
Exemplo n.º 11
0
        /// <summary>Gets path information from a path spec. </summary>
        private PathSpec ParsePathSpec(string spec)
        {
            var ps = new PathSpec(this);

            if (spec.StartsWith("."))
            {
                ps.Find = true;
                spec    = spec.Substring(1);
            }
            else
            {
                ps.Find = false;
            }

            if (spec.Length == 0)
            {
                throw new HL7Exception("Invalid path (some path element is either empty or contains only a dot)");
            }

            var tok = new SupportClass.Tokenizer(spec, "()", false);

            ps.Pattern = tok.NextToken();
            if (tok.HasMoreTokens())
            {
                var repString = tok.NextToken();
                try
                {
                    ps.Rep = int.Parse(repString);
                }
                catch (FormatException)
                {
                    throw new HL7Exception(repString + " is not a valid rep #", ErrorCode.APPLICATION_INTERNAL_ERROR);
                }
            }
            else
            {
                ps.Rep = 0;
            }

            return(ps);
        }
Exemplo n.º 12
0
        /// <summary> Given a Terser path, returns an array containing field num, field rep,
        /// component, and subcomponent.
        /// </summary>
        public static int[] getIndices(String spec)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            tok.NextToken();             //skip over segment
            if (!tok.HasMoreTokens())
            {
                throw new HL7Exception("Must specify field in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            int[] ret = null;
            try
            {
                SupportClass.Tokenizer fieldSpec = new SupportClass.Tokenizer(tok.NextToken(), "()", false);
                int fieldNum = Int32.Parse(fieldSpec.NextToken());
                int fieldRep = 0;
                if (fieldSpec.HasMoreTokens())
                {
                    fieldRep = Int32.Parse(fieldSpec.NextToken());
                }

                int component = 1;
                if (tok.HasMoreTokens())
                {
                    component = Int32.Parse(tok.NextToken());
                }

                int subcomponent = 1;
                if (tok.HasMoreTokens())
                {
                    subcomponent = Int32.Parse(tok.NextToken());
                }
                int[] result = new int[] { fieldNum, fieldRep, component, subcomponent };
                ret = result;
            }
            catch (FormatException)
            {
                throw new HL7Exception("Invalid integer in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            return(ret);
        }
Exemplo n.º 13
0
        /// <seealso cref="Genetibase.NuGenHL7.parser.Parser.doParse(java.lang.String, java.lang.String)">
        /// </seealso>
        protected internal override Message doParse(System.String message, System.String version)
        {
            Message result = null;

            char fieldSep = message[3];
            NuGenEncodingCharacters ec = new NuGenEncodingCharacters(fieldSep, message.Substring(4, (8) - (4)));

            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(message.Substring(4), System.Convert.ToString(new char[] { fieldSep, ourSegmentSeparator }), true);

            System.String[] mshFields = getMSHFields(tok, fieldSep);
            System.Object[] structure = getStructure(mshFields[8], ec.ComponentSeparator);

            StructRef root = (StructRef)myEventGuideMap[structure[0]];

            if (root == null)
            {
                result = myPipeParser.parse(message);
            }
            else
            {
                int csIndex = mshFields[11].IndexOf((System.Char)ec.ComponentSeparator);
                result = instantiateMessage((System.String)structure[1], version, ((System.Boolean)structure[2]));

                StructRef mshRef = null;
                lock (root)
                {
                    mshRef = root.getSuccessor("MSH");
                    root.reset();
                }
                Segment msh = (Segment)result.get_Renamed("MSH");
                for (int i = 0; i < mshRef.Fields.Length; i++)
                {
                    int fieldNum = mshRef.Fields[i];
                    parse(mshFields[fieldNum - 1], msh, fieldNum, ec);
                }

                parse(tok, result, root, ec);
            }

            return(result);
        }
Exemplo n.º 14
0
        ///
        ///     <summary> * add - adds a integer list string to the existing integer list
        ///     * </summary>
        ///     * <param name="s"> the given string
        ///     * </param>
        ///     * <exception cref="FormatException"> - if the String has not a valid format </exception>
        ///
        public virtual void Add(string s)
        {
            //StringTokenizer sToken = new StringTokenizer(s, JDFConstants.BLANK);
            SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(s, JDFConstants.BLANK);

            ArrayList numList = m_numList;

            while (sToken.HasMoreTokens())
            {
                int i = StringUtil.parseInt(sToken.NextToken(), 0);

                try
                {
                    numList.Add(i);
                }
                catch (FormatException)
                {
                    throw new FormatException("Data format exception!");
                }
            }
        }
Exemplo n.º 15
0
        /// <summary> <p>A convenience method for registering applications (using <code>registerApplication()
        /// </code>) with this service.  Information about which Applications should handle which
        /// messages is read from the given text file.  Each line in the file should have the
        /// following format (entries tab delimited):</p>
        /// <p>message_type &#009; trigger_event &#009; application_class</p>
        /// <p>message_type &#009; trigger_event &#009; application_class</p>
        /// <p>Note that message type and event can be the wildcard "*", which means any.</p>
        /// <p>For example, if you write an Application called org.yourorganiztion.ADTProcessor
        /// that processes several types of ADT messages, and another called
        /// org.yourorganization.ResultProcessor that processes result messages, you might have a
        /// file that looks like this: </p>
        /// <p>ADT &#009; * &#009; org.yourorganization.ADTProcessor<br>
        /// ORU &#009; R01 &#009; org.yourorganization.ResultProcessor</p>
        /// <p>Each class listed in this file must implement Application and must have a zero-argument
        /// constructor.</p>
        /// </summary>
        public virtual void  loadApplicationsFromFile(System.IO.FileInfo f)
        {
            System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(f.FullName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(f.FullName, System.Text.Encoding.Default).CurrentEncoding);
            System.String          line       = null;
            while ((line = in_Renamed.ReadLine()) != null)
            {
                //parse application registration information
                SupportClass.Tokenizer tok = new SupportClass.Tokenizer(line, "\t", false);
                System.String          type = null, event_Renamed = null, className = null;

                if (tok.HasMoreTokens())
                {
                    //skip blank lines
                    try
                    {
                        type          = tok.NextToken();
                        event_Renamed = tok.NextToken();
                        className     = tok.NextToken();
                    }
                    catch (System.ArgumentOutOfRangeException)
                    {
                        throw new NuGenHL7Exception("Can't register applications from file " + f.Name + ". The line '" + line + "' is not of the form: message_type [tab] trigger_event [tab] application_class.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    System.Type      appClass  = System.Type.GetType(className);               //may throw ClassNotFoundException
                    System.Object    appObject = System.Activator.CreateInstance(appClass);
                    NuGenApplication app       = null;
                    try
                    {
                        app = (NuGenApplication)appObject;
                    }
                    catch (System.InvalidCastException)
                    {
                        throw new NuGenHL7Exception("The specified class, " + appClass.FullName + ", doesn't implement Application.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    this.registerApplication(type, event_Renamed, app);
                }
            }
        }
Exemplo n.º 16
0
        public override void characterData(CMLStack xpath, char[] ch, int start, int length)
        {
            System.String s = new System.String(ch, start, length).Trim();

            if (isELSYM)
            {
                elsym.Add(s);
            }
            else if (isBond)
            {
                //logger.debug("CD (bond): " + s);

                if (connect_root.Length > 0)
                {
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(s);

                    while (st.HasMoreTokens())
                    {
                        System.String atom = (System.String)st.NextToken();

                        if (!atom.Equals("0"))
                        {
                            //logger.debug("new bond: " + connect_root + "-" + atom);
                            cdo.startObject("Bond");

                            int atom1 = System.Int32.Parse(connect_root) - 1;
                            int atom2 = System.Int32.Parse(atom) - 1;
                            cdo.setObjectProperty("Bond", "atom1", ((System.Int32)atom1).ToString());
                            cdo.setObjectProperty("Bond", "atom2", ((System.Int32)atom2).ToString());
                            cdo.setObjectProperty("Bond", "order", "1");
                            cdo.endObject("Bond");
                        }
                    }
                }
            }
            else
            {
                base.characterData(xpath, ch, start, length);
            }
        }
Exemplo n.º 17
0
 /// <summary>  Description of the Method
 ///
 /// </summary>
 /// <param name="value"> Description of the Parameter
 /// </param>
 /// <returns>        Description of the Return Value
 /// </returns>
 public static Player fromString(System.String value_Renamed)
 {
     //		System.out.println("."+value+".");
     try
     {
         Player player             = new Player();
         SupportClass.Tokenizer st = new SupportClass.Tokenizer(value_Renamed, "\t");
         player.FullName     = st.NextToken();
         player.Rating       = System.Int32.Parse(st.NextToken());
         player.QuickRating  = System.Int32.Parse(st.NextToken());
         player.MemberNumber = st.NextToken();
         player.Expires      = st.NextToken();
         player.State        = st.NextToken();
         return(player);
     }
     catch (System.Exception e)
     {
         System.Console.Out.WriteLine(value_Renamed);
         SupportClass.WriteStackTrace(e, Console.Error);
         return(null);
     }
 }
Exemplo n.º 18
0
        /// <summary> Extracts the subtypes from the specified attribute name.
        ///
        /// For example, if the attribute name is cn;lang-ja;phonetic,
        /// this method returns an array containing lang-ja and phonetic.
        ///
        /// </summary>
        /// <param name="attrName">  Name of the attribute from which to extract
        /// the subtypes.
        ///
        /// </param>
        /// <returns> An array subtypes or null if the attribute has none.
        ///
        /// @throws IllegalArgumentException if attrName is null
        /// </returns>
        public static string[] getSubtypes(string attrName)
        {
            if ((object)attrName == null)
            {
                throw new ArgumentException("Attribute name cannot be null");
            }
            SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";");
            string[] subTypes         = null;
            int      cnt = st.Count;

            if (cnt > 0)
            {
                st.NextToken(); // skip over basename
                subTypes = new string[cnt - 1];
                int i = 0;
                while (st.HasMoreTokens())
                {
                    subTypes[i++] = st.NextToken();
                }
            }
            return(subTypes);
        }
Exemplo n.º 19
0
        private void ProcessResponse()
        {
            SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(begin, " \r\t");

            try
            {
                version = tokens.NextToken();
                status  = Int32.Parse(tokens.NextToken());
                if (tokens.HasMoreTokens())
                {
                    reason = tokens.NextToken();
                }
                else
                {
                    reason = "";
                }
            }
            catch
            {
                throw new IOException("Failed to parse HTTP response \"" + begin + "\"");
            }
        }
Exemplo n.º 20
0
        /// <summary>Gets path information from a path spec. </summary>
        private PathSpec parsePathSpec(System.String spec)
        {
            PathSpec ps = new PathSpec(this);

            if (spec.StartsWith("."))
            {
                ps.find = true;
                spec    = spec.Substring(1);
            }
            else
            {
                ps.find = false;
            }

            if (spec.Length == 0)
            {
                throw new NuGenHL7Exception("Invalid path (some path element is either empty or contains only a dot)");
            }
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "()", false);
            ps.pattern = tok.NextToken();
            if (tok.HasMoreTokens())
            {
                System.String repString = tok.NextToken();
                try
                {
                    ps.rep = System.Int32.Parse(repString);
                }
                catch (System.FormatException)
                {
                    throw new NuGenHL7Exception(repString + " is not a valid rep #", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                }
            }
            else
            {
                ps.rep = 0;
            }
            return(ps);
        }
Exemplo n.º 21
0
        private void  parse(System.String field, Segment segment, int num, NuGenEncodingCharacters ec)
        {
            if (field != null)
            {
                int  rep          = 0;
                int  component    = 1;
                int  subcomponent = 1;
                Type type         = segment.getField(num, rep);

                System.String delim = System.Convert.ToString(new char[] { ec.RepetitionSeparator, ec.ComponentSeparator, ec.SubcomponentSeparator });
                for (SupportClass.Tokenizer tok = new SupportClass.Tokenizer(field, delim, true); tok.HasMoreTokens();)
                {
                    System.String token = tok.NextToken();
                    char          c     = token[0];
                    if (c == ec.RepetitionSeparator)
                    {
                        rep++;
                        component    = 1;
                        subcomponent = 1;
                        type         = segment.getField(num, rep);
                    }
                    else if (c == ec.ComponentSeparator)
                    {
                        component++;
                        subcomponent = 1;
                    }
                    else if (c == ec.SubcomponentSeparator)
                    {
                        subcomponent++;
                    }
                    else
                    {
                        Primitive p = Terser.getPrimitive(type, component, subcomponent);
                        p.Value = token;
                    }
                }
            }
        }
Exemplo n.º 22
0
        ///
        ///     <summary> *
        ///     * constructs a VString by tokenizing a string </summary>
        ///     * <param name="strIn">  the string to tokenize </param>
        ///     * <param name="strSep"> the separator character </param>
        ///
        public VString(string strIn, string strSep)
            : base()
        {
            this.Clear();

            string strSepLocal = strSep;

            if (strIn != null)
            {
                if (strSepLocal == null)
                {
                    strSepLocal = JDFConstants.BLANK;
                }

                //StringTokenizer sToken = new StringTokenizer (strIn, strSepLocal);
                SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(strIn, strSepLocal);

                while (sToken.HasMoreTokens())
                {
                    this.Add(sToken.NextToken());
                }
            }
        }
Exemplo n.º 23
0
        private System.String getMolName(System.String line)
        {
            if (line == null)
            {
                return("");
            }
            SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " ");
            int ntok = st.Count;

            System.String[] toks = new System.String[ntok];
            for (int j = 0; j < ntok; j++)
            {
                toks[j] = st.NextToken();
            }
            if (toks.Length == 3)
            {
                return(toks[2]);
            }
            else
            {
                return("");
            }
        }
Exemplo n.º 24
0
        }         //end method

        /// <summary> Checks a code for an exact match, and using certain sequences where some
        /// characters are wildcards (e.g. HL7nnnn).  If the pattern contains one of
        /// " or ", " OR ", or "," each operand is checked.
        /// </summary>
        private bool checkCode(System.String code, System.String pattern)
        {
            bool match = false;

            //mod by Neal acharya - Do full match on with the pattern.  If code matches pattern then return true
            //else parse pattern to look for wildcard characters
            if (code.Equals(pattern))
            {
                match = true;
            }
            //end if
            else
            {
                if (pattern.IndexOf(' ') >= 0 || pattern.IndexOf(',') >= 0)
                {
                    SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pattern, ", ", false);
                    while (tok.HasMoreTokens() && !match)
                    {
                        System.String t = tok.NextToken();
                        if (!t.ToUpper().Equals("or".ToUpper()))
                        {
                            match = checkCode(code, t);
                        }
                    }                     //end while
                }
                //end if
                else
                {
                    if (code.Equals(pattern))
                    {
                        match = true;
                    }
                } //end else
            }     //end else
            return(match);
        }         //end method
Exemplo n.º 25
0
        ///
        ///	 <summary> * add - adds a x and a y coordinate to the vector
        ///	 *  </summary>
        ///	 * <param name="s"> a string with the x and y coordinate to add
        ///	 *  </param>
        ///	 * <exception cref="FormatException"> - if the String has not a valid format </exception>
        ///
        public virtual void add(string s)
        {
            //StringTokenizer sToken = new StringTokenizer(s, JDFConstants.BLANK);
            SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(s, JDFConstants.BLANK);

            if ((sToken.Count % 2) != 0)
            {
                throw new FormatException("Data format exception!");
            }

            while (sToken.HasMoreTokens())
            {
                string t = sToken.NextToken().Trim();

                try
                {
                    m_numList.Add(t); // (new double(t));
                }
                catch (FormatException)
                {
                    throw new FormatException("Data format exception!");
                }
            }
        }
Exemplo n.º 26
0
        ///
        ///	 <summary> * isValid - validates the given String
        ///	 *  </summary>
        ///	 * <param name="s"> the given string
        ///	 *  </param>
        ///	 * <exception cref="FormatException"> - if the String has not a valid format </exception>
        ///
        protected internal virtual void isValid(string s)
        {
            VString vs = new VString();

            //StringTokenizer sToken = new StringTokenizer(s, "~");
            SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(s, "~");

            while (sToken.HasMoreTokens())
            {
                string str = sToken.NextToken();
                vs.Add(str.Trim());
            }

            Left = vs[0];

            if (vs.Count == 2)
            {
                Right = vs[1];
            }
            else
            {
                Right = vs[0];
            }
        }
Exemplo n.º 27
0
	private static void  predict(System.IO.StreamReader input, System.IO.BinaryWriter output, svm_model model, int predict_probability)
	{
		int correct = 0;
		int total = 0;
		double error = 0;
		double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
		
		int svm_type = svm.svm_get_svm_type(model);
		int nr_class = svm.svm_get_nr_class(model);
		int[] labels = new int[nr_class];
		double[] prob_estimates = null;
		
		if (predict_probability == 1)
		{
			if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
			{
				System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
			}
			else
			{
				svm.svm_get_labels(model, labels);
				prob_estimates = new double[nr_class];
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("labels");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(" " + labels[j]);
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
		}
		while (true)
		{
			System.String line = input.ReadLine();
			if ((System.Object) line == null)
				break;
			
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");
			
			double target = atof(st.NextToken());
			int m = st.Count / 2;
			svm_node[] x = new svm_node[m];
			for (int j = 0; j < m; j++)
			{
				x[j] = new svm_node();
				x[j].index = atoi(st.NextToken());
				x[j].value_Renamed = atof(st.NextToken());
			}
			
			double v;
			if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
			{
				v = svm.svm_predict_probability(model, x, prob_estimates);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + " ");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(prob_estimates[j] + " ");
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
			else
			{
				v = svm.svm_predict(model, x);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + "\n");
			}
			
			if (v == target)
				++correct;
			error += (v - target) * (v - target);
			sumv += v;
			sumy += target;
			sumvv += v * v;
			sumyy += target * target;
			sumvy += v * target;
			++total;
		}
		System.Console.Out.Write("Accuracy = " + (double) correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
		System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
		System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
	}
Exemplo n.º 28
0
        /// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary>
        private Asn1Tagged parseFilterComp()
        {
            Asn1Tagged tag = null;
            int filterComp = ft.OpOrAttr;

            switch (filterComp)
            {

                case AND:
                case OR:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false);
                    break;

                case NOT:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true);
                    break;

                default:
                    int filterType = ft.FilterType;
                    System.String value_Renamed = ft.Value;

                    switch (filterType)
                    {

                        case GREATER_OR_EQUAL:
                        case LESS_OR_EQUAL:
                        case APPROX_MATCH:
                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            break;

                        case EQUALITY_MATCH:
                            if (value_Renamed.Equals("*"))
                            {
                                // present
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false);
                            }
                            else if (value_Renamed.IndexOf((System.Char) '*') != - 1)
                            {
                                // substrings parse:
                                //    [initial], *any*, [final] into an Asn1SequenceOf
                                SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*", true);
            //								SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true);
                                Asn1SequenceOf seq = new Asn1SequenceOf(5);
                                int tokCnt = sub.Count;
                                int cnt = 0;

                                System.String lastTok = new System.Text.StringBuilder("").ToString();

                                while (sub.HasMoreTokens())
                                {
                                    System.String subTok = sub.NextToken();
                                    cnt++;
                                    if (subTok.Equals("*"))
                                    {
                                        // if previous token was '*', and since the current
                                        // token is a '*', we need to insert 'any'
                                        if (lastTok.Equals(subTok))
                                        {
                                            // '**'
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false));
                                        }
                                    }
                                    else
                                    {
                                        // value (RfcLdapString)
                                        if (cnt == 1)
                                        {
                                            // initial
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else if (cnt < tokCnt)
                                        {
                                            // any
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else
                                        {
                                            // final
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                    }
                                    lastTok = subTok;
                                }

                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false);
                            }
                            else
                            {
                                // simple
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            }
                            break;

                        case EXTENSIBLE_MATCH:
                            System.String type = null, matchingRule = null;
                            bool dnAttributes = false;
            //							SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true);
                            SupportClass.Tokenizer st = new SupportClass.Tokenizer(ft.Attr, ":");//, true);

                            bool first = true;
                            while (st.HasMoreTokens())
                            {
                                System.String s = st.NextToken().Trim();
                                if (first && !s.Equals(":"))
                                {
                                    type = s;
                                }
                                // dn must be lower case to be considered dn of the Entry.
                                else if (s.Equals("dn"))
                                {
                                    dnAttributes = true;
                                }
                                else if (!s.Equals(":"))
                                {
                                    matchingRule = s;
                                }
                                first = false;
                            }

                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((System.Object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((System.Object) type == null)?null:new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), (dnAttributes == false)?null:new Asn1Boolean(true)), false);
                            break;
                        }
                    break;

            }
            return tag;
        }
Exemplo n.º 29
0
        internal static System.String determineAtomSetCollectionReader(System.IO.StreamReader bufferedReader)
        {
            System.String[]   lines = new System.String[4];
            LimitedLineReader llr   = new LimitedLineReader(bufferedReader, 16384);

            for (int i = 0; i < lines.Length; ++i)
            {
                lines[i] = llr.readLineWithNewline();
            }
            if (lines[3].Length >= 6)
            {
                System.String line4trimmed = lines[3].Trim();
                if (line4trimmed.EndsWith("V2000") || line4trimmed.EndsWith("v2000") || line4trimmed.EndsWith("V3000"))
                {
                    return("Mol");
                }
                try
                {
                    System.Int32.Parse(lines[3].Substring(0, (3) - (0)).Trim());
                    System.Int32.Parse(lines[3].Substring(3, (6) - (3)).Trim());
                    return("Mol");
                }
                catch (System.FormatException nfe)
                {
                }
            }
            try
            {
                /*int atomCount = */
                System.Int32.Parse(lines[0].Trim());
                return("Xyz");
            }
            catch (System.FormatException e)
            {
            }
            try
            {
                SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(lines[0].Trim(), " \t");
                if ((tokens != null) && (tokens.Count >= 2))
                {
                    System.Int32.Parse(tokens.NextToken().Trim());
                    return("FoldingXyz");
                }
            }
            catch (System.FormatException e)
            {
                //
            }
            // run these loops forward ... easier for people to understand
            for (int i = 0; i < startsWithRecords.Length; ++i)
            {
                System.String[] recordTags = startsWithRecords[i];
                for (int j = 0; j < recordTags.Length; ++j)
                {
                    System.String recordTag = recordTags[j];
                    for (int k = 0; k < lines.Length; ++k)
                    {
                        if (lines[k].StartsWith(recordTag))
                        {
                            return(startsWithFormats[i]);
                        }
                    }
                }
            }
            for (int i = 0; i < containsRecords.Length; ++i)
            {
                System.String[] recordTags = containsRecords[i];
                for (int j = 0; j < recordTags.Length; ++j)
                {
                    System.String recordTag = recordTags[j];
                    for (int k = 0; k < lines.Length; ++k)
                    {
                        if (lines[k].IndexOf(recordTag) != -1)
                        {
                            return(containsFormats[i]);
                        }
                    }
                }
            }

            if (lines[1] == null || lines[1].Trim().Length == 0)
            {
                return("Jme"); // this is really quite broken :-)
            }
            return(null);
        }
        /// <summary> Reads a text based configuration file.
        ///
        /// </summary>
        /// <param name="builder">IChemObjectBuilder used to construct the IAtomType's.
        /// </param>
        /// <throws>         IOException when a problem occured with reading from the InputStream </throws>
        /// <returns>        A Vector with read IAtomType's.
        /// </returns>
        public virtual System.Collections.ArrayList readAtomTypes(IChemObjectBuilder builder)
        {
            System.Collections.ArrayList atomTypes = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));

            if (ins == null)
            {
                // trying the default
                //System.out.println("readAtomTypes getResourceAsStream:"
                //                   + configFile);
                //UPGRADE_ISSUE: Method 'java.lang.ClassLoader.getResourceAsStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassLoader'"
                //UPGRADE_ISSUE: Method 'java.lang.Class.getClassLoader' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassgetClassLoader'"
                ins = Assembly.GetExecutingAssembly().GetManifestResourceStream("NuGenCDKSharp." + configFile);
            }
            if (ins == null)
            {
                throw new System.IO.IOException("There was a problem getting the default stream: " + configFile);
            }

            // read the contents from file
            //UPGRADE_TODO: The differences in the expected value  of parameters for constructor 'java.io.BufferedReader.BufferedReader'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
            //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
            System.IO.StreamReader reader = new System.IO.StreamReader(new System.IO.StreamReader(ins, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(ins, System.Text.Encoding.Default).CurrentEncoding, false, 1024);
            SupportClass.Tokenizer tokenizer;
            System.String          string_Renamed;

            while (true)
            {
                string_Renamed = reader.ReadLine();
                if (string_Renamed == null)
                {
                    break;
                }
                if (!string_Renamed.StartsWith("#"))
                {
                    System.String name = "";
                    System.String rootType = "";
                    int           atomicNumber = 0, colorR = 0, colorG = 0, colorB = 0;
                    double        mass = 0.0, vdwaals = 0.0, covalent = 0.0;
                    tokenizer = new SupportClass.Tokenizer(string_Renamed, "\t ,;");
                    int tokenCount = tokenizer.Count;

                    if (tokenCount == 9)
                    {
                        name     = tokenizer.NextToken();
                        rootType = tokenizer.NextToken();
                        System.String san       = tokenizer.NextToken();
                        System.String sam       = tokenizer.NextToken();
                        System.String svdwaals  = tokenizer.NextToken();
                        System.String scovalent = tokenizer.NextToken();
                        System.String sColorR   = tokenizer.NextToken();
                        System.String sColorG   = tokenizer.NextToken();
                        System.String sColorB   = tokenizer.NextToken();

                        try
                        {
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            mass = System.Double.Parse(sam);
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            vdwaals = System.Double.Parse(svdwaals);
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            covalent     = System.Double.Parse(scovalent);
                            atomicNumber = System.Int32.Parse(san);
                            colorR       = System.Int32.Parse(sColorR);
                            colorG       = System.Int32.Parse(sColorG);
                            colorB       = System.Int32.Parse(sColorB);
                        }
                        catch (System.FormatException nfe)
                        {
                            throw new System.IO.IOException("AtomTypeTable.ReadAtypes: " + "Malformed Number");
                        }

                        IAtomType atomType = builder.newAtomType(name, rootType);
                        atomType.AtomicNumber = atomicNumber;
                        atomType.setExactMass(mass);
                        atomType.VanderwaalsRadius = vdwaals;
                        atomType.CovalentRadius    = covalent;
                        System.Drawing.Color color = System.Drawing.Color.FromArgb(colorR, colorG, colorB);
                        atomType.setProperty("org.openscience.cdk.renderer.color", color);
                        atomTypes.Add(atomType);
                    }
                    else
                    {
                        throw new System.IO.IOException("AtomTypeTable.ReadAtypes: " + "Wrong Number of fields");
                    }
                }
            } // end while
            ins.Close();

            return(atomTypes);
        }
Exemplo n.º 31
0
		/// <summary> Constructs a new 'QuantTypeSpec' for the specified number of components
		/// and tiles and the arguments of "-Qtype" option. This constructor is
		/// called by the encoder.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public QuantTypeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qtype");
			if (param == null)
			{
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault("reversible");
				}
				else
				{
					setDefault("expounded");
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecValType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						
						if (curSpecValType == SPEC_COMP_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						
						if (curSpecValType == SPEC_TILE_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_COMP_DEF;
						}
						break;
					
					case 'r': 
					// reversible specification
					case 'd': 
					// derived quantization step size specification
					case 'e':  // expounded quantization step size specification
						if (!word.ToUpper().Equals("reversible".ToUpper()) && !word.ToUpper().Equals("derived".ToUpper()) && !word.ToUpper().Equals("expounded".ToUpper()))
						{
							throw new System.ArgumentException("Unknown parameter " + "for " + "'-Qtype' option: " + word);
						}
						
						if (pl.getBooleanParameter("lossless") && (word.ToUpper().Equals("derived".ToUpper()) || word.ToUpper().Equals("expounded".ToUpper())))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "quantization with " + "'-lossless' option");
						}
						
						if (curSpecValType == SPEC_DEF)
						{
							// Default specification
							setDefault(word);
						}
						else if (curSpecValType == SPEC_TILE_DEF)
						{
							// Tile default specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								if (tileSpec[i])
								{
									setTileDef(i, word);
								}
							}
						}
						else if (curSpecValType == SPEC_COMP_DEF)
						{
							// Component default specification 
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, word);
								}
						}
						else
						{
							// Tile-component specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, word);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecValType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Unknown parameter for " + "'-Qtype' option: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, the
				// quantization type is 'reversible' (if '-lossless' is specified)
				// or 'expounded' (if not). 
				if (ndefspec != 0)
				{
					if (pl.getBooleanParameter("lossless"))
					{
						setDefault("reversible");
					}
					else
					{
						setDefault("expounded");
					}
				}
				else
				{
					// All tile-component have been specified, takes arbitrarily
					// the first tile-component value as default and modifies the
					// specification type of all tile-component sharing this
					// value.
					setDefault(getTileCompVal(0, 0));
					
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Exemplo n.º 32
0
        /// <summary> Read a Reaction from a file in MDL RXN format
        ///
        /// </summary>
        /// <returns>  The Reaction that was read from the MDL file.
        /// </returns>
        private IMolecule readMolecule(IMolecule molecule)
        {
            AtomTypeFactory atFactory = null;

            try
            {
                atFactory = AtomTypeFactory.getInstance("mol2_atomtypes.xml", molecule.Builder);
            }
            catch (System.Exception exception)
            {
                System.String error = "Could not instantiate an AtomTypeFactory";
                //logger.error(error);
                //logger.debug(exception);
                throw new CDKException(error, exception);
            }
            try
            {
                System.String line      = input.ReadLine();
                int           atomCount = 0;
                int           bondCount = 0;
                while (line != null)
                {
                    if (line.StartsWith("@<TRIPOS>MOLECULE"))
                    {
                        //logger.info("Reading molecule block");
                        // second line has atom/bond counts?
                        input.ReadLine(); // disregard the name line
                        System.String          counts    = input.ReadLine();
                        SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(counts);
                        try
                        {
                            atomCount = System.Int32.Parse(tokenizer.NextToken());
                        }
                        catch (System.FormatException nfExc)
                        {
                            System.String error = "Error while reading atom count from MOLECULE block";
                            //logger.error(error);
                            //logger.debug(nfExc);
                            throw new CDKException(error, nfExc);
                        }
                        if (tokenizer.HasMoreTokens())
                        {
                            try
                            {
                                bondCount = System.Int32.Parse(tokenizer.NextToken());
                            }
                            catch (System.FormatException nfExc)
                            {
                                System.String error = "Error while reading atom and bond counts";
                                //logger.error(error);
                                //logger.debug(nfExc);
                                throw new CDKException(error, nfExc);
                            }
                        }
                        else
                        {
                            bondCount = 0;
                        }
                        //logger.info("Reading #atoms: ", atomCount);
                        //logger.info("Reading #bonds: ", bondCount);

                        //logger.warn("Not reading molecule qualifiers");
                    }
                    else if (line.StartsWith("@<TRIPOS>ATOM"))
                    {
                        //logger.info("Reading atom block");
                        for (int i = 0; i < atomCount; i++)
                        {
                            line = input.ReadLine().Trim();
                            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line);
                            tokenizer.NextToken(); // disregard the id token
                            System.String nameStr     = tokenizer.NextToken();
                            System.String xStr        = tokenizer.NextToken();
                            System.String yStr        = tokenizer.NextToken();
                            System.String zStr        = tokenizer.NextToken();
                            System.String atomTypeStr = tokenizer.NextToken();
                            IAtomType     atomType    = atFactory.getAtomType(atomTypeStr);
                            if (atomType == null)
                            {
                                atomType = atFactory.getAtomType("X");
                                //logger.error("Could not find specified atom type: ", atomTypeStr);
                            }
                            IAtom atom = molecule.Builder.newAtom("X");
                            atom.ID           = nameStr;
                            atom.AtomTypeName = atomTypeStr;
                            atFactory.configure(atom);
                            try
                            {
                                double x = System.Double.Parse(xStr);
                                double y = System.Double.Parse(yStr);
                                double z = System.Double.Parse(zStr);
                                atom.setPoint3d(new Point3d(x, y, z));
                            }
                            catch (System.FormatException nfExc)
                            {
                                System.String error = "Error while reading atom coordinates";
                                //logger.error(error);
                                //logger.debug(nfExc);
                                throw new CDKException(error, nfExc);
                            }
                            molecule.addAtom(atom);
                        }
                    }
                    else if (line.StartsWith("@<TRIPOS>BOND"))
                    {
                        //logger.info("Reading bond block");
                        for (int i = 0; i < bondCount; i++)
                        {
                            line = input.ReadLine();
                            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line);
                            tokenizer.NextToken(); // disregard the id token
                            System.String atom1Str = tokenizer.NextToken();
                            System.String atom2Str = tokenizer.NextToken();
                            System.String orderStr = tokenizer.NextToken();
                            try
                            {
                                int    atom1 = System.Int32.Parse(atom1Str);
                                int    atom2 = System.Int32.Parse(atom2Str);
                                double order = 0;
                                if ("1".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_AROMATIC;
                                }
                                else if ("2".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_DOUBLE;
                                }
                                else if ("3".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_TRIPLE;
                                }
                                else if ("am".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_SINGLE;
                                }
                                else if ("ar".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_AROMATIC;
                                }
                                else if ("du".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_SINGLE;
                                }
                                else if ("un".Equals(orderStr))
                                {
                                    order = CDKConstants.BONDORDER_SINGLE;
                                }
                                else if ("nc".Equals(orderStr))
                                {
                                    // not connected
                                    order = 0;
                                }
                                if (order != 0)
                                {
                                    molecule.addBond(atom1 - 1, atom2 - 1, order);
                                }
                            }
                            catch (System.FormatException nfExc)
                            {
                                System.String error = "Error while reading bond information";
                                //logger.error(error);
                                //logger.debug(nfExc);
                                throw new CDKException(error, nfExc);
                            }
                        }
                    }
                    line = input.ReadLine();
                }
            }
            catch (System.IO.IOException exception)
            {
                System.String error = "Error while reading general structure";
                //logger.error(error);
                //logger.debug(exception);
                throw new CDKException(error, exception);
            }
            return(molecule);
        }
Exemplo n.º 33
0
		/// <summary> Constructs a new 'IntegerSpec' for the specified number of tiles and
		/// components, the allowed specifications type and the ParameterList
		/// instance. This constructor is normally called at encoder side and parse
		/// arguments of specified option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">The allowed specifications type
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		/// <param name="optName">The name of the option to process
		/// 
		/// </param>
		public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName):base(nt, nc, type)
		{
			
			System.Int32 value_Renamed;
			System.String param = pl.getParameter(optName);
			
			if (param == null)
			{
				// No parameter specified
				param = pl.DefaultParameterList.getParameter(optName);
				try
				{
					setDefault((System.Object) System.Int32.Parse(param));
				}
				catch (System.FormatException)
				{
					throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					default: 
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word);
						}
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					param = pl.DefaultParameterList.getParameter(optName);
					try
					{
						setDefault((System.Object) System.Int32.Parse(param));
					}
					catch (System.FormatException)
					{
						throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
					}
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Exemplo n.º 34
0
		/// <summary> Returns a String representing the encoding of the given message, if
		/// the encoding is recognized.  For example if the given message appears
		/// to be encoded using HL7 2.x XML rules then "XML" would be returned.
		/// If the encoding is not recognized then null is returned.  That this
		/// method returns a specific encoding does not guarantee that the
		/// message is correctly encoded (e.g. well formed XML) - just that
		/// it is not encoded using any other encoding than the one returned.
		/// </summary>
		public override System.String getEncoding(System.String message)
		{
			System.String encoding = null;
			
			//quit if the string is too short
			if (message.Length < 4)
				return null;
			
			//see if it looks like this message is | encoded ...
			bool ok = true;
			
			//string should start with "MSH"
			if (!message.StartsWith("MSH"))
				return null;
			
			//4th character of each segment should be field delimiter
			char fourthChar = message[3];
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(message, System.Convert.ToString(segDelim), false);
			while (st.HasMoreTokens())
			{
				System.String x = st.NextToken();
				if (x.Length > 0)
				{
					if (System.Char.IsWhiteSpace(x[0]))
						x = stripLeadingWhitespace(x);
					if (x.Length >= 4 && x[3] != fourthChar)
						return null;
				}
			}
			
			//should be at least 11 field delimiters (because MSH-12 is required)
			int nextFieldDelimLoc = 0;
			for (int i = 0; i < 11; i++)
			{
				nextFieldDelimLoc = message.IndexOf((System.Char) fourthChar, nextFieldDelimLoc + 1);
				if (nextFieldDelimLoc < 0)
					return null;
			}
			
			if (ok)
				encoding = "VB";
			
			return encoding;
		}
Exemplo n.º 35
0
		/// <summary> Creates a new PGX file reader from the specified File object.
		/// 
		/// </summary>
		/// <param name="in">The input file as File object.
		/// 
		/// </param>
		/// <exception cref="IOException">If an I/O error occurs.
		/// 
		/// </exception>
		public ImgReaderPGX(System.IO.FileInfo in_Renamed)
		{
			System.String header;
			
			// Check if specified file exists
			bool tmpBool;
			if (System.IO.File.Exists(in_Renamed.FullName))
				tmpBool = true;
			else
				tmpBool = System.IO.Directory.Exists(in_Renamed.FullName);
			if (!tmpBool)
			{
				throw new System.ArgumentException("PGX file " + in_Renamed.Name + " does not exist");
			}
			
			//Opens the given file
			this.in_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(in_Renamed, "r");
			try
			{
                System.IO.StreamReader in_reader = new System.IO.StreamReader(this.in_Renamed);
				//UPGRADE_ISSUE: Method 'java.io.RandomAccessFile.readLine' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioRandomAccessFilereadLine'"
				header = in_reader.ReadLine();
			}
			catch (System.IO.IOException)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
			}
			if (header == null)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is an empty file");
			}
			offset = (header.Length + 1);
			
			//Get informations from header
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(header);
			try
			{
				int nTokens = st.Count;
				
				// Magic Number
				if (!(st.NextToken()).Equals("PG"))
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				
				// Endianess
				System.String tmp = st.NextToken();
				if (tmp.Equals("LM"))
					byteOrder = CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN;
				else if (tmp.Equals("ML"))
					byteOrder = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN;
				else
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				
				// Unsigned/signed if present in the header
				if (nTokens == 6)
				{
					tmp = st.NextToken();
					if (tmp.Equals("+"))
						isSigned = false;
					else if (tmp.Equals("-"))
						isSigned = true;
					else
						throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				}
				
				// bit-depth, width, height
				try
				{
					bitDepth = (System.Int32.Parse(st.NextToken()));
					// bitDepth must be between 1 and 31
					if ((bitDepth <= 0) || (bitDepth > 31))
						throw new System.IO.IOException(in_Renamed.Name + " is not a valid PGX file");
					
					w = (System.Int32.Parse(st.NextToken()));
					h = (System.Int32.Parse(st.NextToken()));
				}
				catch (System.FormatException)
				{
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				}
			}
			catch (System.ArgumentOutOfRangeException)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
			}
			
			// Number of component
			nc = 1;
			
			// Number of bytes per data
			if (bitDepth <= 8)
				packBytes = 1;
			else if (bitDepth <= 16)
				packBytes = 2;
			// <= 31
			else
				packBytes = 4;
		}
Exemplo n.º 36
0
		/// <summary> Splits the given composite string into an array of components using the given
		/// delimiter.
		/// </summary>
		public static System.String[] split(System.String composite, System.String delim)
		{
			System.Collections.ArrayList components = new System.Collections.ArrayList();
			
			//defend against evil nulls
			if (composite == null)
				composite = "";
			if (delim == null)
				delim = "";
			
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(composite, delim, true);
			bool previousTokenWasDelim = true;
			while (tok.HasMoreTokens())
			{
				System.String thisTok = tok.NextToken();
				if (thisTok.Equals(delim))
				{
					if (previousTokenWasDelim)
						components.Add(null);
					previousTokenWasDelim = true;
				}
				else
				{
					components.Add(thisTok);
					previousTokenWasDelim = false;
				}
			}
			
			System.String[] ret = new System.String[components.Count];
			for (int i = 0; i < components.Count; i++)
			{
				ret[i] = ((System.String) components[i]);
			}
			
			return ret;
		}
Exemplo n.º 37
0
        /// <summary> Creates a ForwardWT object with the specified filters, and with other
        /// options specified in the parameter list 'pl'.
        ///
        /// </summary>
        /// <param name="src">The source of data to be transformed
        ///
        /// </param>
        /// <param name="pl">The parameter list (or options).
        ///
        /// </param>
        /// <param name="kers">The encoder specifications.
        ///
        /// </param>
        /// <returns> A new ForwardWT object with the specified filters and options
        /// from 'pl'.
        ///
        /// </returns>
        /// <exception cref="IllegalArgumentException">If mandatory parameters are missing
        /// or if invalid values are given.
        ///
        /// </exception>
        public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec)
        {
            int deflev; // defdec removed

            //System.String decompstr;
            //System.String wtstr;
            //System.String pstr;
            //SupportClass.StreamTokenizerSupport stok;
            //SupportClass.Tokenizer strtok;
            //int prefx, prefy; // Partitioning reference point coordinates

            // Check parameters
            pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));

            deflev = ((System.Int32)encSpec.dls.getDefault());

            // Code-block partition origin
            System.String str = "";
            if (pl.getParameter("Wcboff") == null)
            {
                throw new System.InvalidOperationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option");
            }
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff"));
            if (stk.Count != 2)
            {
                throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option.");
            }
            int cb0x = 0;

            str = stk.NextToken();
            try
            {
                cb0x = (System.Int32.Parse(str));
            }
            catch (System.FormatException e)
            {
                throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str);
            }
            if (cb0x < 0 || cb0x > 1)
            {
                throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin.");
            }
            int cb0y = 0;

            str = stk.NextToken();
            try
            {
                cb0y = (System.Int32.Parse(str));
            }
            catch (System.FormatException e)
            {
                throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str);
            }
            if (cb0y < 0 || cb0y > 1)
            {
                throw new System.ArgumentException("Invalid vertical " + "code-block partition origin.");
            }
            if (cb0x != 0 || cb0y != 0)
            {
                FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders.");
            }

            return(new ForwWTFull(src, encSpec, cb0x, cb0y));
        }
Exemplo n.º 38
0
        private IChemModel readChemModel(IChemModel model)
        {
            int[]    atoms       = new int[1];
            double[] atomxs      = new double[1];
            double[] atomys      = new double[1];
            double[] atomzs      = new double[1];
            double[] atomcharges = new double[1];

            int[] bondatomid1 = new int[1];
            int[] bondatomid2 = new int[1];
            int[] bondorder   = new int[1];

            int numberOfAtoms = 0;
            int numberOfBonds = 0;

            try
            {
                System.String line = input.ReadLine();
                while (line != null)
                {
                    SupportClass.Tokenizer st      = new SupportClass.Tokenizer(line);
                    System.String          command = st.NextToken();
                    if ("!Header".Equals(command))
                    {
                        //logger.warn("Ignoring header");
                    }
                    else if ("!Info".Equals(command))
                    {
                        //logger.warn("Ignoring info");
                    }
                    else if ("!Atoms".Equals(command))
                    {
                        //logger.info("Reading atom block");
                        // determine number of atoms to read
                        try
                        {
                            numberOfAtoms = System.Int32.Parse(st.NextToken());
                            //logger.debug("  #atoms: " + numberOfAtoms);
                            atoms       = new int[numberOfAtoms];
                            atomxs      = new double[numberOfAtoms];
                            atomys      = new double[numberOfAtoms];
                            atomzs      = new double[numberOfAtoms];
                            atomcharges = new double[numberOfAtoms];

                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                atoms[atomID] = System.Int32.Parse(atomInfoFields.NextToken());
                                //logger.debug("Set atomic number of atom (" + atomID + ") to: " + atoms[atomID]);
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Atoms block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Bonds".Equals(command))
                    {
                        //logger.info("Reading bond block");
                        try
                        {
                            // determine number of bonds to read
                            numberOfBonds = System.Int32.Parse(st.NextToken());
                            bondatomid1   = new int[numberOfAtoms];
                            bondatomid2   = new int[numberOfAtoms];
                            bondorder     = new int[numberOfAtoms];

                            for (int i = 0; i < numberOfBonds; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer bondInfoFields = new SupportClass.Tokenizer(line);
                                bondatomid1[i] = System.Int32.Parse(bondInfoFields.NextToken());
                                bondatomid2[i] = System.Int32.Parse(bondInfoFields.NextToken());
                                System.String order = bondInfoFields.NextToken();
                                if ("D".Equals(order))
                                {
                                    bondorder[i] = 2;
                                }
                                else if ("S".Equals(order))
                                {
                                    bondorder[i] = 1;
                                }
                                else if ("T".Equals(order))
                                {
                                    bondorder[i] = 3;
                                }
                                else
                                {
                                    // ignore order, i.e. set to single
                                    //logger.warn("Unrecognized bond order, using single bond instead. Found: " + order);
                                    bondorder[i] = 1;
                                }
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Bonds block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Coord".Equals(command))
                    {
                        //logger.info("Reading coordinate block");
                        try
                        {
                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int    atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                double x      = System.Double.Parse(atomInfoFields.NextToken());
                                double y      = System.Double.Parse(atomInfoFields.NextToken());
                                double z      = System.Double.Parse(atomInfoFields.NextToken());
                                atomxs[atomID] = x;
                                atomys[atomID] = y;
                                atomzs[atomID] = z;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Coord block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Charges".Equals(command))
                    {
                        //logger.info("Reading charges block");
                        try
                        {
                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int    atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                double charge = System.Double.Parse(atomInfoFields.NextToken());
                                atomcharges[atomID] = charge;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Charges block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!End".Equals(command))
                    {
                        //logger.info("Found end of file");
                        // Store atoms
                        IAtomContainer container = model.Builder.newAtomContainer();
                        for (int i = 0; i < numberOfAtoms; i++)
                        {
                            try
                            {
                                IAtom atom = model.Builder.newAtom(IsotopeFactory.getInstance(container.Builder).getElementSymbol(atoms[i]));
                                atom.AtomicNumber = atoms[i];
                                atom.setPoint3d(new Point3d(atomxs[i], atomys[i], atomzs[i]));
                                atom.setCharge(atomcharges[i]);
                                container.addAtom(atom);
                                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                                //logger.debug("Stored atom: " + atom);
                            }
                            catch (System.Exception exception)
                            {
                                //logger.error("Cannot create an atom with atomic number: " + atoms[i]);
                                //logger.debug(exception);
                            }
                        }

                        // Store bonds
                        for (int i = 0; i < numberOfBonds; i++)
                        {
                            container.addBond(bondatomid1[i], bondatomid2[i], bondorder[i]);
                        }

                        ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules();
                        moleculeSet.addMolecule(model.Builder.newMolecule(container));
                        model.SetOfMolecules = moleculeSet;

                        return(model);
                    }
                    else
                    {
                        //logger.warn("Skipping line: " + line);
                    }

                    line = input.ReadLine();
                }
            }
            catch (System.Exception exception)
            {
                //logger.error("Error while reading file");
                //logger.debug(exception);
            }

            // this should not happen, file is lacking !End command
            return(null);
        }
Exemplo n.º 39
0
        /// <summary> Constructs a new 'AnWTFilterSpec' for the specified number of
        /// components and tiles.
        ///
        /// </summary>
        /// <param name="nt">The number of tiles
        ///
        /// </param>
        /// <param name="nc">The number of components
        ///
        /// </param>
        /// <param name="type">the type of the specification module i.e. tile specific,
        /// component specific or both.
        ///
        /// </param>
        /// <param name="qts">Quantization specifications
        ///
        /// </param>
        /// <param name="pl">The ParameterList
        ///
        /// </param>
        public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl) : base(nt, nc, type)
        {
            // Check parameters
            pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo));

            System.String param             = pl.getParameter("Ffilters");
            bool          isFilterSpecified = true;

            // No parameter specified
            if (param == null)
            {
                isFilterSpecified = false;

                // If lossless compression, uses the reversible filters in each
                // tile-components
                if (pl.getBooleanParameter("lossless"))
                {
                    setDefault(parseFilters(REV_FILTER_STR));
                    return;
                }

                // If no filter is specified through the command-line, use
                // REV_FILTER_STR or NON_REV_FILTER_STR according to the
                // quantization type
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        switch (qts.getSpecValType(t, c))
                        {
                        case SPEC_DEF:
                            if (getDefault() == null)
                            {
                                if (pl.getBooleanParameter("lossless"))
                                {
                                    setDefault(parseFilters(REV_FILTER_STR));
                                }
                                if (((System.String)qts.getDefault()).Equals("reversible"))
                                {
                                    setDefault(parseFilters(REV_FILTER_STR));
                                }
                                else
                                {
                                    setDefault(parseFilters(NON_REV_FILTER_STR));
                                }
                            }
                            specValType[t][c] = SPEC_DEF;
                            break;

                        case SPEC_COMP_DEF:
                            if (!isCompSpecified(c))
                            {
                                if (((System.String)qts.getCompDef(c)).Equals("reversible"))
                                {
                                    setCompDef(c, parseFilters(REV_FILTER_STR));
                                }
                                else
                                {
                                    setCompDef(c, parseFilters(NON_REV_FILTER_STR));
                                }
                            }
                            specValType[t][c] = SPEC_COMP_DEF;
                            break;

                        case SPEC_TILE_DEF:
                            if (!isTileSpecified(t))
                            {
                                if (((System.String)qts.getTileDef(t)).Equals("reversible"))
                                {
                                    setTileDef(t, parseFilters(REV_FILTER_STR));
                                }
                                else
                                {
                                    setTileDef(t, parseFilters(NON_REV_FILTER_STR));
                                }
                            }
                            specValType[t][c] = SPEC_TILE_DEF;
                            break;

                        case SPEC_TILE_COMP:
                            if (!isTileCompSpecified(t, c))
                            {
                                if (((System.String)qts.getTileCompVal(t, c)).Equals("reversible"))
                                {
                                    setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
                                }
                                else
                                {
                                    setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
                                }
                            }
                            specValType[t][c] = SPEC_TILE_COMP;
                            break;

                        default:
                            throw new System.ArgumentException("Unsupported " + "specification " + "type");
                        }
                    }
                }
                return;
            }

            // Parse argument
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            System.String          word;    // current word
            byte curSpecType = SPEC_DEF;    // Specification type of the

            // current parameter
            bool[]         tileSpec = null;     // Tiles concerned by the specification
            bool[]         compSpec = null;     // Components concerned by the specification
            AnWTFilter[][] filter;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {
                case 't':
                // Tiles specification
                case 'T':                          // Tiles specification
                    tileSpec = parseIdx(word, nTiles);
                    if (curSpecType == SPEC_COMP_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_TILE_DEF;
                    }
                    break;

                case 'c':
                // Components specification
                case 'C':                          // Components specification
                    compSpec = parseIdx(word, nComp);
                    if (curSpecType == SPEC_TILE_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_COMP_DEF;
                    }
                    break;

                case 'w':
                // WT filters specification
                case 'W':                          // WT filters specification
                    if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper()))
                    {
                        throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option");
                    }

                    filter = parseFilters(word);
                    if (curSpecType == SPEC_DEF)
                    {
                        setDefault(filter);
                    }
                    else if (curSpecType == SPEC_TILE_DEF)
                    {
                        for (int i = tileSpec.Length - 1; i >= 0; i--)
                        {
                            if (tileSpec[i])
                            {
                                setTileDef(i, filter);
                            }
                        }
                    }
                    else if (curSpecType == SPEC_COMP_DEF)
                    {
                        for (int i = compSpec.Length - 1; i >= 0; i--)
                        {
                            if (compSpec[i])
                            {
                                setCompDef(i, filter);
                            }
                        }
                    }
                    else
                    {
                        for (int i = tileSpec.Length - 1; i >= 0; i--)
                        {
                            for (int j = compSpec.Length - 1; j >= 0; j--)
                            {
                                if (tileSpec[i] && compSpec[j])
                                {
                                    setTileCompVal(i, j, filter);
                                }
                            }
                        }
                    }

                    // Re-initialize
                    curSpecType = SPEC_DEF;
                    tileSpec    = null;
                    compSpec    = null;
                    break;


                default:
                    throw new System.ArgumentException("Bad construction for " + "parameter: " + word);
                }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, it takes
                // the default value defined in ParameterList
                if (ndefspec != 0)
                {
                    if (((System.String)qts.getDefault()).Equals("reversible"))
                    {
                        setDefault(parseFilters(REV_FILTER_STR));
                    }
                    else
                    {
                        setDefault(parseFilters(NON_REV_FILTER_STR));
                    }
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {
                    case SPEC_TILE_DEF:
                        for (int c = nc - 1; c >= 0; c--)
                        {
                            if (specValType[0][c] == SPEC_TILE_DEF)
                            {
                                specValType[0][c] = SPEC_DEF;
                            }
                        }
                        tileDef[0] = null;
                        break;

                    case SPEC_COMP_DEF:
                        for (int t = nt - 1; t >= 0; t--)
                        {
                            if (specValType[t][0] == SPEC_COMP_DEF)
                            {
                                specValType[t][0] = SPEC_DEF;
                            }
                        }
                        compDef[0] = null;
                        break;

                    case SPEC_TILE_COMP:
                        specValType[0][0]   = SPEC_DEF;
                        tileCompVal["t0c0"] = null;
                        break;
                    }
                }
            }

            // Check consistency between filter and quantization type
            // specification
            for (int t = nt - 1; t >= 0; t--)
            {
                for (int c = nc - 1; c >= 0; c--)
                {
                    // Reversible quantization
                    if (((System.String)qts.getTileCompVal(t, c)).Equals("reversible"))
                    {
                        // If filter is reversible, it is OK
                        if (isReversible(t, c))
                        {
                            continue;
                        }

                        // If no filter has been defined, use reversible filter
                        if (!isFilterSpecified)
                        {
                            setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
                        }
                        else
                        {
                            // Non reversible filter specified -> Error
                            throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line.");
                        }
                    }
                    else
                    {
                        // No reversible quantization
                        // No reversible filter -> OK
                        if (!isReversible(t, c))
                        {
                            continue;
                        }

                        // If no filter has been specified, use non-reversible
                        // filter
                        if (!isFilterSpecified)
                        {
                            setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
                        }
                        else
                        {
                            // Reversible filter specified -> Error
                            throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line");
                        }
                    }
                }
            }
        }
        /// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles
        /// and components and the ParameterList instance.
        ///
        /// </summary>
        /// <param name="nt">The number of tiles
        ///
        /// </param>
        /// <param name="nc">The number of components
        ///
        /// </param>
        /// <param name="type">the type of the specification module i.e. tile specific,
        /// component specific or both.
        ///
        /// </param>
        /// <param name="imgsrc">The image source (used to get the image size)
        ///
        /// </param>
        /// <param name="pl">The ParameterList instance
        ///
        /// </param>
        public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl) : base(nt, nc, type)
        {
            this.dls = dls;

            // The precinct sizes are stored in a 2 elements vector array, the
            // first element containing a vector for the precincts width for each
            // resolution level and the second element containing a vector for the
            // precincts height for each resolution level. The precincts sizes are
            // specified from the highest resolution level to the lowest one
            // (i.e. 0).  If there are less elements than the number of
            // decomposition levels, the last element is used for all remaining
            // resolution levels (i.e. if the precincts sizes are specified only
            // for resolutions levels 5, 4 and 3, then the precincts size for
            // resolution levels 2, 1 and 0 will be the same as the size used for
            // resolution level 3).

            // Boolean used to know if we were previously reading a precinct's
            // size or if we were reading something else.
            bool wasReadingPrecinctSize = false;

            System.String param = pl.getParameter(optName);

            // Set precinct sizes to default i.e. 2^15 =
            // Markers.PRECINCT_PARTITION_DEF_SIZE
            System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2];
            tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));             // ppx
            tmpv[0].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
            tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));             // ppy
            tmpv[1].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
            setDefault(tmpv);

            if (param == null)
            {
                // No precinct size specified in the command line so we do not try
                // to parse it.
                return;
            }

            // Precinct partition is used : parse arguments
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType           = SPEC_DEF;   // Specification type of the

            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            bool[] compSpec = null; // Components concerned by the specification
            int    ci, ti;          //i, xIdx removed

            bool endOfParamList = false;

            System.String word = null;             // current word
            System.Int32  w, h;
            System.String errMsg = null;

            while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList)
            {
                System.Collections.ArrayList[] v = new System.Collections.ArrayList[2];                 // v[0] : ppx, v[1] : ppy

                // We do not read the next token if we were reading a precinct's
                // size argument as we have already read the next token into word.
                if (!wasReadingPrecinctSize)
                {
                    word = stk.NextToken();
                }

                wasReadingPrecinctSize = false;

                switch (word[0])
                {
                case 't':                          // Tiles specification
                    tileSpec = parseIdx(word, nTiles);
                    if (curSpecType == SPEC_COMP_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_TILE_DEF;
                    }
                    break;


                case 'c':                          // Components specification
                    compSpec = parseIdx(word, nComp);
                    if (curSpecType == SPEC_TILE_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_COMP_DEF;
                    }
                    break;


                default:
                    if (!System.Char.IsDigit(word[0]))
                    {
                        errMsg = "Bad construction for parameter: " + word;
                        throw new System.ArgumentException(errMsg);
                    }

                    // Initialises Vector objects
                    v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));                             // ppx
                    v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));                             // ppy

                    while (true)
                    {
                        // Now get the precinct dimensions
                        try
                        {
                            // Get precinct width
                            w = System.Int32.Parse(word);

                            // Get next word in argument list
                            try
                            {
                                word = stk.NextToken();
                            }
                            catch (System.ArgumentOutOfRangeException)
                            {
                                errMsg = "'" + optName + "' option : could not " + "parse the precinct's width";
                                throw new System.ArgumentException(errMsg);
                            }
                            // Get precinct height
                            h = System.Int32.Parse(word);
                            if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h)))
                            {
                                errMsg = "Precinct dimensions must be powers of 2";
                                throw new System.ArgumentException(errMsg);
                            }
                        }
                        catch (System.FormatException)
                        {
                            errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed.";
                            throw new System.ArgumentException(errMsg);
                        }
                        // Store packet's dimensions in Vector arrays
                        v[0].Add(w);
                        v[1].Add(h);

                        // Try to get the next token
                        if (stk.HasMoreTokens())
                        {
                            word = stk.NextToken();
                            if (!System.Char.IsDigit(word[0]))
                            {
                                // The next token does not start with a digit so
                                // it is not a precinct's size argument. We set
                                // the wasReadingPrecinctSize booleen such that we
                                // know that we don't have to read another token
                                // and check for the end of the parameters list.
                                wasReadingPrecinctSize = true;

                                if (curSpecType == SPEC_DEF)
                                {
                                    setDefault(v);
                                }
                                else if (curSpecType == SPEC_TILE_DEF)
                                {
                                    for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                                    {
                                        if (tileSpec[ti])
                                        {
                                            setTileDef(ti, v);
                                        }
                                    }
                                }
                                else if (curSpecType == SPEC_COMP_DEF)
                                {
                                    for (ci = compSpec.Length - 1; ci >= 0; ci--)
                                    {
                                        if (compSpec[ci])
                                        {
                                            setCompDef(ci, v);
                                        }
                                    }
                                }
                                else
                                {
                                    for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                                    {
                                        for (ci = compSpec.Length - 1; ci >= 0; ci--)
                                        {
                                            if (tileSpec[ti] && compSpec[ci])
                                            {
                                                setTileCompVal(ti, ci, v);
                                            }
                                        }
                                    }
                                }
                                // Re-initialize
                                curSpecType = SPEC_DEF;
                                tileSpec    = null;
                                compSpec    = null;

                                // Go back to 'normal' parsing
                                break;
                            }
                            else
                            {
                                // Next token starts with a digit so read it
                            }
                        }
                        else
                        {
                            // We have reached the end of the parameters list so
                            // we store the last precinct's sizes and we stop
                            if (curSpecType == SPEC_DEF)
                            {
                                setDefault(v);
                            }
                            else if (curSpecType == SPEC_TILE_DEF)
                            {
                                for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                                {
                                    if (tileSpec[ti])
                                    {
                                        setTileDef(ti, v);
                                    }
                                }
                            }
                            else if (curSpecType == SPEC_COMP_DEF)
                            {
                                for (ci = compSpec.Length - 1; ci >= 0; ci--)
                                {
                                    if (compSpec[ci])
                                    {
                                        setCompDef(ci, v);
                                    }
                                }
                            }
                            else
                            {
                                for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                                {
                                    for (ci = compSpec.Length - 1; ci >= 0; ci--)
                                    {
                                        if (tileSpec[ti] && compSpec[ci])
                                        {
                                            setTileCompVal(ti, ci, v);
                                        }
                                    }
                                }
                            }
                            endOfParamList = true;
                            break;
                        }
                    }     // while (true)
                    break;
                }         // switch
            }             // while
        }
Exemplo n.º 41
0
		/// <summary> Constructs a new 'AnWTFilterSpec' for the specified number of
		/// components and tiles.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="qts">Quantization specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl):base(nt, nc, type)
		{
			
			// Check parameters
			pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo));
			
			System.String param = pl.getParameter("Ffilters");
			bool isFilterSpecified = true;
			
			// No parameter specified
			if (param == null)
			{
				isFilterSpecified = false;
				
				// If lossless compression, uses the reversible filters in each
				// tile-components 
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault(parseFilters(REV_FILTER_STR));
					return ;
				}
				
				// If no filter is specified through the command-line, use
				// REV_FILTER_STR or NON_REV_FILTER_STR according to the
				// quantization type
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						switch (qts.getSpecValType(t, c))
						{
							
							case SPEC_DEF: 
								if (getDefault() == null)
								{
									if (pl.getBooleanParameter("lossless"))
										setDefault(parseFilters(REV_FILTER_STR));
									if (((System.String) qts.getDefault()).Equals("reversible"))
									{
										setDefault(parseFilters(REV_FILTER_STR));
									}
									else
									{
										setDefault(parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_DEF;
								break;
							
							case SPEC_COMP_DEF: 
								if (!isCompSpecified(c))
								{
									if (((System.String) qts.getCompDef(c)).Equals("reversible"))
									{
										setCompDef(c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setCompDef(c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_COMP_DEF;
								break;
							
							case SPEC_TILE_DEF: 
								if (!isTileSpecified(t))
								{
									if (((System.String) qts.getTileDef(t)).Equals("reversible"))
									{
										setTileDef(t, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileDef(t, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_DEF;
								break;
							
							case SPEC_TILE_COMP: 
								if (!isTileCompSpecified(t, c))
								{
									if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
									{
										setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_COMP;
								break;
							
							default: 
								throw new System.ArgumentException("Unsupported " + "specification " + "type");
							
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			AnWTFilter[][] filter;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't': 
					// Tiles specification
					case 'T':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c': 
					// Components specification
					case 'C':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					case 'w': 
					// WT filters specification
					case 'W':  // WT filters specification
						if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper()))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option");
						}
						
						filter = parseFilters(word);
						if (curSpecType == SPEC_DEF)
						{
							setDefault(filter);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, filter);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, filter);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, filter);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Bad construction for " + "parameter: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					if (((System.String) qts.getDefault()).Equals("reversible"))
						setDefault(parseFilters(REV_FILTER_STR));
					else
						setDefault(parseFilters(NON_REV_FILTER_STR));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
			
			// Check consistency between filter and quantization type
			// specification
			for (int t = nt - 1; t >= 0; t--)
			{
				for (int c = nc - 1; c >= 0; c--)
				{
					// Reversible quantization
					if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
					{
						// If filter is reversible, it is OK
						if (isReversible(t, c))
							continue;
						
						// If no filter has been defined, use reversible filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
						}
						else
						{
							// Non reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line.");
						}
					}
					else
					{
						// No reversible quantization
						// No reversible filter -> OK
						if (!isReversible(t, c))
							continue;
						
						// If no filter has been specified, use non-reversible
						// filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
						}
						else
						{
							// Reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line");
						}
					}
				}
			}
		}
Exemplo n.º 42
0
		/// <summary> Locates the member via a dotted name starting at the given id.
		/// It will traverse any and all proto chains if necc. to find the name.
		/// </summary>
		internal virtual Value locate(int startingId, String dottedName, bool traverseProto)
		{
			if (dottedName == null) return null;
			// first rip apart the dottedName
			SupportClass.Tokenizer names = new SupportClass.Tokenizer(dottedName, "."); //$NON-NLS-1$
			Value val = Session.getValue(startingId);
            while (names.HasMoreTokens() && val != null)
            {
                val = locateForNamed(val.Id, names.NextToken(), traverseProto).getValue();
            }
			return val;
		}
Exemplo n.º 43
0
		//*************************************************************************
		// connect methods
		//*************************************************************************
		
		/// <summary> 
		/// Connects to the specified host and port.
		/// 
		/// If this LdapConnection object represents an open connection, the
		/// connection is closed first before the new connection is opened.
		/// At this point, there is no authentication, and any operations are
		/// conducted as an anonymous client.
		/// 
		///  When more than one host name is specified, each host is contacted
		/// in turn until a connection can be established.
		/// 
		/// </summary>
		/// <param name="host">A host name or a dotted string representing the IP address
		/// of a host running an Ldap server. It may also
		/// contain a list of host names, space-delimited. Each host
		/// name can include a trailing colon and port number.
		/// 
		/// </param>
		/// <param name="port">The TCP or UDP port number to connect to or contact.
		/// The default Ldap port is 389. The port parameter is
		/// ignored for any host hame which includes a colon and
		/// port number.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// 
		/// </exception>
		public virtual void  Connect(System.String host, int port)
		{
			// connect doesn't affect other clones
			// If not a clone, destroys old connection.
			// Step through the space-delimited list
			SupportClass.Tokenizer hostList = new SupportClass.Tokenizer(host, " ");
			System.String address = null;
			
			int specifiedPort;
			int colonIndex; //after the colon is the port
			while (hostList.HasMoreTokens())
			{
				try
				{
					specifiedPort = port;
					address = hostList.NextToken();
					colonIndex = address.IndexOf((System.Char) ':');
					if (colonIndex != - 1 && colonIndex + 1 != address.Length)
					{
						//parse Port out of address
						try
						{
							specifiedPort = System.Int32.Parse(address.Substring(colonIndex + 1));
							address = address.Substring(0, (colonIndex) - (0));
						}
						catch (System.Exception e)
						{
							throw new System.ArgumentException(ExceptionMessages.INVALID_ADDRESS);
						}
					}
					// This may return a different conn object
					// Disassociate this clone with the underlying connection.
					conn = conn.destroyClone(true);
					conn.connect(address, specifiedPort);
					break;
				}
				catch (LdapException LE)
				{
					if (!hostList.HasMoreTokens())
						throw LE;
				}
			}
			return ;
		}
Exemplo n.º 44
0
    private static ArrayList[] predict(System.IO.StreamReader input, System.IO.StreamWriter output, svm_model model, int predict_probability)
    {
        //int correct = 0;
        //int total = 0;
        //double error = 0;
        //double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
        ArrayList[] arrResult = new ArrayList[2];//Mảng thứ 1 chứa kết quả thực sự, mảng thứ 2 chứa kết quả dự đoán
        arrResult[0] = new ArrayList();
        arrResult[1] = new ArrayList();

        int svm_type = svm.svm_get_svm_type(model);
        int nr_class = svm.svm_get_nr_class(model);
        int[] labels = new int[nr_class];
        double[] prob_estimates = null;

        if (predict_probability == 1)
        {
            if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
            {
                System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
            }
            else
            {
                svm.svm_get_labels(model, labels);
                prob_estimates = new double[nr_class];
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("labels");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(" " + labels[j]);
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
        }
        #region [Thêm] Lấy thông tin tiền xử lý từ dòng đầu của file test
        System.String strPreprocess = input.ReadLine();
        #endregion

        while (true)
        {
            System.String line = input.ReadLine();
            if ((System.Object)line == null)
                break;

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

            double target = atof(st.NextToken());
            int m = st.Count / 2;
            svm_node[] x = new svm_node[m];
            for (int j = 0; j < m; j++)
            {
                x[j] = new svm_node();
                x[j].index = atoi(st.NextToken());
                x[j].value_Renamed = atof(st.NextToken());
            }

            double v;
            if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
            {
                v = svm.svm_predict_probability(model, x, prob_estimates);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(v + " ");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(prob_estimates[j] + " ");
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
            else
            {
                v = svm.svm_predict(model, x);
                #region [Thêm] Chuyển về dữ liệu nguyên thủy dựa vào cách tiền xử lý
                string[] strItems = strPreprocess.Split(' ');
                double dblMin;
                double dblMax;
                double dblDiff;
                switch (strItems[0])
                {
                    case "ScaleByMinMax":
                        dblMin = Convert.ToDouble(strItems[1]);
                        dblMax = Convert.ToDouble(strItems[2]);
                        dblDiff = dblMax - dblMin;
                        v = v * dblDiff + dblMin;
                        target = target * dblDiff + dblMin;
                        break;
                    default:
                        break;
                }
                #endregion
                arrResult[0].Add(target);
                arrResult[1].Add(v);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(target + " " + v + "\n");
            }
            //#region [Thêm] Chuyển về dữ liệu nguyên thủy dựa vào cách tiền xử lý
            //string[] strItems = strPreprocess.Split(' ');
            //switch (strItems[0])
            //{
            //    case "Scale(0,1)":
            //        double dblMin = Convert.ToDouble(strItems[1]);
            //        double dblMax = Convert.ToDouble(strItems[2]);
            //        double dblDiff = dblMax - dblMin;
            //        v = (v - 0.15) * dblDiff / 0.7 + dblMin;
            //        target = (target - 0.15) * dblDiff / 0.7 + dblMin;
            //        break;
            //    default:
            //        break;
            //}
            //#endregion
            //arrResult[0].Add(target);
            //arrResult[1].Add(v);
            //if (v == target)
            //    ++correct;
            //error += (v - target) * (v - target);
            //sumv += v;
            //sumy += target;
            //sumvv += v * v;
            //sumyy += target * target;
            //sumvy += v * target;
            //++total;
        }
        return arrResult;
        //System.Console.Out.Write("Accuracy = " + (double) correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
        //System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
        //System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
    }
Exemplo n.º 45
0
		/// <summary> Extracts the subtypes from the specified attribute name.
		/// 
		/// For example, if the attribute name is cn;lang-ja;phonetic,
		/// this method returns an array containing lang-ja and phonetic.
		/// 
		/// </summary>
		/// <param name="attrName">  Name of the attribute from which to extract
		/// the subtypes.
		/// 
		/// </param>
		/// <returns> An array subtypes or null if the attribute has none.
		/// 
		/// @throws IllegalArgumentException if attrName is null
		/// </returns>
		public static System.String[] getSubtypes(System.String attrName)
		{
			if ((System.Object) attrName == null)
			{
				throw new System.ArgumentException("Attribute name cannot be null");
			}
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";");
			System.String[] subTypes = null;
			int cnt = st.Count;
			if (cnt > 0)
			{
				st.NextToken(); // skip over basename
				subTypes = new System.String[cnt - 1];
				int i = 0;
				while (st.HasMoreTokens())
				{
					subTypes[i++] = st.NextToken();
				}
			}
			return subTypes;
		}
Exemplo n.º 46
0
        /// <summary> Constructs a new 'IntegerSpec' for the specified number of tiles and
        /// components, the allowed specifications type and the ParameterList
        /// instance. This constructor is normally called at encoder side and parse
        /// arguments of specified option.
        ///
        /// </summary>
        /// <param name="nt">The number of tiles
        ///
        /// </param>
        /// <param name="nc">The number of components
        ///
        /// </param>
        /// <param name="type">The allowed specifications type
        ///
        /// </param>
        /// <param name="pl">The ParameterList instance
        ///
        /// </param>
        /// <param name="optName">The name of the option to process
        ///
        /// </param>
        public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName) : base(nt, nc, type)
        {
            System.Int32  value_Renamed;
            System.String param = pl.getParameter(optName);

            if (param == null)
            {
                // No parameter specified
                param = pl.DefaultParameterList.getParameter(optName);
                try
                {
                    setDefault((System.Object)System.Int32.Parse(param));
                }
                catch (System.FormatException e)
                {
                    throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
                }
                return;
            }

            // Parse argument
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            System.String          word;    // current word
            byte curSpecType = SPEC_DEF;    // Specification type of the

            // current parameter
            bool[] tileSpec = null;             // Tiles concerned by the specification
            bool[] compSpec = null;             // Components concerned by the specification

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {
                case 't':                          // Tiles specification
                    tileSpec = parseIdx(word, nTiles);
                    if (curSpecType == SPEC_COMP_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_TILE_DEF;
                    }
                    break;

                case 'c':                          // Components specification
                    compSpec = parseIdx(word, nComp);
                    if (curSpecType == SPEC_TILE_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_COMP_DEF;
                    }
                    break;

                default:
                    try
                    {
                        value_Renamed = System.Int32.Parse(word);
                    }
                    catch (System.FormatException e)
                    {
                        throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word);
                    }

                    if (curSpecType == SPEC_DEF)
                    {
                        setDefault((System.Object)value_Renamed);
                    }
                    else if (curSpecType == SPEC_TILE_DEF)
                    {
                        for (int i = tileSpec.Length - 1; i >= 0; i--)
                        {
                            if (tileSpec[i])
                            {
                                setTileDef(i, (System.Object)value_Renamed);
                            }
                        }
                    }
                    else if (curSpecType == SPEC_COMP_DEF)
                    {
                        for (int i = compSpec.Length - 1; i >= 0; i--)
                        {
                            if (compSpec[i])
                            {
                                setCompDef(i, (System.Object)value_Renamed);
                            }
                        }
                    }
                    else
                    {
                        for (int i = tileSpec.Length - 1; i >= 0; i--)
                        {
                            for (int j = compSpec.Length - 1; j >= 0; j--)
                            {
                                if (tileSpec[i] && compSpec[j])
                                {
                                    setTileCompVal(i, j, (System.Object)value_Renamed);
                                }
                            }
                        }
                    }

                    // Re-initialize
                    curSpecType = SPEC_DEF;
                    tileSpec    = null;
                    compSpec    = null;
                    break;
                }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, it takes
                // the default value defined in ParameterList
                if (ndefspec != 0)
                {
                    param = pl.DefaultParameterList.getParameter(optName);
                    try
                    {
                        setDefault((System.Object)System.Int32.Parse(param));
                    }
                    catch (System.FormatException e)
                    {
                        throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
                    }
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {
                    case SPEC_TILE_DEF:
                        for (int c = nc - 1; c >= 0; c--)
                        {
                            if (specValType[0][c] == SPEC_TILE_DEF)
                            {
                                specValType[0][c] = SPEC_DEF;
                            }
                        }
                        tileDef[0] = null;
                        break;

                    case SPEC_COMP_DEF:
                        for (int t = nt - 1; t >= 0; t--)
                        {
                            if (specValType[t][0] == SPEC_COMP_DEF)
                            {
                                specValType[t][0] = SPEC_DEF;
                            }
                        }
                        compDef[0] = null;
                        break;

                    case SPEC_TILE_COMP:
                        specValType[0][0]   = SPEC_DEF;
                        tileCompVal["t0c0"] = null;
                        break;
                    }
                }
            }
        }
Exemplo n.º 47
0
		/// <summary> Constructs a new 'GuardBitsSpec' for the specified number of components
		/// and tiles and the arguments of "-Qguard_bits" option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public GuardBitsSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qguard_bits");
			if (param == null)
			{
				throw new System.ArgumentException("Qguard_bits option not " + "specified");
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			System.Int32 value_Renamed; // value of the guard bits
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					default:  // Step size value
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "-Qguard_bits option" + " : " + word);
						}
						
						if ((float) value_Renamed <= 0.0f)
						{
							throw new System.ArgumentException("Guard bits value " + "must be positive : " + value_Renamed);
						}
						
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					setDefault((System.Object) System.Int32.Parse(pl.DefaultParameterList.getParameter("Qguard_bits")));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Exemplo n.º 48
0
		/// <summary> Returns the query portion of the URL, broken up into individual key/value
		/// pairs. Does NOT unescape the keys and values.
		/// </summary>
		public virtual LinkedHashMap getParameterMap()
		{
            LinkedHashMap map;
			
			SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&"); //$NON-NLS-1$
			// multiply by 2 to create a sufficiently large HashMap
			map = new LinkedHashMap(tokens.Count * 2);
			
			while (tokens.HasMoreTokens())
			{
				String nameValuePair = tokens.NextToken();
				String name = nameValuePair;
				String value = ""; //$NON-NLS-1$
				int equalsIndex = nameValuePair.IndexOf('=');
				if (equalsIndex != - 1)
				{
					name = nameValuePair.Substring(0, (equalsIndex) - (0));
					if (name.Length > 0)
					{
						value = nameValuePair.Substring(equalsIndex + 1);
					}
				}
				map.Add(name, value);
			}
			
			return map;
		}
Exemplo n.º 49
0
	// read in a problem (in svmlight format)
	
	private void  read_problem()
	{
		/* UPGRADE_TODO: Expected value of parameters of constructor
		 * 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET.
		 * 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"'
		 */
		System.IO.StreamReader fp = new System.IO.StreamReader(input_file_name);
		System.Collections.ArrayList vy = new System.Collections.ArrayList(10);
		System.Collections.ArrayList vx = new System.Collections.ArrayList(10);
		int max_index = 0;
		
		while (true)
		{
			System.String line = fp.ReadLine();
			if ((System.Object) line == null)
				break;
			
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");
			
			vy.Add(st.NextToken());
			int m = st.Count / 2;
			svm_node[] x = new svm_node[m];
			for (int j = 0; j < m; j++)
			{
				x[j] = new svm_node();
				x[j].index = atoi(st.NextToken());
				x[j].value_Renamed = atof(st.NextToken());
			}
			if (m > 0)
				max_index = System.Math.Max(max_index, x[m - 1].index);
			vx.Add(x);
		}
		
		prob = new svm_problem();
		prob.l = vy.Count;
		prob.x = new svm_node[prob.l][];
		for (int i = 0; i < prob.l; i++)
			prob.x[i] = (svm_node[]) vx[i];
		prob.y = new double[prob.l];
		for (int i = 0; i < prob.l; i++)
			prob.y[i] = atof((System.String) vy[i]);
		
		if (param.gamma == 0)
			param.gamma = 1.0 / max_index;
		
		fp.Close();
	}
Exemplo n.º 50
0
	/// <summary>
	/// Hacky method to figure out the relative path
	/// that we are currently in. This is good for getting
	/// the relative path for images and anchor's.
	/// </summary>
	private String getRelativePath(String file) {
	    if (file == null || file.Length == 0)
		return "";
	    SupportClass.Tokenizer st = new SupportClass.Tokenizer(file, "/\\");
	    // needs to be -1 cause ST returns 1 even if there are no matches. huh?
	    int slashCount = st.Count - 1;
	    System.Text.StringBuilder sb = new System.Text.StringBuilder();
	    for (int i = 0; i < slashCount; i++) {
		sb.Append("../");
	    }

	    if (sb.ToString().Length > 0) {
		return StringUtils.chop(sb.ToString(), 1);
	    } else {
		return ".";
	    }
	}
Exemplo n.º 51
0
        public static svm_model svm_load_model(System.String model_file_name)
        {
            //UPGRADE_TODO: The differences in the expected value  of parameters for constructor 'java.io.BufferedReader.BufferedReader'  may cause compilation errors.  'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"'
            //UPGRADE_WARNING: At least one expression was used more than once in the target code. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1181_3"'
            //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_3"'
            /*Original System.IO.StreamReader fp = new System.IO.StreamReader(new System.IO.StreamReader(model_file_name, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(model_file_name, System.Text.Encoding.Default).CurrentEncoding);*/
            System.IO.StreamReader fp = new System.IO.StreamReader(new System.IO.FileStream(model_file_name, System.IO.FileMode.Open));

            // read parameters

            svm_model model = new svm_model();
            svm_parameter param = new svm_parameter();
            model.param = param;
            model.rho = null;
            model.probA = null;
            model.probB = null;
            model.label = null;
            model.nSV = null;

            while (true)
            {
                System.String cmd = fp.ReadLine();
                System.String arg = cmd.Substring(cmd.IndexOf((System.Char) ' ') + 1);

                if (cmd.StartsWith("svm_type"))
                {
                    int i;
                    for (i = 0; i < svm_type_table.Length; i++)
                    {
                        if (arg.IndexOf(svm_type_table[i]) != - 1)
                        {
                            param.svm_type = i;
                            break;
                        }
                    }
                    if (i == svm_type_table.Length)
                    {
                        System.Console.Error.Write("unknown svm type.\n");
                        return null;
                    }
                }
                else if (cmd.StartsWith("kernel_type"))
                {
                    int i;
                    for (i = 0; i < kernel_type_table.Length; i++)
                    {
                        if (arg.IndexOf(kernel_type_table[i]) != - 1)
                        {
                            param.kernel_type = i;
                            break;
                        }
                    }
                    if (i == kernel_type_table.Length)
                    {
                        System.Console.Error.Write("unknown kernel function.\n");
                        return null;
                    }
                }
                else if (cmd.StartsWith("degree"))
                    param.degree = atof(arg);
                else if (cmd.StartsWith("gamma"))
                    param.gamma = atof(arg);
                else if (cmd.StartsWith("coef0"))
                    param.coef0 = atof(arg);
                else if (cmd.StartsWith("nr_class"))
                    model.nr_class = atoi(arg);
                else if (cmd.StartsWith("total_sv"))
                    model.l = atoi(arg);
                else if (cmd.StartsWith("rho"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.rho = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.rho[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("label"))
                {
                    int n = model.nr_class;
                    model.label = new int[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.label[i] = atoi(st.NextToken());
                }
                else if (cmd.StartsWith("probA"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.probA = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.probA[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("probB"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.probB = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.probB[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("nr_sv"))
                {
                    int n = model.nr_class;
                    model.nSV = new int[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.nSV[i] = atoi(st.NextToken());
                }
                else if (cmd.StartsWith("SV"))
                {
                    break;
                }
                else
                {
                    System.Console.Error.Write("unknown text in model file\n");
                    return null;
                }
            }

            // read sv_coef and SV

            int m = model.nr_class - 1;
            int l = model.l;
            model.sv_coef = new double[m][];
            for (int i = 0; i < m; i++)
            {
                model.sv_coef[i] = new double[l];
            }
            model.SV = new svm_node[l][];

            for (int i = 0; i < l; i++)
            {
                System.String line = fp.ReadLine();
                SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

                for (int k = 0; k < m; k++)
                    model.sv_coef[k][i] = atof(st.NextToken());
                int n = st.Count / 2;
                model.SV[i] = new svm_node[n];
                for (int j = 0; j < n; j++)
                {
                    model.SV[i][j] = new svm_node();
                    model.SV[i][j].index = atoi(st.NextToken());
                    model.SV[i][j].value = atof(st.NextToken());
                }
            }

            fp.Close();
            return model;
        }
Exemplo n.º 52
0
	private static void  predict(System.IO.StreamReader input, System.IO.BinaryWriter output, svm_model model, int predict_probability)
	{
		int correct = 0;
		int total = 0;
		double error = 0;
		double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
		
		int svm_type = svm.svm_get_svm_type(model);
		int nr_class = svm.svm_get_nr_class(model);
		int[] labels = new int[nr_class];
		double[] prob_estimates = null;
		
		if (predict_probability == 1)
		{
			if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
			{
				System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
			}
			else
			{
				svm.svm_get_labels(model, labels);
				prob_estimates = new double[nr_class];
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("labels");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(" " + labels[j]);
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
		}
		while (true)
		{
			System.String line = input.ReadLine();
			if ((System.Object) line == null)
				break;
			
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");
			
			double target = atof(st.NextToken());
			int m = st.Count / 2;
			svm_node[] x = new svm_node[m];
			for (int j = 0; j < m; j++)
			{
				x[j] = new svm_node();
				x[j].index = atoi(st.NextToken());
				x[j].value = atof(st.NextToken());
			}
			
			double v;
			if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
			{
				v = svm.svm_predict_probability(model, x, prob_estimates);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + " ");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(prob_estimates[j] + " ");
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
			else
			{
				v = svm.svm_predict(model, x);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + "\n");
			}
			
			if (v == target)
				++correct;
			error += (v - target) * (v - target);
			sumv += v;
			sumy += target;
			sumvv += v * v;
			sumyy += target * target;
			sumvy += v * target;
			++total;
		}
		System.Console.Out.Write("Accuracy = " + (double) correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
		System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
		System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
	}
Exemplo n.º 53
0
        /// <summary> Creates a new CBlkSizeSpec object for the specified number of tiles and
        /// components and the ParameterList instance.
        ///
        /// </summary>
        /// <param name="nt">The number of tiles
        ///
        /// </param>
        /// <param name="nc">The number of components
        ///
        /// </param>
        /// <param name="type">the type of the specification module i.e. tile specific,
        /// component specific or both.
        ///
        /// </param>
        /// <param name="imgsrc">The image source (used to get the image size)
        ///
        /// </param>
        /// <param name="pl">The ParameterList instance
        ///
        /// </param>
        public CBlkSizeSpec(int nt, int nc, byte type, ParameterList pl) : base(nt, nc, type)
        {
            bool firstVal = true;

            System.String param = pl.getParameter(optName);

            // Precinct partition is used : parse arguments
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType           = SPEC_DEF;   // Specification type of the

            // current parameter
            bool[] tileSpec = null;      // Tiles concerned by the specification
            bool[] compSpec = null;      // Components concerned by the specification
            int    ci, ti;               //  i, xIdx removed

            System.String word   = null; // current word
            System.String errMsg = null;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {
                case 't':                          // Tiles specification
                    tileSpec = parseIdx(word, nTiles);
                    if (curSpecType == SPEC_COMP_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_TILE_DEF;
                    }
                    break;


                case 'c':                          // Components specification
                    compSpec = parseIdx(word, nComp);
                    if (curSpecType == SPEC_TILE_DEF)
                    {
                        curSpecType = SPEC_TILE_COMP;
                    }
                    else
                    {
                        curSpecType = SPEC_COMP_DEF;
                    }
                    break;


                default:
                    if (!System.Char.IsDigit(word[0]))
                    {
                        errMsg = "Bad construction for parameter: " + word;
                        throw new System.ArgumentException(errMsg);
                    }
                    System.Int32[] dim = new System.Int32[2];
                    // Get code-block's width
                    try
                    {
                        dim[0] = System.Int32.Parse(word);
                        // Check that width is not >
                        // StdEntropyCoderOptions.MAX_CB_DIM
                        if (dim[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "width cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
                            throw new System.ArgumentException(errMsg);
                        }
                        // Check that width is not <
                        // StdEntropyCoderOptions.MIN_CB_DIM
                        if (dim[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "width cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
                            throw new System.ArgumentException(errMsg);
                        }
                        // Check that width is a power of 2
                        if (dim[0] != (1 << MathUtil.log2(dim[0])))
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "width must be a power of 2";
                            throw new System.ArgumentException(errMsg);
                        }
                    }
                    catch (System.FormatException)
                    {
                        errMsg = "'" + optName + "' option : the code-block's " + "width could not be parsed.";
                        throw new System.ArgumentException(errMsg);
                    }
                    // Get the next word in option
                    try
                    {
                        word = stk.NextToken();
                    }
                    catch (System.ArgumentOutOfRangeException)
                    {
                        errMsg = "'" + optName + "' option : could not parse the " + "code-block's height";
                        throw new System.ArgumentException(errMsg);
                    }
                    // Get the code-block's height
                    try
                    {
                        dim[1] = System.Int32.Parse(word);
                        // Check that height is not >
                        // StdEntropyCoderOptions.MAX_CB_DIM
                        if (dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "height cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
                            throw new System.ArgumentException(errMsg);
                        }
                        // Check that height is not <
                        // StdEntropyCoderOptions.MIN_CB_DIM
                        if (dim[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "height cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
                            throw new System.ArgumentException(errMsg);
                        }
                        // Check that height is a power of 2
                        if (dim[1] != (1 << MathUtil.log2(dim[1])))
                        {
                            errMsg = "'" + optName + "' option : the code-block's " + "height must be a power of 2";
                            throw new System.ArgumentException(errMsg);
                        }
                        // Check that the code-block 'area' (i.e. width*height) is
                        // not greater than StdEntropyCoderOptions.MAX_CB_AREA
                        if (dim[0] * dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA)
                        {
                            errMsg = "'" + optName + "' option : The " + "code-block's area (i.e. width*height) " + "cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA;
                            throw new System.ArgumentException(errMsg);
                        }
                    }
                    catch (System.FormatException)
                    {
                        errMsg = "'" + optName + "' option : the code-block's height " + "could not be parsed.";
                        throw new System.ArgumentException(errMsg);
                    }

                    // Store the maximum dimensions if necessary
                    if (dim[0] > maxCBlkWidth)
                    {
                        maxCBlkWidth = dim[0];
                    }

                    if (dim[1] > maxCBlkHeight)
                    {
                        maxCBlkHeight = dim[1];
                    }

                    if (firstVal)
                    {
                        // This is the first time a value is given so we set it as
                        // the default one
                        setDefault((System.Object)(dim));
                        firstVal = false;
                    }

                    switch (curSpecType)
                    {
                    case SPEC_DEF:
                        setDefault((System.Object)(dim));
                        break;

                    case SPEC_TILE_DEF:
                        for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                        {
                            if (tileSpec[ti])
                            {
                                setTileDef(ti, (System.Object)(dim));
                            }
                        }
                        break;

                    case SPEC_COMP_DEF:
                        for (ci = compSpec.Length - 1; ci >= 0; ci--)
                        {
                            if (compSpec[ci])
                            {
                                setCompDef(ci, (System.Object)(dim));
                            }
                        }
                        break;

                    default:
                        for (ti = tileSpec.Length - 1; ti >= 0; ti--)
                        {
                            for (ci = compSpec.Length - 1; ci >= 0; ci--)
                            {
                                if (tileSpec[ti] && compSpec[ci])
                                {
                                    setTileCompVal(ti, ci, (System.Object)(dim));
                                }
                            }
                        }
                        break;
                    }
                    break;
                }                 // end switch
            }
        }
Exemplo n.º 54
0
		/// <summary> Constructs a new 'ForwCompTransfSpec' for the specified number of
		/// components and tiles, the wavelet filters type and the parameter of the
		/// option 'Mct'. This constructor is called by the encoder. It also checks
		/// that the arguments belong to the recognized arguments list.
		/// 
		/// <p>This constructor chose the component transformation type depending
		/// on the wavelet filters : RCT with w5x3 filter and ICT with w9x7
		/// filter. Note: All filters must use the same data type.</p>
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="wfs">The wavelet filter specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public ForwCompTransfSpec(int nt, int nc, byte type, AnWTFilterSpec wfs, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Mct");
			
			if (param == null)
			{
				// The option has not been specified
				
				// If less than three component, do not use any component
				// transformation 
				if (nc < 3)
				{
					setDefault("none");
					return ;
				}
				// If the compression is lossless, uses RCT
				else if (pl.getBooleanParameter("lossless"))
				{
					setDefault("rct");
					return ;
				}
				else
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three first components use the same filters
					bool reject = false;
					for (int c = 1; c < 3; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setDefault("none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setDefault("ict");
						}
						else
						{
							setDefault("rct");
						}
					}
				}
				
				// Each tile receives a component transform specification
				// according the type of wavelet filters that are used by the
				// three first components
				for (int t = 0; t < nt; t++)
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the
			// specification
			//System.Boolean value_Renamed;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						throw new System.ArgumentException("Component specific " + " parameters" + " not allowed with " + "'-Mct' option");
					
					default: 
						if (word.Equals("off"))
						{
							if (curSpecType == SPEC_DEF)
							{
								setDefault("none");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
									if (tileSpec[i])
									{
										setTileDef(i, "none");
									}
							}
						}
						else if (word.Equals("on"))
						{
							if (nc < 3)
							{
								throw new System.ArgumentException("Cannot use component" + " transformation on a " + "image with less than " + "three components");
							}
							
							if (curSpecType == SPEC_DEF)
							{
								// Set arbitrarily the default
								// value to RCT (later will be found the suitable
								// component transform for each tile)
								setDefault("rct");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
								{
									if (tileSpec[i])
									{
										if (getFilterType(i, wfs) == CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3)
										{
											setTileDef(i, "rct");
										}
										else
										{
											setTileDef(i, "ict");
										}
									}
								}
							}
						}
						else
						{
							throw new System.ArgumentException("Default parameter of " + "option Mct not" + " recognized: " + param);
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				// If not, set arbitrarily the default value to 'none' but
				// specifies explicitely a default value for each tile depending
				// on the wavelet transform that is used
				setDefault("none");
				
				for (int t = 0; t < nt; t++)
				{
					if (isTileSpecified(t))
					{
						continue;
					}
					
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
			}
			
			// Check validity of component transformation of each tile compared to
			// the filter used.
			for (int t = nt - 1; t >= 0; t--)
			{
				
				if (((System.String) getTileDef(t)).Equals("none"))
				{
					// No comp. transf is used. No check is needed
					continue;
				}
				else if (((System.String) getTileDef(t)).Equals("rct"))
				{
					// Tile is using Reversible component transform
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // OK
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // Must use ICT
							if (isTileSpecified(t))
							{
								// User has requested RCT -> Error
								throw new System.ArgumentException("Cannot use RCT " + "with 9x7 filter " + "in tile " + t);
							}
							else
							{
								// Specify ICT for this tile
								setTileDef(t, "ict");
							}
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
				else
				{
					// ICT
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // Must use RCT
							if (isTileSpecified(t))
							{
								// User has requested ICT -> Error
								throw new System.ArgumentException("Cannot use ICT " + "with filter 5x3 " + "in tile " + t);
							}
							else
							{
								setTileDef(t, "rct");
							}
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // OK
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
			}
		}
Exemplo n.º 55
0
		/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles
		/// and components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl):base(nt, nc, type)
		{
			
			this.dls = dls;
			
			// The precinct sizes are stored in a 2 elements vector array, the
			// first element containing a vector for the precincts width for each
			// resolution level and the second element containing a vector for the
			// precincts height for each resolution level. The precincts sizes are
			// specified from the highest resolution level to the lowest one
			// (i.e. 0).  If there are less elements than the number of
			// decomposition levels, the last element is used for all remaining
			// resolution levels (i.e. if the precincts sizes are specified only
			// for resolutions levels 5, 4 and 3, then the precincts size for
			// resolution levels 2, 1 and 0 will be the same as the size used for
			// resolution level 3).
			
			// Boolean used to know if we were previously reading a precinct's 
			// size or if we were reading something else.
			bool wasReadingPrecinctSize = false;
			
			System.String param = pl.getParameter(optName);
			
			// Set precinct sizes to default i.e. 2^15 =
			// Markers.PRECINCT_PARTITION_DEF_SIZE
			System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2];
			tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
			tmpv[0].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
			tmpv[1].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			setDefault(tmpv);
			
			if (param == null)
			{
				// No precinct size specified in the command line so we do not try 
				// to parse it.
				return ;
			}
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //i, xIdx removed
			
			bool endOfParamList = false;
			System.String word = null; // current word
			System.Int32 w, h;
			System.String errMsg = null;
			
			while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList)
			{
				
				System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy
				
				// We do not read the next token if we were reading a precinct's
				// size argument as we have already read the next token into word.
				if (!wasReadingPrecinctSize)
				{
					word = stk.NextToken();
				}
				
				wasReadingPrecinctSize = false;
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						
						// Initialises Vector objects
						v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
						v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
						
						while (true)
						{
							
							// Now get the precinct dimensions
							try
							{
								// Get precinct width
								w = System.Int32.Parse(word);
								
								// Get next word in argument list
								try
								{
									word = stk.NextToken();
								}
								catch (System.ArgumentOutOfRangeException)
								{
									errMsg = "'" + optName + "' option : could not " + "parse the precinct's width";
									throw new System.ArgumentException(errMsg);
								}
								// Get precinct height
								h = System.Int32.Parse(word);
								if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h)))
								{
									errMsg = "Precinct dimensions must be powers of 2";
									throw new System.ArgumentException(errMsg);
								}
							}
							catch (System.FormatException)
							{
								errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed.";
								throw new System.ArgumentException(errMsg);
							}
							// Store packet's dimensions in Vector arrays
							v[0].Add(w);
							v[1].Add(h);
							
							// Try to get the next token
							if (stk.HasMoreTokens())
							{
								word = stk.NextToken();
								if (!System.Char.IsDigit(word[0]))
								{
									// The next token does not start with a digit so
									// it is not a precinct's size argument. We set
									// the wasReadingPrecinctSize booleen such that we
									// know that we don't have to read another token
									// and check for the end of the parameters list.
									wasReadingPrecinctSize = true;
									
									if (curSpecType == SPEC_DEF)
									{
										setDefault(v);
									}
									else if (curSpecType == SPEC_TILE_DEF)
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											if (tileSpec[ti])
											{
												setTileDef(ti, v);
											}
										}
									}
									else if (curSpecType == SPEC_COMP_DEF)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (compSpec[ci])
											{
												setCompDef(ci, v);
											}
										}
									}
									else
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											for (ci = compSpec.Length - 1; ci >= 0; ci--)
											{
												if (tileSpec[ti] && compSpec[ci])
												{
													setTileCompVal(ti, ci, v);
												}
											}
										}
									}
									// Re-initialize
									curSpecType = SPEC_DEF;
									tileSpec = null;
									compSpec = null;
									
									// Go back to 'normal' parsing
									break;
								}
								else
								{
									// Next token starts with a digit so read it
								}
							}
							else
							{
								// We have reached the end of the parameters list so
								// we store the last precinct's sizes and we stop
								if (curSpecType == SPEC_DEF)
								{
									setDefault(v);
								}
								else if (curSpecType == SPEC_TILE_DEF)
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										if (tileSpec[ti])
										{
											setTileDef(ti, v);
										}
									}
								}
								else if (curSpecType == SPEC_COMP_DEF)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (compSpec[ci])
										{
											setCompDef(ci, v);
										}
									}
								}
								else
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (tileSpec[ti] && compSpec[ci])
											{
												setTileCompVal(ti, ci, v);
											}
										}
									}
								}
								endOfParamList = true;
								break;
							}
						} // while (true)
						break;
					
				} // switch
			} // while
		}
Exemplo n.º 56
0
		/// <param name="theMessage">an HL7 message from which data are to be queried 
		/// </param>
		/// <param name="theQuery">the query (see class docs for syntax)
		/// </param>
		/// <returns> data from the message that are selected by the query 
		/// </returns>
		public static NuGenMessageQuery.Result query(Message theMessage, System.String theQuery)
		{
			System.Collections.Specialized.NameValueCollection clauses = getClauses(theQuery);
			
			//parse select clause
			SupportClass.Tokenizer select = new SupportClass.Tokenizer(clauses.Get("select"), ", ", false);
			System.Collections.ArrayList fieldPaths = new System.Collections.ArrayList(10);
			System.Collections.Hashtable names = new System.Collections.Hashtable(10);
			while (select.HasMoreTokens())
			{
				System.String token = select.NextToken();
				if (token.Equals("as"))
				{
					if (!select.HasMoreTokens())
					{
						throw new System.ArgumentException("Keyword 'as' must be followed by a field label");
					}
					names[select.NextToken()] = (System.Int32) (fieldPaths.Count - 1);
				}
				else
				{
					fieldPaths.Add(token);
				}
			}
			
			//parse loop clause 
			SupportClass.Tokenizer loop = new SupportClass.Tokenizer(clauses["loop"] == null?"":clauses["loop"], ",", false);
			System.Collections.ArrayList loopPoints = new System.Collections.ArrayList(10);
			System.Collections.Hashtable loopPointNames = new System.Collections.Hashtable(10);
			while (loop.HasMoreTokens())
			{
				System.String pointDecl = loop.NextToken();
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pointDecl, "=", false);
				System.String name = tok.NextToken().Trim();
				System.String path = tok.NextToken().Trim();
				loopPoints.Add(path);
				loopPointNames[name] = (System.Int32) (loopPoints.Count - 1);
			}
			
			//parse where clause 
			//TODO: this will do for now but it should really be evaluated like an expression 
			//rather than a list  
			SupportClass.Tokenizer where = new SupportClass.Tokenizer(clauses["where"] == null?"":clauses["where"], ",", false);
			System.Collections.ArrayList filters = new System.Collections.ArrayList();
			while (where.HasMoreTokens())
			{
				filters.Add(where.NextToken());
			}
			System.String[] filterPaths = new System.String[filters.Count];
			System.String[] filterPatterns = new System.String[filters.Count];
			bool[] exactFlags = new bool[filters.Count];
			
			for (int i = 0; i < filters.Count; i++)
			{
				exactFlags[i] = true;
				System.String filter = (System.String) filters[i];
				System.String[] parts = splitFromEnd(filter, "=");
				if (parts[1] != null)
				{
					parts[1] = parts[1].Substring(1);
				}
				else
				{
					exactFlags[i] = false;
					parts = splitFromEnd(filter, "like");
					parts[1] = parts[1].Substring(4);
				}
				filterPaths[i] = parts[0].Trim();
				parts[1] = parts[1].Trim();
				filterPatterns[i] = parts[1].Substring(1, (parts[1].Length - 1) - (1));
			}

            String[] retVal1 = new String[loopPoints.Count];
            loopPoints.CopyTo(retVal1);

            String[] retVal2 = new String[fieldPaths.Count];
            fieldPaths.CopyTo(retVal2);

			return new ResultImpl(theMessage, retVal1, loopPointNames, retVal2, names, filterPaths, filterPatterns, exactFlags);
		}
        /// <summary> Creates a new PGX file reader from the specified File object.
        ///
        /// </summary>
        /// <param name="in">The input file as File object.
        ///
        /// </param>
        /// <exception cref="IOException">If an I/O error occurs.
        ///
        /// </exception>
        public ImgReaderPGX(System.IO.FileInfo in_Renamed)
        {
            System.String header;

            // Check if specified file exists
            bool tmpBool;

            if (System.IO.File.Exists(in_Renamed.FullName))
            {
                tmpBool = true;
            }
            else
            {
                tmpBool = System.IO.Directory.Exists(in_Renamed.FullName);
            }
            if (!tmpBool)
            {
                throw new System.ArgumentException("PGX file " + in_Renamed.Name + " does not exist");
            }

            //Opens the given file
            this.in_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(in_Renamed, "r");
            try
            {
                System.IO.StreamReader in_reader = new System.IO.StreamReader(this.in_Renamed);
                //UPGRADE_ISSUE: Method 'java.io.RandomAccessFile.readLine' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioRandomAccessFilereadLine'"
                header = in_reader.ReadLine();
            }
            catch (System.IO.IOException)
            {
                throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
            }
            if (header == null)
            {
                throw new System.IO.IOException(in_Renamed.Name + " is an empty file");
            }
            offset = (header.Length + 1);

            //Get informations from header
            SupportClass.Tokenizer st = new SupportClass.Tokenizer(header);
            try
            {
                int nTokens = st.Count;

                // Magic Number
                if (!(st.NextToken()).Equals("PG"))
                {
                    throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
                }

                // Endianess
                System.String tmp = st.NextToken();
                if (tmp.Equals("LM"))
                {
                    byteOrder = CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN;
                }
                else if (tmp.Equals("ML"))
                {
                    byteOrder = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN;
                }
                else
                {
                    throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
                }

                // Unsigned/signed if present in the header
                if (nTokens == 6)
                {
                    tmp = st.NextToken();
                    if (tmp.Equals("+"))
                    {
                        isSigned = false;
                    }
                    else if (tmp.Equals("-"))
                    {
                        isSigned = true;
                    }
                    else
                    {
                        throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
                    }
                }

                // bit-depth, width, height
                try
                {
                    bitDepth = (System.Int32.Parse(st.NextToken()));
                    // bitDepth must be between 1 and 31
                    if ((bitDepth <= 0) || (bitDepth > 31))
                    {
                        throw new System.IO.IOException(in_Renamed.Name + " is not a valid PGX file");
                    }

                    w = (System.Int32.Parse(st.NextToken()));
                    h = (System.Int32.Parse(st.NextToken()));
                }
                catch (System.FormatException)
                {
                    throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
                }
            }
            catch (System.ArgumentOutOfRangeException)
            {
                throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
            }

            // Number of component
            nc = 1;

            // Number of bytes per data
            if (bitDepth <= 8)
            {
                packBytes = 1;
            }
            else if (bitDepth <= 16)
            {
                packBytes = 2;
            }
            // <= 31
            else
            {
                packBytes = 4;
            }
        }
Exemplo n.º 58
0
			//extracts LP# of label between first '{' and first '}', or -1 if there isn't one
			private int getLoopPointReference(System.String thePath)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePath, "{}", false);
				if (thePath.IndexOf('{') >= 0 && tok.HasMoreTokens())
				{
					System.String ref_Renamed = tok.NextToken();
					return ((System.Int32) myLoopPointNames[ref_Renamed]);
				}
				else
				{
					return - 1;
				}
			}
Exemplo n.º 59
0
        /// <summary> Creates a new ProgressionSpec object for the specified number of tiles,
        /// components and the ParameterList instance.
        ///
        /// </summary>
        /// <param name="nt">The number of tiles
        ///
        /// </param>
        /// <param name="nc">The number of components
        ///
        /// </param>
        /// <param name="nl">The number of layer
        ///
        /// </param>
        /// <param name="dls">The number of decomposition levels specifications
        ///
        /// </param>
        /// <param name="type">the type of the specification module. The ProgressionSpec
        /// class should only be used only with the type ModuleSpec.SPEC_TYPE_TILE.
        ///
        /// </param>
        /// <param name="pl">The ParameterList instance
        ///
        /// </param>
        public ProgressionSpec(int nt, int nc, int nl, IntegerSpec dls, byte type, ParameterList pl) : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Aptype");
            Progression[] prog;
            int           mode = -1;

            if (param == null)
            {
                // No parameter specified
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }

                if (mode == -1)
                {
                    System.String errMsg = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg);
                }
                prog    = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return;
            }

            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType           = SPEC_DEF;   // Specification type of the

            // current parameter
            bool[]        tileSpec    = null;  // Tiles concerned by the specification
            System.String word        = null;  // current word
            System.String errMsg2     = null;  // Error message
            bool          needInteger = false; // True if an integer value is expected
            int           intType     = 0;     // Type of read integer value (0=index of first

            // resolution level, 1= index of first component, 2=index of first
            // layer not included, 3= index of first resolution level not
            // included, 4= index of  first component not included
            System.Collections.ArrayList progression = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
            int         tmp     = 0;
            Progression curProg = null;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {
                case 't':
                    // If progression were previously found, store them
                    if (progression.Count > 0)
                    {
                        // Ensure that all information has been taken
                        curProg.ce  = nc;
                        curProg.lye = nl;
                        curProg.re  = dls.Max + 1;
                        prog        = new Progression[progression.Count];
                        progression.CopyTo(prog);
                        if (curSpecType == SPEC_DEF)
                        {
                            setDefault(prog);
                        }
                        else if (curSpecType == SPEC_TILE_DEF)
                        {
                            for (int i = tileSpec.Length - 1; i >= 0; i--)
                            {
                                if (tileSpec[i])
                                {
                                    setTileDef(i, prog);
                                }
                            }
                        }
                    }
                    progression.Clear();
                    intType     = -1;
                    needInteger = false;

                    // Tiles specification
                    tileSpec    = parseIdx(word, nTiles);
                    curSpecType = SPEC_TILE_DEF;
                    break;

                default:
                    // Here, words is either a Integer (progression bound index)
                    // or a String (progression order type). This is determined by
                    // the value of needInteger.
                    if (needInteger)
                    {
                        // Progression bound info
                        try
                        {
                            tmp = (System.Int32.Parse(word));
                        }
                        catch (System.FormatException)
                        {
                            // Progression has missing parameters
                            throw new System.ArgumentException("Progression " + "order" + " specification " + "has missing " + "parameters: " + param);
                        }

                        switch (intType)
                        {
                        case 0:                                          // cs
                            if (tmp < 0 || tmp > (dls.Max + 1))
                            {
                                throw new System.ArgumentException("Invalid res_start " + "in '-Aptype'" + " option: " + tmp);
                            }
                            curProg.rs = tmp; break;

                        case 1:                                          // rs
                            if (tmp < 0 || tmp > nc)
                            {
                                throw new System.ArgumentException("Invalid comp_start " + "in '-Aptype' " + "option: " + tmp);
                            }
                            curProg.cs = tmp; break;

                        case 2:                                          // lye
                            if (tmp < 0)
                            {
                                throw new System.ArgumentException("Invalid layer_end " + "in '-Aptype'" + " option: " + tmp);
                            }
                            if (tmp > nl)
                            {
                                tmp = nl;
                            }
                            curProg.lye = tmp; break;

                        case 3:                                          // ce
                            if (tmp < 0)
                            {
                                throw new System.ArgumentException("Invalid res_end " + "in '-Aptype'" + " option: " + tmp);
                            }
                            if (tmp > (dls.Max + 1))
                            {
                                tmp = dls.Max + 1;
                            }
                            curProg.re = tmp; break;

                        case 4:                                          // re
                            if (tmp < 0)
                            {
                                throw new System.ArgumentException("Invalid comp_end " + "in '-Aptype'" + " option: " + tmp);
                            }
                            if (tmp > nc)
                            {
                                tmp = nc;
                            }
                            curProg.ce = tmp; break;
                        }

                        if (intType < 4)
                        {
                            intType++;
                            needInteger = true;
                            break;
                        }
                        else if (intType == 4)
                        {
                            intType     = 0;
                            needInteger = false;
                            break;
                        }
                        else
                        {
                            throw new System.ApplicationException("Error in usage of 'Aptype' " + "option: " + param);
                        }
                    }

                    if (!needInteger)
                    {
                        // Progression type info
                        mode = checkProgMode(word);
                        if (mode == -1)
                        {
                            errMsg2 = "Unknown progression type : '" + word + "'";
                            throw new System.ArgumentException(errMsg2);
                        }
                        needInteger = true;
                        intType     = 0;
                        if (progression.Count == 0)
                        {
                            curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                        }
                        else
                        {
                            curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                        }
                        progression.Add(curProg);
                    }
                    break;
                }         // switch
            }             // while

            if (progression.Count == 0)
            {
                // No progression defined
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }
                if (mode == -1)
                {
                    errMsg2 = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg2);
                }
                prog    = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return;
            }

            // Ensure that all information has been taken
            curProg.ce  = nc;
            curProg.lye = nl;
            curProg.re  = dls.Max + 1;

            // Store found progression
            prog = new Progression[progression.Count];
            progression.CopyTo(prog);

            if (curSpecType == SPEC_DEF)
            {
                setDefault(prog);
            }
            else if (curSpecType == SPEC_TILE_DEF)
            {
                for (int i = tileSpec.Length - 1; i >= 0; i--)
                {
                    if (tileSpec[i])
                    {
                        setTileDef(i, prog);
                    }
                }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, they
                // receive the default progressiveness.
                if (ndefspec != 0)
                {
                    if (pl.getParameter("Rroi") == null)
                    {
                        mode = checkProgMode("res");
                    }
                    else
                    {
                        mode = checkProgMode("layer");
                    }
                    if (mode == -1)
                    {
                        errMsg2 = "Unknown progression type : '" + param + "'";
                        throw new System.ArgumentException(errMsg2);
                    }
                    prog    = new Progression[1];
                    prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                    setDefault(prog);
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {
                    case SPEC_TILE_DEF:
                        for (int c = nc - 1; c >= 0; c--)
                        {
                            if (specValType[0][c] == SPEC_TILE_DEF)
                            {
                                specValType[0][c] = SPEC_DEF;
                            }
                        }
                        tileDef[0] = null;
                        break;

                    case SPEC_COMP_DEF:
                        for (int t = nt - 1; t >= 0; t--)
                        {
                            if (specValType[t][0] == SPEC_COMP_DEF)
                            {
                                specValType[t][0] = SPEC_DEF;
                            }
                        }
                        compDef[0] = null;
                        break;

                    case SPEC_TILE_COMP:
                        specValType[0][0]   = SPEC_DEF;
                        tileCompVal["t0c0"] = null;
                        break;
                    }
                }
            }
        }
Exemplo n.º 60
0
        /// <summary> Write COM marker segment(s) to the codestream.
        /// 
        /// <p>This marker is currently written in main header and indicates the
        /// JJ2000 encoder's version that has created the codestream.</p>
        /// 
        /// </summary>
        private void writeCOM()
        {
            // JJ2000 COM marker segment
            if (enJJ2KMarkSeg)
            {
                System.String str = "Created by: CSJ2K version " + JJ2KInfo.version;
                int markSegLen; // the marker segment length

                // COM marker
                hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                // Calculate length: Lcom(2) + Rcom (2) + string's length;
                markSegLen = 2 + 2 + str.Length;
                hbuf.Write((System.Int16) markSegLen);

                // Rcom
                hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin) values)

                byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                for (int i = 0; i < chars.Length; i++)
                {
                    hbuf.Write((byte) chars[i]);
                }
            }
            // other COM marker segments
            if (otherCOMMarkSeg != null)
            {
                SupportClass.Tokenizer stk = new SupportClass.Tokenizer(otherCOMMarkSeg, "#");
                while (stk.HasMoreTokens())
                {
                    System.String str = stk.NextToken();
                    int markSegLen; // the marker segment length

                    // COM marker
                    hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                    // Calculate length: Lcom(2) + Rcom (2) + string's length;
                    markSegLen = 2 + 2 + str.Length;
                    hbuf.Write((System.Int16) markSegLen);

                    // Rcom
                    hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin)
                    // values)

                    byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                    for (int i = 0; i < chars.Length; i++)
                    {
                        hbuf.Write((byte) chars[i]);
                    }
                }
            }
        }